1   <?php
  2  
  3   if (!function_exists('parse_portal_ini')) {
  4           function parse_portal_ini($file, $parse_section = false) {
  5                   
  6                           if (!file_exists($file)) return;
  7                   
  8               if(file_exists($file) && !is_readable($file)) 
  9                   die('Could Not Open Ini File');
  10               
  11               $contents = file($file);
  12               
  13               $retval = array();
  14               
  15               $section = '';
  16               $ln = 1;
  17               $resave = false;
  18               foreach($contents as $line) {
  19                           if ($ln == 1 && $line != '<'.'?'.'php die() ?'.">\n") {
  20                                   $resave = true;
  21                           }
  22                           $ln++;
  23                   $line = trim($line);
  24                   $line = eregi_replace(';[.]*','',$line);
  25                   if(strlen($line) > 0) {
  26                       //echo $line . " - ";
  27                       if(eregi('^[[a-z]+]$',str_replace(' ', '', $line))) {
  28                           //echo 'section';
  29                           $section = substr($line,1,(strlen($line)-2));
  30                           if ($parse_section) {
  31                                   $retval[$section] = array();
  32                           }
  33                           continue;
  34                       } elseif(eregi('=',$line)) {
  35                           //echo 'main element';
  36                           list($key,$val) = explode(' = ',$line);
  37                           if (!$parse_section) {
  38                                   $retval[trim($key)] = str_replace('"', '', $val);
  39                           }
  40                           else {
  41                                                   $retval[$section][trim($key)] = str_replace('"', '', $val);                     
  42                           }
  43                       } //end if
  44                       //echo '<br />';
  45                   } //end if
  46               } //end foreach
  47               if ($resave) {
  48                   $fp = fopen($file, "w");
  49                   reset($contents);
  50                                   fwrite($fp,'<'.'?'.'php die() ?'.">\n\n");
  51                                   foreach($contents as $line) fwrite($fp,"$line");
  52                                   fclose($fp);
  53                           }  
  54              
  55               return $retval;
  56           }
  57   }
  58  
  59   $vars = parse_portal_ini($pathtoroot."config.php");
  60  
  61   while($key = key($vars))
  62   {
  63     $key = "g_".$key;
  64     global $$key;
  65     $$key = current($vars); //variable variables
  66     next($vars);
  67   }
  68  
  69   /*list the tables which contain item data */
  70   $ItemTables = array();
  71  
  72   $KeywordIgnore = array();
  73   global $debuglevel;
  74  
  75   $debuglevel = 0;
  76   //$GLOBALS['debuglevel'] = 0;
  77  
  78   /*New, Hot, Pop field values */
  79   define('NEVER', 0);
  80   define('ALWAYS', 1);
  81   define('AUTO', 2);
  82  
  83   /*Status Values */
  84   if( !defined('STATUS_DISABLED') ) define('STATUS_DISABLED', 0);
  85   if( !defined('STATUS_ACTIVE') ) define('STATUS_ACTIVE', 1);
  86   if( !defined('STATUS_PENDING') ) define('STATUS_PENDING', 2);
  87  
  88   $LogLevel = 0;
  89   $LogFile = NULL;
  90  
  91   /**
  92    * @return object
  93    * @desc Returns reference to database connection
  94   */
  95   function &GetADODBConnection()
  96   {
  97           static $DB = null;
  98           
  99           global $g_DBType, $g_DBHost, $g_DBUser, $g_DBUserPassword, $g_DBName, $g_DebugMode;
  100           global $ADODB_FETCH_MODE, $ADODB_COUNTRECS, $ADODB_CACHE_DIR, $pathtoroot;
  101           
  102           if( !isset($DB) && strlen($g_DBType) > 0 )
  103           {
  104                   $DB = ADONewConnection($g_DBType);
  105                   $connected = $DB->Connect($g_DBHost, $g_DBUser, $g_DBUserPassword, $g_DBName);
  106                   if(!$connected) die("Error connecting to database $g_DBHost <br>\n");
  107                   
  108                   $ADODB_CACHE_DIR = $pathtoroot."cache";
  109                   $ADODB_FETCH_MODE = 2;
  110                   $ADODB_COUNTRECS = false;
  111                   $DB->debug = defined('ADODB_OUTP') ? 1 : 0;
  112                   $DB->cacheSecs = 3600;
  113                   $DB->Execute('SET SQL_BIG_SELECTS = 1');
  114           }
  115           elseif( !strlen($g_DBType) )
  116           {
  117                   global $rootURL;
  118                   echo 'In-Portal is probably not installed, or configuration file is missing.<br>';
  119                   echo 'Please use the installation script to fix the problem.<br><br>';
  120                   if ( !preg_match('/admin/', __FILE__) ) $ins = 'admin/';
  121                   
  122                   echo '<a href="'.$rootURL.$ins.'install.php">Go to installation script</a><br><br>';
  123                   flush();
  124                   exit;
  125           }
  126           return $DB;
  127   }
  128  
  129   function GetNextResourceId($Increment=1)
  130   {
  131           global $objModules, $pathtoroot;
  132           $table_name = GetTablePrefix().'IdGenerator';
  133  
  134           $db = &GetADODBConnection();
  135  
  136           // dummy protection: get maximal resource id used actually and fix last_id used
  137           $max_resourceid = 0;
  138           
  139           $m = GetModuleArray();
  140           foreach($m as $key=>$value)
  141           {
  142                   $path = $pathtoroot. $value."admin/include/parser.php";
  143                   if(file_exists($path))
  144                   {
  145                           include_once($path);
  146                   }
  147           }
  148           
  149           $table_info = $objModules->ExecuteFunction('GetModuleInfo', 'dupe_resourceids');
  150           $sql_template = 'SELECT MAX(ResourceId) FROM '.GetTablePrefix().'%s';
  151  
  152           foreach($table_info as $module_name => $module_info)
  153           {
  154                   foreach($module_info as $module_sub_info)
  155                   {
  156                           $sql = sprintf($sql_template,$module_sub_info['Table']);
  157                           $tmp_resourceid = $db->GetOne($sql);
  158                           if($tmp_resourceid > $max_resourceid) $max_resourceid = $tmp_resourceid;
  159                   }
  160           }
  161  
  162           // update lastid to be next resourceid available
  163           $db->Execute('LOCK TABLES '.$table_name.' WRITE');
  164  
  165           $last_id = $db->GetOne('SELECT lastid FROM '.$table_name);
  166           if ($last_id - 1 > $max_resourceid) $max_resourceid = $last_id - 1;
  167           
  168           $id_diff = $db->GetOne('SELECT '.$max_resourceid.' + 1 - lastid FROM '.$table_name);
  169           if($id_diff) $Increment += $id_diff;
  170  
  171           $sql = 'UPDATE '.$table_name.' SET lastid = lastid + '.$Increment; // set new id in db
  172           $db->Execute($sql);
  173  
  174           $val = $db->GetOne('SELECT lastid FROM '.$table_name);
  175           if($val === false)
  176           {
  177                   $db->Execute('INSERT INTO '.$table_name.' (lastid) VALUES ('.$Increment.')');
  178                   $val = $Increment;
  179           }
  180           $db->Execute('UNLOCK TABLES');
  181  
  182           return $val - $Increment  + $id_diff; // return previous free id (-1) ?
  183   }
  184  
  185   function AddSlash($s)
  186   {
  187       if(substr($s,-1) != "/")
  188       {
  189           return $s."/";
  190       }
  191       else
  192           return $s;
  193   }
  194  
  195   function StripNewline($s)
  196   {
  197           $bfound = false;
  198           while (strlen($s)>0 && !$bfound)
  199           {
  200                   if(ord(substr($s,-1))<32)
  201                   {
  202                           $s = substr($s,0,-1);
  203                   }
  204                   else
  205                     $bfound = true;
  206           }
  207           return $s;
  208   }
  209  
  210   function DeleteElement($array, $indice)
  211   {
  212     for($i=$indice;$i<count($array)-1;$i++)
  213           $array[$i] = $array[$i+1];
  214     unset($array[count($array)-1]);
  215     return $array;
  216   }
  217  
  218   function DeleteElementValue($needle, &$haystack)
  219   {
  220     while(($gotcha = array_search($needle,$haystack)) > -1)
  221      unset($haystack[$gotcha]);
  222   }       
  223  
  224   function TableCount($TableName, $where="",$JoinCats=1)
  225   {
  226       $db = &GetADODBConnection();
  227       if(!$JoinCats)
  228       {   
  229         $sql = "SELECT count(*) as TableCount FROM $TableName";
  230       }
  231       else
  232           $sql = "SELECT count(*) as TableCount FROM $TableName INNER JOIN ".GetTablePrefix()."CategoryItems ON ".GetTablePrefix()."CategoryItems.ItemResourceId=$TableName.ResourceId";
  233       if(strlen($where)>0)
  234           $sql .= " WHERE ".$where;
  235     
  236       $rs = $db->Execute($sql);
  237          
  238   //    echo "SQL TABLE COUNT: ".$sql."<br>\n";
  239      
  240       $res = $rs->fields["TableCount"];
  241       return $res;
  242   }
  243  
  244   Function QueryCount($sql)
  245   {
  246           $sql = preg_replace('/SELECT(.*)FROM[ \n\r](.*)/is','SELECT COUNT(*) AS TableCount FROM $2', $sql);
  247           $sql = preg_replace('/(.*)LIMIT(.*)/is','$1', $sql);
  248           $sql = preg_replace('/(.*)ORDER BY(.*)/is','$1', $sql);
  249           
  250           //echo $sql;
  251           
  252           $db =& GetADODBConnection();
  253           return $db->GetOne($sql);
  254   }
  255      
  256   function GetPageCount($ItemsPerPage,$NumItems)
  257   {
  258    if($ItemsPerPage==0 || $NumItems==0)
  259    {
  260      return 1;
  261    }           
  262    $value = $NumItems/$ItemsPerPage;
  263    return ceil($value);       
  264   }
  265  
  266  
  267   /**
  268    * @return string
  269    * @desc Returns database table prefix entered while installation
  270   */
  271   function GetTablePrefix()
  272   {
  273       global $g_TablePrefix;
  274  
  275       return $g_TablePrefix;
  276   }
  277  
  278   function TableHasPrefix($t)
  279   {
  280           $pre = GetTablePrefix();
  281           
  282           if(strlen($pre)>0)
  283           {
  284                   if(substr($t,0,strlen($pre))==$pre)
  285                   {
  286                           return TRUE;
  287                   }
  288                   else
  289                     return FALSE;
  290           }
  291           else
  292             return TRUE;
  293   }
  294  
  295   function AddTablePrefix($t)
  296   {
  297           if(!TableHasPrefix($t))
  298             $t = GetTablePrefix().$t;
  299            
  300           return $t;
  301   }
  302  
  303   function ThisDomain()
  304   {
  305           global $objConfig, $g_Domain;
  306           
  307           if($objConfig->Get("DomainDetect"))
  308           {
  309                   $d = $_SERVER['HTTP_HOST'];
  310           }
  311           else
  312             $d = $g_Domain;
  313            
  314           return $d;
  315   }
  316  
  317   function GetIndexUrl($secure=0)
  318   {
  319       global $indexURL, $rootURL, $secureURL;
  320      
  321       switch($secure)
  322       {
  323           case 0:
  324                   $ret = $indexURL;
  325                   break;
  326                   
  327           case 1:
  328                   $ret = $secureURL."index.php";
  329                   break;
  330                   
  331           case 2:
  332                   $ret = $rootURL."index.php";
  333                   break;
  334                   
  335           default:
  336                   $ret = $i;
  337                   break;
  338       }                                   
  339       return $ret;
  340   }
  341  
  342   function GetLimitSQL($Page,$PerPage)
  343   {
  344     if($Page<1)
  345       $Page=1;
  346  
  347     if(is_numeric($PerPage))
  348     {
  349             if($PerPage==0)        
  350               $PerPage = 20;
  351         $Start = ($Page-1)*$PerPage;
  352         $limit = "LIMIT ".$Start.",".$PerPage;
  353     }
  354     else
  355         $limit = NULL;
  356     return $limit;
  357   }
  358  
  359   function filelist ($currentdir, $startdir=NULL,$ext=NULL)
  360   {
  361     global $pathchar;
  362  
  363     //chdir ($currentdir);
  364  
  365     // remember where we started from
  366     if (!$startdir)
  367     {
  368         $startdir = $currentdir;
  369     }
  370  
  371     $d = @opendir($currentdir);
  372  
  373     $files = array();
  374     if(!$d)
  375       return $files
  376     //list the files in the dir
  377     while (false !== ($file = readdir($d)))
  378     {
  379         if ($file != ".." && $file != ".")
  380         {
  381             if (is_dir($currentdir."/".$file))
  382             {
  383                 // If $file is a directory take a look inside
  384                 $a = filelist ($currentdir."/".$file, $startdir,$ext);
  385                 if(is_array($a))
  386                   $files = array_merge($files,$a);
  387             }
  388             else
  389             {
  390                 if($ext!=NULL)
  391                 {
  392                     $extstr = stristr($file,".".$ext);
  393                     if(strlen($extstr))
  394                         $files[] = $currentdir."/".$file;
  395                 }
  396                 else
  397                   $files[] = $currentdir.'/'.$file;
  398             }
  399         }
  400     }
  401  
  402     closedir ($d);
  403  
  404     return $files;
  405   }       
  406  
  407   function DecimalToBin($dec,$WordLength=8)
  408   {
  409     $bits = array();
  410    
  411     $str = str_pad(decbin($dec),$WordLength,"0",STR_PAD_LEFT);
  412     for($i=$WordLength;$i>0;$i--)
  413     {
  414         $bits[$i-1] = (int)substr($str,$i-1,1);
  415     }
  416     return $bits;
  417   }
  418   /*
  419   function inp_escape($in, $html_enable=0)
  420   {
  421           $out = stripslashes($in);
  422           $out = str_replace("\n", "\n^br^", $out);
  423           if($html_enable==0)
  424           {
  425                   $out=ereg_replace("<","&lt;",$out);
  426                   $out=ereg_replace(">","&gt;",$out);
  427                   $out=ereg_replace("\"","&quot;",$out);
  428                   $out = str_replace("\n^br^", "\n<br />", $out);
  429           }       
  430           else
  431                   $out = str_replace("\n^br^", "\n", $out);
  432           $out=addslashes($out);
  433  
  434           return $out;
  435   }
  436   */
  437   function inp_escape($var,$html=0)
  438   {
  439           if($html)return $var;
  440           if(is_array($var))
  441                   foreach($var as $k=>$v)
  442                           $var[$k]=inp_escape($v);
  443           else
  444   //              $var=htmlspecialchars($var,ENT_NOQUOTES);
  445                   $var=strtr($var,Array('<'=>'&lt;','>'=>'&gt;',));
  446           return $var;
  447   }
  448   function inp_striptags($var,$html=0)
  449   {
  450           if($html)return $var;
  451           if(is_array($var))
  452                   foreach($var as $k=>$v)
  453                           $var[$k]=inp_striptags($v);
  454           else
  455                   $var=strip_tags($var);
  456           return $var;
  457   }
  458  
  459   function inp_unescape($in)
  460   {
  461   //      if (get_magic_quotes_gpc())
  462                   return $in;
  463           $out=stripslashes($in);
  464           return $out;
  465   }
  466  
  467   function inp_textarea_unescape($in)
  468   {
  469   //      if (get_magic_quotes_gpc())
  470                   return $in;
  471           $out=stripslashes($in);
  472           $out = str_replace("\n<br />", "\n", $out);
  473           return $out;
  474   }
  475  
  476   function HighlightKeywords($Keywords, $html, $OpenTag="", $CloseTag="")
  477   {
  478       global $objConfig;
  479  
  480       if(!strlen($OpenTag))
  481           $OpenTag = "<B>";
  482       if(!strlen($CloseTag))
  483               $CloseTag = "</B>"
  484           
  485           $r = preg_split('((>)|(<))', $html, -1, PREG_SPLIT_DELIM_CAPTURE);
  486           
  487           foreach ($Keywords as $k) {             
  488                   for ($i = 0; $i < count($r); $i++) {
  489                  if ($r[$i] == "<") {
  490                      $i++; continue;
  491                  }
  492                  $r[$i] = preg_replace("/($k)/i", "$OpenTag\\1$CloseTag", $r[$i]);
  493               }
  494           }
  495           return join("", $r);
  496   }
  497  
  498   /*
  499   function HighlightKeywords($Keywords,$html, $OpenTag="", $CloseTag="")
  500   {
  501       global $objConfig;
  502  
  503       if(!strlen($OpenTag))
  504           $OpenTag = "<B>";
  505       if(!strlen($CloseTag))
  506               $CloseTag = "</B>";
  507       $ret = strip_tags($html);
  508  
  509       foreach ($Keywords as $k)
  510       {  
  511           if(strlen($k))
  512           {       
  513             //$html = str_replace("<$k>", ":#:", $html);
  514             //$html = str_replace("</$k>", ":##:", $html);
  515             //$html = strip_tags($html);
  516             if ($html = preg_replace("/($k)/Ui","$OpenTag\\1$CloseTag", $html))
  517             //if ($html = preg_replace("/(>[^<]*)($k)([^<]*< )/Ui","$OpenTag\\1$CloseTag", $html))
  518               $ret = $html;
  519             //$ret = str_replace(":#:", "<$k>", $ret);
  520             //$ret = str_replace(":##:", "</$k>", $ret);
  521           }
  522       }
  523       return $ret;       
  524   }
  525   */
  526   function ExtractDatePart($part,$datestamp)
  527   {
  528       switch($part)
  529       {
  530           case "month":
  531               if($datestamp<=0)
  532               {                       
  533                   $ret = "";
  534               }
  535               else
  536                 $ret = adodb_date("m",$datestamp);
  537           break;          
  538           case "day":
  539               if($datestamp<=0)
  540               {                       
  541                   $ret = "";
  542               }
  543               else
  544                   $ret = adodb_date("d", $datestamp);
  545           break;          
  546           case "year":
  547               if($datestamp<=0)
  548               {                       
  549                   $ret = "";
  550               }
  551               else
  552                   $ret = adodb_date("Y", $datestamp);
  553           break;
  554           case "time_24hr":
  555               if($datestamp<=0)
  556               {                       
  557                   $ret = "";
  558               }
  559               else
  560                   $ret = adodb_date("H:i", $datestamp);
  561           break;
  562           case "time_12hr":
  563               if($datestamp<=0)
  564               {
  565                   $ret = "";
  566               }
  567               else
  568                   $ret = adodb_date("g:i a",$datestamp);
  569                   break;
  570           default:
  571                   $ret = adodb_date($part, $datestamp);
  572                   break;
  573        }
  574       return $ret;
  575   }
  576  
  577   function GetLocalTime($TimeStamp,$TargetZone=NULL)
  578   {
  579       if($TargetZone==NULL)
  580           $TargetZone = $objConfig->Get("Config_Site_Time");  
  581       $server = $objConfig->Get("Config_Server_Time");
  582       if($TargetZone!=$server)
  583       {   
  584         $offset = ($server - $TargetZone) * -1;
  585         $TimeStamp = $TimeStamp + (3600 * $offset);
  586       }
  587       return $TimeStamp;
  588   }
  589  
  590   function _unhtmlentities ($string)
  591   {
  592       $trans_tbl = get_html_translation_table (HTML_ENTITIES);
  593       $trans_tbl = array_flip ($trans_tbl);
  594       return strtr ($string, $trans_tbl);
  595   }
  596  
  597   function getLastStr($hay, $need){
  598     $getLastStr = 0;
  599     $pos = strpos($hay, $need);
  600     if (is_int ($pos)){ //this is to decide whether it is "false" or "0"
  601      while($pos) {
  602        $getLastStr = $getLastStr + $pos + strlen($need);
  603        $hay = substr ($hay , $pos + strlen($need));
  604        $pos = strpos($hay, $need);
  605      }
  606      return $getLastStr - strlen($need);
  607     } else {
  608      return -1; //if $need wasn´t found it returns "-1" , because it could return "0" if it´s found on position "0".
  609     }
  610   }
  611  
  612   // --- bbcode processing function: begin ----
  613   function PreformatBBCodes($text)
  614   {
  615           // convert phpbb url bbcode to valid in-bulletin's format
  616           // 1. urls
  617           $text = preg_replace('/\[url=(.*)\](.*)\[\/url\]/Ui','[url href="$1"]$2[/url]',$text);
  618           $text = preg_replace('/\[url\](.*)\[\/url\]/Ui','[url href="$1"]$1[/url]',$text);
  619           // 2. images
  620           $text = preg_replace('/\[img\](.*)\[\/img\]/Ui','[img src="$1" border="0"][/img]',$text);
  621           // 3. color
  622           $text = preg_replace('/\[color=(.*)\](.*)\[\/color\]/Ui','[font color="$1"]$2[/font]',$text);
  623           // 4. size
  624           $text = preg_replace('/\[size=(.*)\](.*)\[\/size\]/Ui','[font size="$1"]$2[/font]',$text);
  625           // 5. lists
  626           $text = preg_replace('/\[list(.*)\](.*)\[\/list\]/Uis','[ul]$2[/ul]',$text);
  627           // 6. email to link
  628           $text = preg_replace('/\[email\](.*)\[\/email\]/Ui','[url href="mailto:$1"]$1[/url]',$text);
  629           //7. b tag
  630           $text = preg_replace('/\[(b|i|u):(.*)\](.*)\[\/(b|i|u):(.*)\]/Ui','[$1]$3[/$4]',$text);
  631           //8. code tag
  632           $text = preg_replace('/\[code:(.*)\](.*)\[\/code:(.*)\]/Uis','[code]$2[/code]',$text);
  633           return $text;
  634   }
  635  
  636   /**
  637    * @return string
  638    * @param string $BBCode
  639    * @param string $TagParams
  640    * @param string $TextInside
  641    * @param string $ParamsAllowed
  642    * @desc Removes not allowed params from tag and returns result
  643   */
  644   function CheckBBCodeAttribs($BBCode, $TagParams, $TextInside, $ParamsAllowed)
  645   {
  646           //      $BBCode - bbcode to check, $TagParams - params string entered by user
  647           //      $TextInside - text between opening and closing bbcode tag
  648           //      $ParamsAllowed - list of allowed parameter names ("|" separated)
  649           $TagParams=str_replace('\"','"',$TagParams);
  650           $TextInside=str_replace('\"','"',$TextInside);
  651           if( $ParamsAllowed && preg_match_all('/ +([^=]*)=["\']?([^ "\']*)["\']?/is',$TagParams,$params,PREG_SET_ORDER) )
  652           {
  653                   $ret = Array();
  654                   foreach($params as $param)
  655                   {
  656                           // remove spaces in both parameter name & value & lowercase parameter name
  657                           $param[1] = strtolower(trim($param[1]));        // name lowercased
  658                           if(($BBCode=='url')&&($param[1]=='href'))
  659                                   if(false!==strpos(strtolower($param[2]),'script:'))
  660                                           return $TextInside;
  661   //                                      $param[2]='about:blank';
  662                           if( isset($ParamsAllowed[ $param[1] ]) )
  663                                   $ret[] = $param[1].'="'.$param[2].'"';
  664                   }
  665                   $ret = count($ret) ? ' '.implode(' ',$ret) : '';
  666                   return '<'.$BBCode.$ret.'>'.$TextInside.'</'.$BBCode.'>';
  667           }
  668           else
  669                   return '<'.$BBCode.'>'.$TextInside.'</'.$BBCode.'>';
  670           return false;
  671   }
  672   function ReplaceBBCode($text)
  673   {
  674           global $objConfig;
  675           // convert phpbb bbcodes to in-bulletin bbcodes
  676           $text = PreformatBBCodes($text);
  677           
  678   //      $tag_defs = 'b:;i:;u:;ul:type|align;font:color|face|size;url:href;img:src|border';
  679           
  680           $tags_defs = $objConfig->Get('BBTags');
  681           foreach(explode(';',$tags_defs) as $tag)
  682           {
  683                   $tag = explode(':',$tag);
  684                   $tag_name = $tag[0];
  685                   $tag_params = $tag[1]?array_flip(explode('|',$tag[1])):0;
  686                   $text = preg_replace('/\['.$tag_name.'(.*)\](.*)\[\/'.$tag_name.' *\]/Uise','CheckBBCodeAttribs("'.$tag_name.'",\'$1\',\'$2\',$tag_params);', $text);
  687           }
  688           
  689           // additional processing for [url], [*], [img] bbcode
  690           $text = preg_replace('/<url>(.*)<\/url>/Usi','<url href="$1">$1</url>',$text);
  691           $text = preg_replace('/<font>(.*)<\/font>/Usi','$1',$text); // skip empty fonts
  692           $text = str_replace(    Array('<url','</url>','[*]'),
  693                                                           Array('<a target="_blank"','</a>','<li>'),
  694                                                           $text);
  695           
  696           // bbcode [code]xxx[/code] processing
  697           $text = preg_replace('/\[code\](.*)\[\/code\]/Uise', "ReplaceCodeBBCode('$1')", $text);
  698           return $text;
  699   }
  700   function leadSpace2nbsp($x)
  701   {
  702           return "\n".str_repeat('&nbsp;',strlen($x));
  703   }
  704   function ReplaceCodeBBCode($input_string)
  705   {
  706           $input_string=str_replace('\"','"',$input_string);
  707           $input_string=$GLOBALS['objSmileys']->UndoSmileys(_unhtmlentities($input_string));
  708           $input_string=trim($input_string);
  709           $input_string=inp_htmlize($input_string);
  710           $input_string=str_replace("\r",'',$input_string);
  711           $input_string = str_replace("\t", "    ", $input_string);
  712           $input_string = preg_replace('/\n( +)/se',"leadSpace2nbsp('$1')",$input_string);
  713           $input_string='<div style="border:1px solid #888888;width:100%;background-color:#eeeeee;margin-top:6px;margin-bottom:6px"><div style="padding:10px;"><code>'.$input_string.'</code></div></div>';
  714   //      $input_string='<textarea wrap="off" style="border:1px solid #888888;width:100%;height:200px;background-color:#eeeeee;">'.inp_htmlize($input_string).'</textarea>';
  715           return $input_string;
  716           
  717           if(false!==strpos($input_string,'<'.'?'))
  718           {
  719                   $input_string=str_replace('<'.'?','<'.'?php',$input_string);
  720                   $input_string=str_replace('<'.'?phpphp','<'.'?php',$input_string);
  721                   $input_string=@highlight_string($input_string,1);
  722           }
  723           else
  724           {
  725                   $input_string = @highlight_string('<'.'?php'.$input_string.'?'.'>',1);
  726                   $input_string = str_replace('&lt;?php', '', str_replace('?&gt;', '', $input_string));
  727           }
  728           return str_replace('<br />','',$input_string);
  729  
  730   }
  731  
  732  
  733   // --- bbcode processing function: end ----
  734  
  735   function GetMinValue($Table,$Field, $Where=NULL)
  736   {
  737       $ret = 0;
  738       $sql = "SELECT min($Field) as val FROM $Table ";
  739       if(strlen($where))
  740           $sql .= "WHERE $Where";
  741       $ado = &GetADODBConnection();
  742       $rs = $ado->execute($sql);
  743       if($rs)
  744           $ret = (int)$rs->fields["val"];
  745       return $ret;
  746   }
  747  
  748  
  749   if (!function_exists( 'getmicrotime' ) ) {
  750           function getmicrotime()
  751           {
  752               list($usec, $sec) = explode(" ",microtime());
  753               return ((float)$usec + (float)$sec);
  754           }
  755   }
  756  
  757   function SetMissingDataErrors($f)
  758   {
  759       global $FormError;
  760  
  761       $count = 0;
  762       if(is_array($_POST))
  763       {   
  764         if(is_array($_POST["required"]))
  765         {     
  766           foreach($_POST["required"] as $r)
  767           {
  768             $found = FALSE;
  769             if(is_array($_FILES))
  770             {
  771               if( isset($_FILES[$r]) && $_FILES[$r]['size'] > 0 ) $found = TRUE;
  772             }
  773          
  774             if(!strlen(trim($_POST[$r])) && !$found)
  775             {          
  776               $count++;
  777              
  778               if (($r == "dob_day") || ($r == "dob_month") || ($r == "dob_year"))
  779                   $r = "dob";             
  780                   
  781               $tag = isset($_POST["errors"]) ? $_POST["errors"][$r] : '';
  782               if(!strlen($tag))
  783                 $tag = "lu_ferror_".$f."_".$r;
  784               $FormError[$f][$r] = language($tag);
  785             }
  786           }
  787         }
  788       }
  789       return $count;
  790   }
  791  
  792   function makepassword($length=10)
  793   {
  794     $pass_length=$length;
  795  
  796     $p1=array('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z');
  797     $p2=array('a','e','i','o','u');
  798     $p3=array('1','2','3','4','5','6','7','8','9');  
  799     $p4=array('(','&',')',';','%');    // if you need real strong stuff
  800  
  801     // how much elements in the array
  802     // can be done with a array count but counting once here is faster
  803  
  804     $s1=21;// this is the count of $p1   
  805     $s2=5; // this is the count of $p2
  806     $s3=9; // this is the count of $p3
  807     $s4=5; // this is the count of $p4
  808  
  809     // possible readable combinations
  810  
  811     $c1='121';    // will be like 'bab'
  812     $c2='212';      // will be like 'aba'
  813     $c3='12';      // will be like 'ab'
  814     $c4='3';        // will be just a number '1 to 9'  if you dont like number delete the 3
  815   // $c5='4';        // uncomment to active the strong stuff
  816  
  817     $comb='4'; // the amount of combinations you made above (and did not comment out)
  818  
  819  
  820  
  821     for ($p=0;$p<$pass_length;)
  822     {
  823       mt_srand((double)microtime()*1000000);
  824       $strpart=mt_rand(1,$comb);
  825       // checking if the stringpart is not the same as the previous one
  826       if($strpart<>$previous)
  827       {
  828         $pass_structure.=${'c'.$strpart};
  829  
  830         // shortcutting the loop a bit
  831         $p=$p+strlen(${'c'.$strpart});
  832       }
  833       $previous=$strpart;
  834     }
  835  
  836  
  837     // generating the password from the structure defined in $pass_structure
  838     for ($g=0;$g<strlen($pass_structure);$g++)
  839     {
  840       mt_srand((double)microtime()*1000000);
  841       $sel=substr($pass_structure,$g,1);
  842       $pass.=${'p'.$sel}[mt_rand(0,-1+${'s'.$sel})];
  843  
  844     }
  845     return $pass;
  846   }
  847  
  848   function LogEntry($text,$writefile=FALSE)
  849   {
  850     global $g_LogFile,$LogFile, $LogData, $LogLevel, $timestart;
  851    
  852     static $last;
  853  
  854     if(strlen($g_LogFile))
  855     {
  856       $el = str_pad(getmicrotime()- $timestart,10," ");
  857       if($last>0)
  858         $elapsed = getmicrotime() - $last;
  859        
  860       if(strlen($el)>10)
  861           $el = substr($el,0,10);     
  862       $indent = str_repeat("  ",$LogLevel);
  863       $text = str_pad($text,$LogLevel,"==",STR_PAD_LEFT);
  864       $LogData .= "$el:". round($elapsed,6).":$indent $text";
  865       $last = getmicrotime();
  866       if($writefile==TRUE && is_writable($g_LogFile))
  867       {
  868         if(!$LogFile)      
  869         {
  870            if(file_exists($g_LogFile))
  871               unlink($g_LogFile);
  872           $LogFile=@fopen($g_LogFile,"w");
  873         }
  874         if($LogFile)
  875         {   
  876           fputs($LogFile,$LogData);
  877         }
  878       }
  879     }
  880   }
  881  
  882   function ValidEmail($email)
  883   {
  884       if (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $email))
  885       {
  886           return TRUE;
  887       }
  888       else
  889       {
  890           return FALSE;
  891       }
  892   }
  893  
  894   function language($phrase,$LangId=0)
  895   {
  896       global $objSession, $objLanguageCache, $objLanguages;
  897  
  898       if($LangId==0)
  899           $LangId = $objSession->Get("Language");
  900          
  901           if($LangId==0)
  902         $LangId = $objLanguages->GetPrimary();       
  903  
  904       $translation = $objLanguageCache->GetTranslation($phrase,$LangId);
  905  
  906       return $translation;
  907   }
  908  
  909   function admin_language($phrase,$lang=0,$LinkMissing=FALSE)
  910   {
  911       global $objSession, $objLanguageCache, $objLanguages;
  912      
  913           //echo "Language passed: $lang<br>";
  914           
  915       if($lang==0)
  916          $lang = $objSession->Get("Language");
  917  
  918       //echo "Language from session: $lang<br>";
  919      
  920           if($lang==0)
  921         $lang = $objLanguages->GetPrimary();  
  922           
  923       //echo "Language after primary: $lang<br>";
  924       //echo "Phrase: $phrase<br>";
  925           $translation = $objLanguageCache->GetTranslation($phrase,$lang);
  926       if($LinkMissing && substr($translation,0,1)=="!" && substr($translation,-1)=="!")
  927       {           
  928           $res = "<A href=\"javascript:OpenPhraseEditor('&direct=1&label=$phrase'); \">$translation</A>";
  929           return $res;
  930       }
  931       else
  932           return $translation;
  933   }
  934  
  935   function prompt_language($phrase,$lang=0)
  936   {
  937     return admin_language($phrase,$lang,TRUE);    
  938   }
  939  
  940   function GetPrimaryTranslation($Phrase)
  941   {
  942           global $objLanguages;
  943  
  944           $l = $objLanguages->GetPrimary();
  945           return language($Phrase,$l);
  946   }
  947  
  948   function CategoryNameCount($ParentId,$Name)
  949   {
  950           $cat_table = GetTablePrefix()."Category";
  951           $sql = "SELECT Name from $cat_table WHERE ParentId=$ParentId AND ";
  952           $sql .="(Name LIKE '".addslashes($Name)."' OR Name LIKE 'Copy of ".addslashes($Name)."' OR Name LIKE 'Copy % of ".addslashes($Name)."')";
  953  
  954           $ado = &GetADODBConnection();
  955           $rs = $ado->Execute($sql);
  956           $ret = array();
  957           while($rs && !$rs->EOF)
  958           {
  959                   $ret[] = $rs->fields["Name"];
  960                   $rs->MoveNext();
  961           }
  962           return $ret;
  963   }       
  964  
  965   function CategoryItemNameCount($CategoryId,$Table,$Field,$Name)
  966   {
  967           $Name=addslashes($Name);
  968           $cat_table = GetTablePrefix()."CategoryItems";
  969           $sql = "SELECT $Field FROM $Table INNER JOIN $cat_table ON ($Table.ResourceId=$cat_table.ItemResourceId) ";
  970           $sql .=" WHERE ($Field LIKE 'Copy % of $Name' OR $Field LIKE '$Name' OR $Field LIKE 'Copy of $Name') AND CategoryId=$CategoryId";
  971           //echo $sql."<br>\n ";
  972           $ado = &GetADODBConnection();
  973           $rs = $ado->Execute($sql);
  974           $ret = array();
  975           while($rs && !$rs->EOF)
  976           {
  977                   $ret[] = $rs->fields[$Field];
  978                   $rs->MoveNext();
  979           }
  980           return $ret;    
  981   }
  982  
  983   function &GetItemCollection($ItemName)
  984   {
  985     global $objItemTypes;
  986  
  987     if(is_numeric($ItemName))
  988     {
  989           $item = $objItemTypes->GetItem($ItemName);
  990     }
  991     else
  992       $item = $objItemTypes->GetTypeByName($ItemName);
  993     if(is_object($item))
  994     {
  995           $module = $item->Get("Module");
  996           $prefix = ModuleTagPrefix($module);
  997           $func = $prefix."_ItemCollection";
  998           if(function_exists($func))
  999           {
  1000             $var =& $func();
  1001           }
  1002     }
  1003     return $var;
  1004   }
  1005  
  1006            
  1007   function UpdateCategoryCount($item_type,$CategoriesIds,$ListType='')
  1008   {
  1009           global $objCountCache, $objItemTypes;
  1010           $db=&GetADODBConnection();
  1011           if( !is_numeric($item_type) )
  1012           {
  1013                   $sql = 'SELECT ItemType FROM '.$objItemTypes->SourceTable.' WHERE ItemName=\''.$item_type.'\'';
  1014                   $item_type=$db->GetOne($sql);
  1015           }
  1016           $objCountCache->EraseGlobalTypeCache($item_type);
  1017           if($item_type)
  1018           {
  1019                   if(is_array($CategoriesIds))
  1020                   {
  1021                           $CategoriesIds=implode(',',$CategoriesIds);
  1022                   }
  1023                   if (!$CategoriesIds)
  1024                   {
  1025                           
  1026                   }
  1027                   
  1028                   if(!is_array($ListType)) $ListType=Array($ListType=>'opa');
  1029                   
  1030                   $sql = 'SELECT ParentPath FROM '.GetTablePrefix().'Category WHERE CategoryId IN ('.$CategoriesIds.')';
  1031                   $rs = $db->Execute($sql);
  1032                   $parents = Array();
  1033                   while (!$rs->EOF)
  1034                   {
  1035                           $tmp=$rs->fields['ParentPath'];
  1036                           $tmp=substr($tmp,1,strlen($tmp)-2);
  1037                           $tmp=explode('|',$tmp);
  1038                           foreach ($tmp as $tmp_cat_id) {
  1039                                   $parents[$tmp_cat_id]=1;
  1040                           }
  1041                           $rs->MoveNext();        
  1042                   }
  1043                   $parents=array_keys($parents);
  1044                   $list_types=array_keys($ListType);
  1045                   foreach($parents as $ParentCategoryId)
  1046                   {
  1047                           foreach ($list_types as $list_type) {
  1048                                   $objCountCache->DeleteValue($list_type, $item_type, $ParentCategoryId, 0);      // total count
  1049                                   $objCountCache->DeleteValue($list_type, $item_type, $ParentCategoryId, 1);      // total count today
  1050                           }
  1051                   }
  1052           }
  1053           else
  1054           {
  1055                   die('wrong item type passed to "UpdateCategoryCount"');
  1056           }
  1057    
  1058   /*      if(is_object($item))
  1059           {       
  1060                   $ItemType  = $item->Get("ItemType");
  1061           
  1062                   $sql = "DELETE FROM ".$objCountCache->SourceTable." WHERE ItemType=$ItemType";
  1063                   if( is_numeric($ListType) ) $sql .= " AND ListType=$ListType";
  1064                   $objCountCache->adodbConnection->Execute($sql);
  1065           }  */
  1066   }
  1067  
  1068   function ResetCache($CategoryId)
  1069   {
  1070           global $objCountCache;
  1071           $db =& GetADODBConnection();
  1072           $sql = 'SELECT ParentPath FROM '.GetTablePrefix().'Category WHERE CategoryId = '.$CategoryId;
  1073           $parents = $db->GetOne($sql);
  1074           $parents = substr($parents,1,strlen($parents)-2);
  1075           $parents = explode('|',$parents);
  1076           foreach($parents as $ParentCategoryId)
  1077           {
  1078                   $objCountCache->DeleteValue('_', TYPE_TOPIC, $ParentCategoryId, 0);     // total topic count
  1079                   $objCountCache->DeleteValue('_', TYPE_TOPIC, $ParentCategoryId, 1);     // total
  1080           }
  1081   }
  1082  
  1083   function UpdateModifiedCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$ExtraId=NULL)
  1084   {
  1085   }
  1086  
  1087   function UpdateGroupCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$GroupId=NULL)
  1088   {
  1089   }
  1090  
  1091   function GetTagCache($module,$tag,$attribs,$env)
  1092   {
  1093       global $objSystemCache, $objSession, $objConfig;
  1094  
  1095       if($objConfig->Get("SystemTagCache") && !$objSession->Get('PortalUserId'))
  1096       {
  1097           $name = $tag;
  1098           if(is_array($attribs))
  1099           {   
  1100               foreach($attribs as $n => $val)
  1101               {   
  1102                   $name .= "-".$val;
  1103               }
  1104           }
  1105           $CachedValue = $objSystemCache->GetContextValue($name,$module,$env, $objSession->Get("GroupList"));
  1106       }
  1107       else
  1108           $CachedValue="";
  1109       return $CachedValue;
  1110   }
  1111  
  1112   function SaveTagCache($module, $tag, $attribs, $env, $newvalue)
  1113   {
  1114       global $objSystemCache, $objSession, $objConfig;
  1115  
  1116       if($objConfig->Get("SystemTagCache"))
  1117       {
  1118           $name = $tag;
  1119           if(is_array($attribs))
  1120           {   
  1121               foreach($attribs as $a => $val)
  1122               {   
  1123                   $name .= "-".$val;
  1124               }
  1125           }
  1126           $objSystemCache->EditCacheItem($name,$newvalue,$module,0,$env,$objSession->Get("GroupList"));
  1127       }
  1128   }
  1129  
  1130   function DeleteTagCache($name,$extraparams, $env="")
  1131   {
  1132       global $objSystemCache, $objConfig;
  1133  
  1134       if($objConfig->Get("SystemTagCache"))
  1135       {
  1136           $where = "Name LIKE '$name%".$extraparams."'";
  1137           if(strlen($env))
  1138               $where .= " AND Context LIKE $env";
  1139           $objSystemCache->DeleteCachedItem($where);
  1140       }
  1141   }
  1142  
  1143   /**
  1144    * Deletes whole tag cache for
  1145    * selected module
  1146    *
  1147    * @param string $module
  1148    * @param string $name
  1149    * @access public
  1150    */
  1151   function DeleteModuleTagCache($module, $tagname='')
  1152   {
  1153       global $objSystemCache, $objConfig;
  1154  
  1155       if($objConfig->Get("SystemTagCache"))
  1156       {
  1157           $where = 'Module LIKE \''.$module.'\'';
  1158           if(strlen($tagname))
  1159           {
  1160               $where .= ' AND Name LIKE \''.$tagname.'\'';
  1161           }
  1162           $objSystemCache->DeleteCachedItem($where);
  1163       }
  1164   }
  1165  
  1166  
  1167  
  1168   /*function ClearTagCache()
  1169   {
  1170       global $objSystemCache, $objConfig;
  1171  
  1172       if($objConfig->Get("SystemTagCache"))
  1173       {
  1174           $where = '';
  1175           $objSystemCache->DeleteCachedItem($where);
  1176       }
  1177   }*/
  1178  
  1179   /*function EraseCountCache()
  1180   {
  1181   //  global $objSystemCache, $objConfig;
  1182  
  1183       $db =& GetADODBConnection();
  1184       $sql = 'DELETE * FROM '.GetTablePrefix().'CountCache';
  1185       return $db->Execute($sql) ? true : false;
  1186   }*/
  1187  
  1188  
  1189   function ParseTagLibrary()
  1190   {
  1191           $objTagList = new clsTagList();
  1192           $objTagList->ParseInportalTags();
  1193           unset($objTagList);
  1194   }
  1195  
  1196   function GetDateFormat($LangId=0)
  1197   {
  1198     global $objLanguages
  1199    
  1200     if(!$LangId)
  1201       $LangId= $objLanguages->GetPrimary();
  1202     $l = $objLanguages->GetItem($LangId); 
  1203     if(is_object($l))
  1204     {
  1205           $fmt = $l->Get("DateFormat");
  1206     }
  1207     else
  1208       $fmt = "m-d-Y";
  1209  
  1210           if(isset($GLOBALS['FrontEnd'])&&$GLOBALS['FrontEnd'])
  1211                   return $fmt;
  1212           return preg_replace('/y+/i','Y',$fmt);
  1213   }
  1214  
  1215   function GetTimeFormat($LangId=0)
  1216   {
  1217     global $objLanguages
  1218    
  1219     if(!$LangId)
  1220       $LangId= $objLanguages->GetPrimary();
  1221     $l = $objLanguages->GetItem($LangId); 
  1222     if(is_object($l))
  1223     {
  1224           $fmt = $l->Get("TimeFormat");
  1225     }
  1226     else
  1227       $fmt = "H:i:s";
  1228     return $fmt;  
  1229   }
  1230  
  1231   /**
  1232    * Gets one of currently selected language options
  1233    *
  1234    * @param string $optionName
  1235    * @param int $LangId
  1236    * @return string
  1237    * @access public
  1238    */
  1239   function GetRegionalOption($optionName,$LangId=0)
  1240   {
  1241           global $objLanguages, $objSession;
  1242           
  1243           if(!$LangId) $LangId=$objSession->Get('Language');
  1244           if(!$LangId) $LangId=$objLanguages->GetPrimary();
  1245           $l = $objLanguages->GetItem($LangId);
  1246           return is_object($l)?$l->Get($optionName):false;
  1247   }
  1248  
  1249   function LangDate($TimeStamp=NULL,$LangId=0)
  1250  
  1251     $fmt = GetDateFormat($LangId);
  1252     $ret = adodb_date($fmt,$TimeStamp);
  1253     return $ret;
  1254   }
  1255  
  1256   function LangTime($TimeStamp=NULL,$LangId=0)
  1257   {
  1258     $fmt = GetTimeFormat($LangId);
  1259     $ret = adodb_date($fmt,$TimeStamp);
  1260     return $ret;
  1261   }
  1262  
  1263   function LangNumber($Num,$DecPlaces=NULL,$LangId=0)
  1264   {
  1265           global $objLanguages;
  1266           
  1267     if(!$LangId)
  1268       $LangId= $objLanguages->GetPrimary();
  1269     $l = $objLanguages->GetItem($LangId); 
  1270     if(is_object($l))
  1271     {
  1272           $ret = number_format($Num,$DecPlaces,$l->Get("DecimalPoint"),$l->Get("ThousandSep"));
  1273     }
  1274     else
  1275       $ret = $num;
  1276      
  1277     return $ret;  
  1278   }
  1279  
  1280   function replacePngTags($x, $spacer="images/spacer.gif")
  1281   {
  1282           global $rootURL,$pathtoroot;
  1283           
  1284       // make sure that we are only replacing for the Windows versions of Internet
  1285       // Explorer 5+, and not Opera identified as MSIE
  1286       $msie='/msie\s([5-9])\.?[0-9]*.*(win)/i';
  1287       $opera='/opera\s+[0-9]+/i';
  1288       if(!isset($_SERVER['HTTP_USER_AGENT']) ||
  1289           !preg_match($msie,$_SERVER['HTTP_USER_AGENT']) ||
  1290           preg_match($opera,$_SERVER['HTTP_USER_AGENT']))
  1291           return $x;
  1292      
  1293       // find all the png images in backgrounds
  1294       preg_match_all('/background-image:\s*url\(\'(.*\.png)\'\);/Uis',$x,$background);
  1295       for($i=0;$i<count($background[0]);$i++){
  1296           // simply replace:
  1297           //  "background-image: url('image.png');"
  1298           // with:
  1299           //  "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(
  1300           //      enabled=true, sizingMethod=scale src='image.png');"
  1301           // haven't tested to see if background-repeat styles work...
  1302           $x=str_replace($background[0][$i],'filter:progid:DXImageTransform.'.
  1303                   'Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale'.
  1304                   ' src=\''.$background[1][$i].'\');',$x);
  1305       }
  1306  
  1307       // OK, time to find all the IMG tags with ".png" in them
  1308       preg_match_all('/(<img.*\.png.*>|<input.*type=([\'"])image\\2.*\.png.*>)/Uis',$x,$images);
  1309       while(list($imgnum,$v)=@each($images[0])){
  1310           $original=$v;
  1311           $atts=''; $width=0; $height=0;
  1312           // If the size is defined by styles, find
  1313           preg_match_all('/style=".*(width: ([0-9]+))px.*'.
  1314                           '(height: ([0-9]+))px.*"/Ui',$v,$arr2);
  1315           if(is_array($arr2) && count($arr2[0])){
  1316               // size was defined by styles, get values
  1317               $width=$arr2[2][0];
  1318               $height=$arr2[4][0];
  1319           }
  1320           // size was not defined by styles, get values
  1321           preg_match_all('/width=\"?([0-9]+)\"?/i',$v,$arr2);
  1322           if(is_array($arr2) && count($arr2[0])){
  1323               $width=$arr2[1][0];
  1324           }
  1325           preg_match_all('/height=\"?([0-9]+)\"?/i',$v,$arr2);
  1326           if(is_array($arr2) && count($arr2[0])){
  1327               $height=$arr2[1][0];
  1328           }
  1329           preg_match_all('/src=\"([^\"]+\.png)\"/i',$v,$arr2);
  1330           if(isset($arr2[1][0]) && !empty($arr2[1][0]))
  1331               $image=$arr2[1][0];
  1332           else
  1333               $image=NULL;
  1334  
  1335           // We do this so that we can put our spacer.gif image in the same
  1336           // directory as the image
  1337           $tmp=split('[\\/]',$image);
  1338           array_pop($tmp);
  1339           $image_path=join('/',$tmp);
  1340              if(substr($image,0,strlen($rootURL))==$rootURL)
  1341              {
  1342                           $path = str_replace($rootURL,$pathtoroot,$image);
  1343              }
  1344             else
  1345             {
  1346                           $path = $pathtoroot."themes/telestial/$image";
  1347             }     
  1348   //        echo "Sizing $path.. <br>\n";
  1349   //        echo "Full Tag: ".htmlentities($image)."<br>\n";       
  1350           //if(!$height || !$width)
  1351           //{
  1352  
  1353             $g = imagecreatefrompng($path);
  1354             if($g)
  1355             {
  1356                   $height = imagesy($g);
  1357                   $width = imagesx($g);
  1358             }     
  1359           //}
  1360           if(strlen($image_path)) $image_path.='/';
  1361  
  1362           // end quote is already supplied by originial src attribute
  1363           $replace_src_with=$spacer.'" style="width: '.$width.
  1364               'px; height: '.$height.'px; filter: progid:DXImageTransform.'.
  1365               'Microsoft.AlphaImageLoader(src=\''.$image.'\', sizingMethod='.
  1366               '\'scale\')';
  1367          
  1368           // now create the new tag from the old
  1369           $new_tag=str_replace($image,$replace_src_with,$original);
  1370          
  1371           // now place the new tag into the content
  1372           $x=str_replace($original,$new_tag,$x);
  1373       }
  1374       return $x;
  1375   }
  1376  
  1377   if (!function_exists('print_pre')) {
  1378           function print_pre($str)
  1379           {
  1380                   // no comments here :)
  1381                   echo '<pre>'.print_r($str, true).'</pre>';
  1382           }
  1383   }
  1384  
  1385   function GetOptions($field) // by Alex
  1386   {
  1387           // get dropdown values from custom field
  1388           $tmp =& new clsCustomField();
  1389           
  1390           $tmp->LoadFromDatabase($field, 'FieldName');
  1391           $tmp_values = $tmp->Get('ValueList');
  1392           unset($tmp);
  1393           $tmp_values = explode(',', $tmp_values);
  1394           
  1395           foreach($tmp_values as $mixed)
  1396           {
  1397                   $elem = explode('=', trim($mixed));
  1398                   $ret[ $elem[0] ] = $elem[1];
  1399           }
  1400           return $ret;
  1401   }
  1402  
  1403   function ResetPage($module_prefix, $page_variable = 'p')
  1404   {
  1405           // resets page in specific module when category is changed      
  1406           global $objSession;
  1407           if( !is_object($objSession) ) // when changing pages session doesn't exist -> InPortal BUG
  1408           {
  1409                   global $var_list, $SessionQueryString, $FrontEnd;
  1410                   //if(!$var_list["sid"]) $var_list["sid"] = $_COOKIE["sid"];
  1411                   $objSession = new clsUserSession($var_list["sid"],($SessionQueryString && $FrontEnd==1));
  1412           }
  1413           //echo "SID_RESET: ".$GLOBALS['var_list']["sid"].'(COOKIE_SID: '.$_COOKIE["sid"].')<br>';
  1414           $last_cat = $objSession->GetVariable('last_category');
  1415           $prev_cat = $objSession->GetVariable('prev_category');
  1416           //echo "Resetting Page [$prev_cat] -> [$last_cat]<br>";
  1417           
  1418           if($prev_cat != $last_cat) $GLOBALS[$module_prefix.'_var_list'][$page_variable] = 1;
  1419   }
  1420  
  1421   if( !function_exists('GetVar') )
  1422   {
  1423           /**
  1424           * @return string
  1425           * @param string $name
  1426           * @param bool $post_priority
  1427           * @desc Get's variable from http query
  1428           */
  1429           function GetVar($name, $post_priority = false)
  1430           {
  1431                   if(!$post_priority) // follow gpc_order in php.ini
  1432                           return isset($_REQUEST[$name]) ? $_REQUEST[$name] : false;
  1433                   else    // get variable from post 1stly if not found then from get
  1434                           return isset($_POST[$name]) && $_POST[$name] !== false ? $_POST[$name] : ( isset($_GET[$name]) && $_GET[$name] ? $_GET[$name] : false );        
  1435           }
  1436   }
  1437  
  1438   function SetVar($VarName, $VarValue)
  1439   {
  1440           $_REQUEST[$VarName] = $VarValue;        
  1441           $_POST[$VarName] = $VarValue;
  1442   }
  1443  
  1444   function PassVar(&$source)
  1445   {
  1446           // source array + any count of key names in passed array        
  1447           $params = func_get_args();
  1448           array_shift($params);
  1449           
  1450           if( count($params) )
  1451           {
  1452                   $ret = Array();
  1453                   foreach($params as $var_name)
  1454                           if( isset($source[$var_name]) )
  1455                                   $ret[] = $var_name.'='.$source[$var_name];
  1456                   $ret = '&'.implode('&', $ret);
  1457           }
  1458           return $ret;
  1459   }
  1460  
  1461   function GetSubmitVariable(&$array, $postfix)
  1462   {
  1463           // gets edit status of module
  1464           // used in case if some modules share
  1465           // common action parsed by kernel parser,
  1466           // but each module uses own EditStatus variable
  1467           
  1468           $modules = Array('In-Link' => 'Link', 'In-News' => 'News', 'In-Bulletin' => 'Topic', 'In-Portal'=>'Review');
  1469           foreach($modules as $module => $prefix)
  1470                   if( isset($array[$prefix.$postfix]) )
  1471                           return Array('Module' => $module, 'variable' => $array[$prefix.$postfix]);
  1472           return false;
  1473   }
  1474  
  1475   function GetModuleByAction()
  1476   {
  1477           $prefix2module = Array('m' => 'In-Portal', 'l' => 'In-Link', 'n' => 'In-News', 'bb' => 'In-Bulletin');
  1478           $action = GetVar('Action');
  1479           if($action)
  1480           {
  1481                   $module_prefix = explode('_', $action);
  1482                   return $prefix2module[ $module_prefix[0] ];
  1483           }
  1484           else
  1485                   return false;
  1486   }
  1487  
  1488   function dir_size($dir) {
  1489      // calculates folder size based on filesizes inside it (recursively)
  1490      $totalsize=0;
  1491      if ($dirstream = @opendir($dir)) {
  1492          while (false !== ($filename = readdir($dirstream))) {
  1493              if ($filename!="." && $filename!="..")
  1494              {
  1495                  if (is_file($dir."/".$filename))
  1496                      $totalsize+=filesize($dir."/".$filename);
  1497                 
  1498                  if (is_dir($dir."/".$filename))
  1499                      $totalsize+=dir_size($dir."/".$filename);
  1500              }
  1501          }
  1502      }
  1503      closedir($dirstream);
  1504      return $totalsize;
  1505   }
  1506  
  1507   function size($bytes) {
  1508     // shows formatted file/directory size
  1509     $types =  Array("la_bytes","la_kilobytes","la_megabytes","la_gigabytes","la_terabytes");
  1510      $current = 0;
  1511     while ($bytes > 1024) {
  1512      $current++;
  1513      $bytes /= 1024;
  1514     }
  1515     return round($bytes,2)." ".language($types[$current]);
  1516   }
  1517  
  1518   function echod($str)
  1519   {
  1520           // echo debug output
  1521           echo str_replace( Array('[',']'), Array('[<b>', '</b>]'), $str).'<br>'
  1522   }
  1523  
  1524  
  1525   function PrepareParams($source, $to_lower, $mapping)
  1526   {
  1527           // prepare array with form values to use with item
  1528           $result = Array();
  1529           foreach($to_lower as $field)
  1530                   $result[ $field ] = $source[ strtolower($field) ];
  1531           
  1532           if( is_array($mapping) )
  1533           {
  1534                   foreach($mapping as $field_from => $field_to)
  1535                           $result[$field_to] = $source[$field_from];
  1536           }
  1537           
  1538           return $result;
  1539   }
  1540  
  1541   function GetELT($field, $phrases = Array())
  1542   {
  1543           // returns FieldOptions equivalent in In-Portal
  1544           $ret = Array();
  1545           foreach($phrases as $phrase)
  1546                   $ret[] = admin_language($phrase);
  1547           $ret = "'".implode("','", $ret)."'";
  1548           return 'ELT('.$field.','.$ret.')';
  1549   }
  1550  
  1551   function GetModuleImgPath($module)
  1552   {
  1553           global $rootURL, $admin;
  1554           return $rootURL.$module.'/'.$admin.'/images';
  1555   }
  1556  
  1557   function ActionPostProcess($StatusField, $ListClass, $ListObjectName = '', $IDField = null)
  1558   {
  1559           // each action postprocessing stuff from admin
  1560           if( !isset($_REQUEST[$StatusField]) ) return false;
  1561           
  1562           $list =& $GLOBALS[$ListObjectName];
  1563           if( !is_object($list) ) $list = new $ListClass();
  1564           $SFValue = $_REQUEST[$StatusField]; // status field value
  1565           switch($SFValue)
  1566           {
  1567                   case 1: // User hit "Save" button
  1568                   $list->CopyFromEditTable($IDField);    
  1569                   break;
  1570                   case 2: // User hit "Cancel" button
  1571                           $list->PurgeEditTable($IDField);
  1572                           break;
  1573           }
  1574           if( function_exists('SpecificProcessing') ) SpecificProcessing($StatusField, $SFValue);
  1575           if($SFValue == 1 || $SFValue == 2) $list->Clear();
  1576   }
  1577  
  1578   if( !function_exists('getArrayValue') )
  1579   {
  1580           /**
  1581            * Returns array value if key exists
  1582            *
  1583            * @param Array $aArray
  1584            * @param int $aIndex
  1585            * @return string
  1586            */
  1587           function getArrayValue(&$aArray, $aIndex)
  1588           {
  1589                   return isset($aArray[$aIndex]) ? $aArray[$aIndex] : false;
  1590           }
  1591   }
  1592   function MakeHTMLTag($element, $attrib_prefix)
  1593   {
  1594           $result = Array();
  1595           $ap_length = strlen($attrib_prefix);
  1596           foreach($element->attributes as $attib_name => $attr_value)
  1597                   if( substr($attib_name, $ap_length) == $ap_length )
  1598                           $result[] = substr($attib_name, $ap_length, strlen($attib_name)).'="'.$attr_value.'"';
  1599           return count($result) ? implode(' ', $result) : false;
  1600   }
  1601  
  1602   function GetImportScripts()
  1603   {
  1604           // return currently installed import scripts    
  1605           static $import_scripts = Array();
  1606           if( count($import_scripts) == 0 )
  1607           {
  1608                   $sql = 'SELECT * FROM '.GetTablePrefix().'ImportScripts ORDER BY is_id';
  1609                   $db =&GetADODBConnection();
  1610                   $rs = $db->Execute($sql);
  1611                   if( $rs && $rs->RecordCount() > 0 )
  1612                   {
  1613                           while(!$rs->EOF)
  1614                           {
  1615                                   $rec =& $rs->fields;
  1616                                   $import_scripts[] = Array(      'label' => $rec['is_label'], 'url' => $rec['is_script'],
  1617                                                                                           'enabled' => $rec['is_enabled'], 'field_prefix' => $rec['is_field_prefix'],
  1618                                                                                           'id' => $rec['is_string_id'], 'required_fields' => $rec['is_requred_fields'],
  1619                                                                                           'module' => strtolower($rec['is_Module']) );
  1620                                   $rs->MoveNext();        
  1621                           }
  1622                   }
  1623                   else
  1624                   {
  1625                           $import_scripts = Array();      
  1626                   }
  1627           }
  1628           return $import_scripts;
  1629   }
  1630  
  1631   function GetImportScript($id)
  1632   {
  1633           $scripts = GetImportScripts();
  1634           return isset($scripts[$id]) ? $scripts[$id] : false;
  1635   }
  1636   function GetNextTemplate($current_template)
  1637   {
  1638           // used on front, returns next template to make
  1639           // redirect to
  1640           $dest = GetVar('dest', true);
  1641           if(!$dest) $dest = GetVar('DestTemplate', true);
  1642           return $dest ? $dest : $current_template;
  1643   }
  1644  
  1645  
  1646   // functions for dealign with enviroment variable construction
  1647   function GenerateModuleEnv($prefix, $var_list)
  1648   {
  1649           // globalize module varible arrays
  1650           $main =& $GLOBALS[$prefix.'_var_list'];
  1651           $update =& $GLOBALS[$prefix.'_var_list_update'];
  1652           //echo "VAR: [$main]; VAR_UPDATE: [$update]<br>";
  1653           
  1654           // ensure that we have no empty values in enviroment variable
  1655           foreach($update as $vl_key => $vl_value)
  1656           if(!$vl_value) $update[$vl_key] = '0'; // unset($update[$vl_key]);
  1657     
  1658       // if update var count is zero, then do nothing
  1659       if(count($update) == 0) return '';
  1660  
  1661       foreach($main as $vl_key => $vl_value)
  1662           if(!$vl_value) $main[$vl_key] = '0'; // unset($main[$vl_key]);
  1663      
  1664           $ret = Array();
  1665           foreach($var_list as $var_name)
  1666                   $ret[] = GetEnvVar($prefix, $var_name);
  1667           
  1668           return ':'.$prefix.implode('-',$ret);
  1669   }
  1670  
  1671   function GetEnvVar($prefix, $name)
  1672   {
  1673           // get variable from template variable's list
  1674           // (used in module parsers to build env string)
  1675           $main =& $GLOBALS[$prefix.'_var_list'];
  1676           $update =& $GLOBALS[$prefix.'_var_list_update'];
  1677  
  1678           return isset($update[$name]) ? $update[$name] : ( isset($main[$name]) ? $main[$name] : '');
  1679   }
  1680  
  1681   /**
  1682    * @return int
  1683    * @desc Checks for debug mode
  1684   */
  1685   function IsDebugMode()
  1686   {
  1687           return defined('DEBUG_MODE') && constant('DEBUG_MODE') == 1 ? 1 : 0;    
  1688   }
  1689  
  1690   /**
  1691    * Two strings in-case-sensitive compare.
  1692    * Returns >0, when string1 > string2,
  1693    *         <0, when string1 > string2,
  1694    *          0, when string1 = string2
  1695    *
  1696    * @param string $string1
  1697    * @param string $string2
  1698    * @return int
  1699    */
  1700   function stricmp ($string1, $string2) {
  1701           return strcmp(strtolower($string1), strtolower($string2));
  1702   }
  1703  
  1704   /**
  1705    * Generates unique code
  1706    *
  1707    * @return string
  1708    */
  1709   function GenerateCode()
  1710   {
  1711           list($usec, $sec) = explode(" ",microtime());
  1712  
  1713           $id_part_1 = substr($usec, 4, 4);
  1714           $id_part_2 = mt_rand(1,9);
  1715           $id_part_3 = substr($sec, 6, 4);
  1716           $digit_one = substr($id_part_1, 0, 1);
  1717           if ($digit_one == 0) {
  1718                   $digit_one = mt_rand(1,9);
  1719                   $id_part_1 = ereg_replace("^0","",$id_part_1);
  1720                   $id_part_1=$digit_one.$id_part_1;
  1721           }
  1722           return $id_part_1.$id_part_2.$id_part_3;
  1723   }
  1724  
  1725   ?>