Index: trunk/globals.php
===================================================================
diff -u -r13 -r568
--- trunk/globals.php	(.../globals.php)	(revision 13)
+++ trunk/globals.php	(.../globals.php)	(revision 568)
@@ -1,7 +1,6 @@
 <?php
-//global $g_DBType,$g_DBHost,$g_DBUser,$g_DBUserPassword,$g_DBName,$g_EnableCookies;
 
-$vars = parse_ini_file($pathtoroot."config.php");
+$vars = parse_portal_ini($pathtoroot."config.php");
 
 while($key = key($vars))
 {
@@ -17,8 +16,8 @@
 $KeywordIgnore = array();
 global $debuglevel;
 
-$debuglevel=0;
-$_GLOBALS["debuglevel"]=0;
+$debuglevel = 0;
+//$GLOBALS['debuglevel'] = 0;
 
 /*New, Hot, Pop field values */
 define('NEVER', 0);
@@ -33,44 +32,100 @@
 $LogLevel=0;
 $LogFile = NULL;
 
+
+function parse_portal_ini($file, $parse_section = false) { 
+    if(!file_exists($file) && !is_readable($file))  
+        die('Could Not Open Ini File'); 
+     
+    $contents = file($file); 
+     
+    $retval = array(); 
+     
+    $section = ''; 
+    $ln = 1;
+    $resave = false;
+    foreach($contents as $line) { 
+    		if ($ln == 1 && $line != '<'.'?'.'php die() ?'.">\n") {
+    			$resave = true;
+    		}
+    		$ln++;
+        $line = trim($line); 
+        $line = eregi_replace(';[.]*','',$line); 
+        if(strlen($line) > 0) { 
+            //echo $line . " - "; 
+            if(eregi('^[[a-z]+]$',str_replace(' ', '', $line))) { 
+                //echo 'section'; 
+                $section = substr($line,1,(strlen($line)-2)); 
+                if ($parse_section) {
+                	$retval[$section] = array(); 
+                }
+                continue;
+            } elseif(eregi('=',$line)) { 
+                //echo 'main element'; 
+                list($key,$val) = explode(' = ',$line); 
+                if (!$parse_section) {
+                	$retval[trim($key)] = str_replace('"', '', $val); 
+                }
+                else {
+					$retval[$section][trim($key)] = str_replace('"', '', $val);                 	
+                }
+            } //end if 
+            //echo '<br />'; 
+        } //end if 
+    } //end foreach 
+    if ($resave) {
+    	$fp = fopen($file, "w");
+    	reset($contents);
+			fwrite($fp,'<'.'?'.'php die() ?'.">\n\n");
+			foreach($contents as $line) fwrite($fp,"$line");
+			fclose($fp);
+		}   
+    
+    return $retval; 
+}
+
+/**
+ * @return object
+ * @desc Returns reference to database connection
+*/
 function &GetADODBConnection()
 {
-	global $g_adodbConnection, $g_DBType, $g_DBHost,$g_DBUser,$g_DBUserPassword,$g_DBName,$g_DebugMode;
-    global $ADODB_FETCH_MODE,$ADODB_COUNTRECS,$ADODB_CACHE_DIR,$pathtoroot; 
-
-    if(!isset($g_adodbConnection) && strlen($g_DBType)>0)
-    {
-		$g_adodbConnection = ADONewConnection($g_DBType);
-		$connected = $g_adodbConnection->Connect($g_DBHost,$g_DBUser,$g_DBUserPassword,$g_DBName);
-        if(!$connected)
-        {
-            echo "Error connecting to database $g_DBHost <br>\n";
-            die();
-        }
-        $ADODB_CACHE_DIR = $pathtoroot."cache"; 
-        $ADODB_FETCH_MODE = 2;    
-        $ADODB_COUNTRECS = FALSE; 
-        $g_adodbConnection->debug = false;
-        $g_adodbConnection->cacheSecs = 3600;
-    }
-    elseif (!strlen($g_DBType)) {
-    	global $rootURL;
-    	echo "In-Portal is probably not installed, or configuration file is missing.<br>";
-			echo "Please use the installation script to fix the problem.<br><br>";
-			if (!preg_match('/admin/', $_SERVER['SCRIPT_FILENAME'])) {
-				$ins = 'admin/'; 
-			}
-			echo "<a href='$rootURL".$ins."install.php'>Go to installation script</a><br><br>";
-			flush();
-			die();
-    }
-	return $g_adodbConnection;
+	static $DB = null;
+	
+	global $g_DBType, $g_DBHost, $g_DBUser, $g_DBUserPassword, $g_DBName, $g_DebugMode;
+	global $ADODB_FETCH_MODE, $ADODB_COUNTRECS, $ADODB_CACHE_DIR, $pathtoroot;
+	
+	if( !isset($DB) && strlen($g_DBType) > 0 )
+	{
+		$DB = ADONewConnection($g_DBType);
+		$connected = $DB->Connect($g_DBHost, $g_DBUser, $g_DBUserPassword, $g_DBName);
+		if(!$connected) die("Error connecting to database $g_DBHost <br>\n");
+		
+		$ADODB_CACHE_DIR = $pathtoroot."cache";
+		$ADODB_FETCH_MODE = 2;
+		$ADODB_COUNTRECS = false;
+		$DB->debug = defined('ADODB_OUTP') ? 1 : 0;
+		$DB->cacheSecs = 3600;
+		$DB->Execute('SET SQL_BIG_SELECTS = 1');
+	}
+	elseif( !strlen($g_DBType) )
+	{
+		global $rootURL;
+		echo 'In-Portal is probably not installed, or configuration file is missing.<br>';
+		echo 'Please use the installation script to fix the problem.<br><br>';
+		if ( !preg_match('/admin/', __FILE__) ) $ins = 'admin/';
+		
+		echo '<a href="'.$rootURL.$ins.'install.php">Go to installation script</a><br><br>';
+		flush();
+		exit;
+	}
+	return $DB;
 }
 
 function GetNextResourceId($Increment=1)
 {
 	$sql = "UPDATE ".GetTablePrefix()."IdGenerator SET lastid=lastid+".$Increment;
-    $adodbConnection = GetADODBConnection();
+    $adodbConnection = &GetADODBConnection();
     $adodbConnection->Execute($sql);    
     $rs = $adodbConnection->Execute("SELECT lastid FROM ".GetTablePrefix()."IdGenerator");
     $val = $rs->fields["lastid"];
@@ -126,7 +181,7 @@
 
 function TableCount($TableName, $where="",$JoinCats=1)
 {
-    $db = GetADODBConnection();
+    $db = &GetADODBConnection();
     if(!$JoinCats)
     {    
       $sql = "SELECT count(*) as TableCount FROM $TableName";
@@ -135,6 +190,7 @@
         $sql = "SELECT count(*) as TableCount FROM $TableName INNER JOIN ".GetTablePrefix()."CategoryItems ON ".GetTablePrefix()."CategoryItems.ItemResourceId=$TableName.ResourceId";
     if(strlen($where)>0)
         $sql .= " WHERE ".$where;
+   
     $rs = $db->Execute($sql);
         
 //    echo "SQL TABLE COUNT: ".$sql."<br>\n";
@@ -145,17 +201,12 @@
 
 Function QueryCount($sql)
 {
-  $countsql = "SELECT count(*) as TableCount ".substr($sql,strpos($sql," FROM "));
-  if(strpos($countsql,"LIMIT"))
-    $countsql = substr($countsql,0,strpos($countsql,"LIMIT"));
-  if(strpos($countsql,"ORDER BY"))
-    $countsql = substr($countsql,0,strpos($countsql,"ORDER BY"));
-    
-  $db = GetADODBConnection();
-  $rs = $db->Execute($countsql);
-  //echo $countsql."<br>\n";
-  $res = $rs->fields["TableCount"];
-  return $res;  
+	$sql = preg_replace('/SELECT(.*)FROM[ \n\r](.*)/is','SELECT COUNT(*) AS TableCount FROM $2', $sql);
+	$sql = preg_replace('/(.*)LIMIT(.*)/is','$1', $sql);
+	$sql = preg_replace('/(.*)ORDER BY(.*)/is','$1', $sql);
+	
+  	$db =& GetADODBConnection();
+  	return $db->GetOne($sql);
 }
     
 function GetPageCount($ItemsPerPage,$NumItems)
@@ -169,6 +220,10 @@
 }
 
 
+/**
+ * @return string
+ * @desc Returns database table prefix entered while installation
+*/
 function GetTablePrefix()
 {
     global $g_TablePrefix;
@@ -438,7 +493,10 @@
             }
             else
                 $ret = adodb_date("g:i a",$datestamp);
-       break;
+       		break;
+       	default:
+       		$ret = adodb_date($part, $datestamp);
+       		break;
      }
     return $ret;
 }
@@ -480,38 +538,42 @@
 
 function ReplaceSingleTag($tag,$text)
 {
-  $opentag = "[".$tag;
-  $closetag = "[/".$tag."]";
+	$tag = strtolower($tag);
+	$opentag = '['.$tag;
+  	$closetag = '[/'.$tag.']';
   
-  if(strstr($text,$opentag))
-  {   
-    $pos = strpos($text,$opentag." ");
-    if($pos === false)
-    {
-        $pos = strpos($text,$opentag."]");
-    }
-    $endopen = strpos($text,"]",$pos);
-    $closepos = strpos($text,$closetag,$pos);
-    
-    if($closepos)
-    {
-        $taglength = ($closepos - $endopen) + strlen($closetag);
-        $tagText = substr($text,$pos, $closepos + strlen($closetag) - $pos);       
-        $innerText = substr($text,$endopen+1,$closepos - $endopen-1);
-        if($tag=="UL")
-            $innerText = str_replace("[*]","<LI>",$innerText);
-        $tagText = substr($tagText,1,($endopen - $pos)-1);   
-        //echo "Matched $tagText <br>\n";
-        $tagText = "<".$tagText.">";
-        $replace_text = $tagText.$innerText."</".$tag.">";
-        $text = substr($text,0,$pos).$replace_text.substr($text,$closepos+strlen($closetag));
-        return $text;
-    }
-    else
-        return $text;
-  }
-  else
-      return $text;
+  	if( stristr($text,$opentag) )
+  	{
+  		$pos = strpos( strtolower($text), $opentag.' '); // tag has parameters
+  		if($pos === false)
+  		{
+  			$pos = strpos( strtolower($text), $opentag.']');
+  		}
+
+  		$endopen = strpos($text,']',$pos);
+  		$closepos = strpos( strtolower($text),$closetag,$pos);
+
+  		if($closepos)
+  		{
+  			$taglength = ($closepos - $endopen) + strlen($closetag);
+  			$tagText = substr($text,$pos, $closepos + strlen($closetag) - $pos);
+  			$innerText = substr($text,$endopen+1,$closepos - $endopen-1);
+  			if($tag=="UL")
+  			{
+  				$innerText = str_replace("[*]","<LI>",$innerText);
+  			}
+  			$tagText = substr($tagText,1,($endopen - $pos)-1);
+  			//echo "Matched $tagText <br>\n";
+  			$tagText = "<".$tagText.">";
+  			$replace_text = $tagText.$innerText."</".$tag.">";
+  			$text = substr($text,0,$pos).$replace_text.substr($text,$closepos+strlen($closetag));
+  			return $text;
+  		}
+  		else
+  		return $text;
+  	}
+  	else
+  	return $text;
 }
 
 function ReplaceTag($tag,$text)
@@ -528,34 +590,46 @@
 
 function ReplaceURL($text)
 {  
-  while(strstr($text,"[URL"))
-  {
-    $urlpos = strpos($text,"[URL");
-    $endopen = strpos($text,"]",$urlpos);
-    if($endopen)
-    {
-        $url = "<A TARGET=\"_blank\"".substr($text,$urlpos+4,$endopen - ($urlpos+4));
-        $url .= ">";
-        $url = _unhtmlentities($url);
-        $text = substr($text,0,$urlpos).$url.substr($text,$endopen+1);
-    }
-  }
-  $text = str_replace("[/URL]","</A>",$text);
-  return $text;
+  
+	// process url bbtags without href parameter
+	$text = preg_replace('/\[url\]([^\]]*)\[\/url\]/U', '[url href="$1"]$1[/url]', $text);
+	
+	// change bbcode to href's
+	while( stristr($text,'[url') )
+	{
+		$urlpos = strpos( strtolower($text), '[url');
+		$endopen = strpos($text,']',$urlpos);
+		if($endopen)
+		{
+			$url = '<a target="_blank"'.substr($text,$urlpos+4,$endopen - ($urlpos+4));
+			$url .= '>';
+			$url = _unhtmlentities($url);
+			$text = substr($text,0,$urlpos).$url.substr($text,$endopen+1);
+		}
+	}
+	$text = str_replace(Array('[/url]','[/URL]'),Array('</a>','</a>'),$text);
+	return $text;
 }
 
 
 function ReplaceBBCode($text)
 {
-  global $objConfig;
+  	global $objConfig;
 
-  $tags = explode(",",$objConfig->Get("BBTags"));
-  for($i=0;$i<count($tags);$i++)
-  {    
-    $text = ReplaceTag(strtoupper($tags[$i]),$text);
-  }
-  $text = ReplaceURL($text);
-  return $text;
+  	// BBCode: [b], [i], [u], [ul], [font]
+  	$tags = explode(",",$objConfig->Get("BBTags"));
+  	for($i = 0; $i < count($tags); $i++)
+  	{
+  		$text = ReplaceTag(strtoupper($tags[$i]),$text);
+  	}
+
+  	// BBCode: [url href="xxx"]xxx[/url]
+  	$text = ReplaceURL($text);
+  	
+  	// BBCode: [code]xxx[/code]
+  	$text = preg_replace('/\[code[^\]]*\](.*)\[\/code[^\]]*\]/Ues', 'highlight_string( _unhtmlentities(\'$1\') , true);', $text);
+  	
+  	return $text;
 }
 
 function GetMinValue($Table,$Field, $Where=NULL)
@@ -564,7 +638,7 @@
     $sql = "SELECT min($Field) as val FROM $Table ";
     if(strlen($where))
         $sql .= "WHERE $Where";
-    $ado = GetADODBConnection();
+    $ado = &GetADODBConnection();
     $rs = $ado->execute($sql);
     if($rs)
         $ret = (int)$rs->fields["val"];
@@ -591,8 +665,7 @@
           $found = FALSE;
           if(is_array($_FILES))
           {
-            if($_FILES[$r]["size"]>0)
-                $found=TRUE;
+            if( isset($_FILES[$r]) && $_FILES[$r]['size'] > 0 ) $found = TRUE;
           }
         
           if(!strlen(trim($_POST[$r])) && !$found)
@@ -602,7 +675,7 @@
             if (($r == "dob_day") || ($r == "dob_month") || ($r == "dob_year"))
             	$r = "dob";            	
             	
-            $tag = $_POST["errors"][$r];
+            $tag = isset($_POST["errors"]) ? $_POST["errors"][$r] : '';
             if(!strlen($tag))
               $tag = "lu_ferror_".$f."_".$r; 
             $FormError[$f][$r] = language($tag);
@@ -775,7 +848,7 @@
 	$sql = "SELECT Name from $cat_table WHERE ParentId=$ParentId AND ";
 	$sql .="(Name LIKE '".addslashes($Name)."' OR Name LIKE 'Copy of ".addslashes($Name)."' OR Name LIKE 'Copy % of ".addslashes($Name)."')";
 
-	$ado = GetADODBConnection();
+	$ado = &GetADODBConnection();
 	$rs = $ado->Execute($sql);
 	$ret = array();
 	while($rs && !$rs->EOF)
@@ -792,7 +865,7 @@
 	$sql = "SELECT $Field FROM $Table INNER JOIN $cat_table ON ($Table.ResourceId=$cat_table.ItemResourceId) ";
 	$sql .=" WHERE ($Field LIKE 'Copy % of $Name' OR $Field LIKE '$Name' OR $Field LIKE 'Copy of $Name') AND CategoryId=$CategoryId";
 	//echo $sql."<br>\n ";
-	$ado = GetADODBConnection();
+	$ado = &GetADODBConnection();
 	$rs = $ado->Execute($sql);
 	$ret = array();
 	while($rs && !$rs->EOF)
@@ -831,23 +904,19 @@
 {
 	global $objCountCache, $objItemTypes;
 
-  if(is_numeric($ItemName))
-  {
-  	$item = $objItemTypes->GetItem($ItemName);
-  }
-  else
-    $item = $objItemTypes->GetTypeByName($ItemName);
-  if(is_object($item))
-  {	
-  	$ItemType  = $item->Get("ItemType");
+  	if(is_numeric($ItemTypeName))
+  		$item = $objItemTypes->GetItem($ItemTypeName);
+  	else
+    	$item = $objItemTypes->GetTypeByName($ItemTypeName);
+  
+  	if(is_object($item))
+  	{	
+  		$ItemType  = $item->Get("ItemType");
   	
-	$sql = "DELETE FROM ".$objCountCache->SourceTable." WHERE ItemType=$ItemType";
-	if(is_numeric($ListType))
-	{
-		$sql .= " AND ListType=$ListType";
-	}
-	$objCountCache->adodbConnection->Execute($sql);
-  }  
+		$sql = "DELETE FROM ".$objCountCache->SourceTable." WHERE ItemType=$ItemType";
+		if( is_numeric($ListType) ) $sql .= " AND ListType=$ListType";
+		$objCountCache->adodbConnection->Execute($sql);
+  	}  
 }
 
 function UpdateModifiedCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$ExtraId=NULL)
@@ -884,7 +953,7 @@
     global $objSystemCache, $objSession, $objConfig;
 
     if($objConfig->Get("SystemTagCache"))
-    {    
+    {
         $name = $tag;
         if(is_array($attribs))
         {    
@@ -930,7 +999,10 @@
   }
   else
     $fmt = "m-d-Y";
-  return $fmt;	
+
+	if(isset($GLOBALS['FrontEnd'])&&$GLOBALS['FrontEnd'])
+		return $fmt;
+	return preg_replace('/y+/i','Y',$fmt);
 }
 
 function GetTimeFormat($LangId=0)
@@ -1104,7 +1176,8 @@
 function ResetPage($module_prefix, $page_variable = 'p')
 {
 	// resets page in specific module when category is changed	
-	if(!is_object($objSession)) // when changing pages session doesn't exist -> InPortal BUG
+	global $objSession;
+	if( !is_object($objSession) ) // when changing pages session doesn't exist -> InPortal BUG
 	{
 		global $var_list, $SessionQueryString, $FrontEnd;
 		//if(!$var_list["sid"]) $var_list["sid"] = $_COOKIE["sid"];
@@ -1118,11 +1191,29 @@
 	if($prev_cat != $last_cat) $GLOBALS[$module_prefix.'_var_list'][$page_variable] = 1;
 }
 
-function GetVar($name)
+if( !function_exists('GetVar') )
 {
-	return isset($_REQUEST[$name]) ? $_REQUEST[$name] : false;
+	/**
+	* @return string
+	* @param string $name
+	* @param bool $post_priority
+	* @desc Get's variable from http query
+	*/
+	function GetVar($name, $post_priority = false)
+	{
+		if(!$post_priority) // follow gpc_order in php.ini
+			return isset($_REQUEST[$name]) ? $_REQUEST[$name] : false;
+		else	// get variable from post 1stly if not found then from get
+			return isset($_POST[$name]) && $_POST[$name] !== false ? $_POST[$name] : ( isset($_GET[$name]) && $_GET[$name] ? $_GET[$name] : false );	
+	}
 }
 
+function SetVar($VarName, $VarValue)
+{
+	$_REQUEST[$VarName] = $VarValue;	
+	$_POST[$VarName] = $VarValue;
+}
+
 function PassVar(&$source)
 {
 	// source array + any count of key names in passed array	
@@ -1157,9 +1248,14 @@
 function GetModuleByAction()
 {
 	$prefix2module = Array('m' => 'In-Portal', 'l' => 'In-Link', 'n' => 'In-News', 'bb' => 'In-Bulletin');
-	$action = $_REQUEST['Action'];
-	$module_prefix = explode('_', $action);
-	return $prefix2module[ $module_prefix[0] ];
+	$action = GetVar('Action');
+	if($action)
+	{
+		$module_prefix = explode('_', $action);
+		return $prefix2module[ $module_prefix[0] ];
+	}
+	else
+		return false;
 }
 
 function dir_size($dir) {
@@ -1269,45 +1365,93 @@
 	return count($result) ? implode(' ', $result) : false;
 }
 
-/* so I dont forget:
-   - the decrypt function is defined in adodb-time and is called xp()
-   - the keygen function is also declared in adodb-time as $b 
-     and eval'd() in dates.php
-*/     
+function GetImportScripts()
+{
+	// return currently installed import scripts	
+	static $import_scripts = Array();
+	if( count($import_scripts) == 0 )
+	{
+		$sql = 'SELECT * FROM '.GetTablePrefix().'ImportScripts ORDER BY is_id';
+		$db =&GetADODBConnection();
+		$rs = $db->Execute($sql);
+		if( $rs && $rs->RecordCount() > 0 )
+		{
+			while(!$rs->EOF)
+			{
+				$rec =& $rs->fields;
+				$import_scripts[] = Array(	'label' => $rec['is_label'], 'url' => $rec['is_script'], 
+											'enabled' => $rec['is_enabled'], 'field_prefix' => $rec['is_field_prefix'],
+											'id' => $rec['is_string_id'], 'required_fields' => $rec['is_requred_fields'],
+											'module' => strtolower($rec['is_Module']) );
+				$rs->MoveNext();	
+			}
+		}
+		else
+		{
+			$import_scripts = Array();	
+		}
+	}
+	return $import_scripts;
+}
 
+function GetImportScript($id)
+{
+	$scripts = GetImportScripts();
+	return isset($scripts[$id]) ? $scripts[$id] : false;
+}
+function GetNextTemplate($current_template) 
+{ 
+	// used on front, returns next template to make 
+	// redirect to 
+	$dest = GetVar('dest', true); 
+	if(!$dest) $dest = GetVar('DestTemplate', true); 
+	return $dest ? $dest : $current_template; 
+}
 
 
-/* //this comes from line 15; moved by PSK for readability 
+// functions for dealign with enviroment variable construction
+function GenerateModuleEnv($prefix, $var_list)
+{ 
+	// globalize module varible arrays
+	$main =& $GLOBALS[$prefix.'_var_list'];
+	$update =& $GLOBALS[$prefix.'_var_list_update'];
+	//echo "VAR: [$main]; VAR_UPDATE: [$update]<br>";
+	
+	// ensure that we have no empty values in enviroment variable
+	foreach($update as $vl_key => $vl_value)
+    	if(!$vl_value) $update[$vl_key] = '0'; // unset($update[$vl_key]);
+   
+    // if update var count is zero, then do nothing
+    if(count($update) == 0) return '';
 
-  $g_DBType = "mysql";
-  $g_DBHost = "kiev";
+    foreach($main as $vl_key => $vl_value)
+    	if(!$vl_value) $main[$vl_key] = '0'; // unset($main[$vl_key]);
+    
+	$ret = Array();
+	foreach($var_list as $var_name)
+		$ret[] = GetEnvVar($prefix, $var_name);
+	
+	return ':'.$prefix.implode('-',$ret);
+}
 
-  $g_DBUser = "root";
-  $g_DBUserPassword = "";
-  $g_DBName = "inportal";
+function GetEnvVar($prefix, $name)
+{
+	// get variable from template variable's list
+	// (used in module parsers to build env string)
+	$main =& $GLOBALS[$prefix.'_var_list'];
+	$update =& $GLOBALS[$prefix.'_var_list_update'];
 
+	return isset($update[$name]) ? $update[$name] : ( isset($main[$name]) ? $main[$name] : '');
+}
 
-//$g_DBUser = "bloopered";
-//$g_DBUserPassword = "vFWPqJT017";
-//$g_DBName = "inportal";
+/**
+ * @return int
+ * @desc Checks for debug mode
+*/
+function IsDebugMode()
+{
+	return defined('DEBUG_MODE') && constant('DEBUG_MODE') == 1 ? 1 : 0;	
+}
 
-  $g_TablePrefix = "";
 
-  $g_EnableCookies = FALSE;
-  $g_SessionExpirationLimit = 3600*1; // 1 hour
-
-//$g_PrivateMessageExpirationLimit = 2592000; // 30 days
-//$g_PrivateMessageThreadLimit = 50;
-//$g_DebugMode=0;
-
-//$g_defaultLanguage = "English";
-//$g_defaultTheme = "default";
-
-  $g_TopRate = 4;
-  $g_PopRate = 80;
-  $g_NewDate = 5;
-
-  
-  $g_adodbConnection=NULL;
-*/
 ?>