1   <?php
  2   //global $g_DBType,$g_DBHost,$g_DBUser,$g_DBUserPassword,$g_DBName,$g_EnableCookies;
  3  
  4   $vars = parse_ini_file($pathtoroot."config.php");
  5  
  6   while($key = key($vars))
  7   {
  8     $key = "g_".$key;
  9     global $$key;
  10     $$key = current($vars); //variable variables
  11     next($vars);
  12   }
  13  
  14   /*list the tables which contain item data */
  15   $ItemTables = array();
  16  
  17   $KeywordIgnore = array();
  18   global $debuglevel;
  19  
  20   $debuglevel=0;
  21   $_GLOBALS["debuglevel"]=0;
  22  
  23   /*New, Hot, Pop field values */
  24   define('NEVER', 0);
  25   define('ALWAYS', 1);
  26   define('AUTO', 2);
  27  
  28   /*Status Values */
  29   define('STATUS_DISABLED', 0);
  30   define('STATUS_ACTIVE', 1);
  31   define('STATUS_PENDING', 2);
  32  
  33   $LogLevel=0;
  34   $LogFile = NULL;
  35  
  36   function &GetADODBConnection()
  37   {
  38           global $g_adodbConnection, $g_DBType, $g_DBHost,$g_DBUser,$g_DBUserPassword,$g_DBName,$g_DebugMode;
  39       global $ADODB_FETCH_MODE,$ADODB_COUNTRECS,$ADODB_CACHE_DIR,$pathtoroot;
  40  
  41       if(!isset($g_adodbConnection) && strlen($g_DBType)>0)
  42       {
  43                   $g_adodbConnection = ADONewConnection($g_DBType);
  44                   $connected = $g_adodbConnection->Connect($g_DBHost,$g_DBUser,$g_DBUserPassword,$g_DBName);
  45           if(!$connected)
  46           {
  47               echo "Error connecting to database $g_DBHost <br>\n";
  48               die();
  49           }
  50           $ADODB_CACHE_DIR = $pathtoroot."cache";
  51           $ADODB_FETCH_MODE = 2;   
  52           $ADODB_COUNTRECS = FALSE;
  53           $g_adodbConnection->debug = false;
  54           $g_adodbConnection->cacheSecs = 3600;
  55       }
  56       elseif (!strlen($g_DBType)) {
  57           global $rootURL;
  58           echo "In-Portal is probably not installed, or configuration file is missing.<br>";
  59                           echo "Please use the installation script to fix the problem.<br><br>";
  60                           if (!preg_match('/admin/', $_SERVER['SCRIPT_FILENAME'])) {
  61                                   $ins = 'admin/';
  62                           }
  63                           echo "<a href='$rootURL".$ins."install.php'>Go to installation script</a><br><br>";
  64                           flush();
  65                           die();
  66       }
  67           return $g_adodbConnection;
  68   }
  69  
  70   function GetNextResourceId($Increment=1)
  71   {
  72           $sql = "UPDATE ".GetTablePrefix()."IdGenerator SET lastid=lastid+".$Increment;
  73       $adodbConnection = GetADODBConnection();
  74       $adodbConnection->Execute($sql);   
  75       $rs = $adodbConnection->Execute("SELECT lastid FROM ".GetTablePrefix()."IdGenerator");
  76       $val = $rs->fields["lastid"];
  77       if(!$rs || $rs->EOF)
  78       {  
  79           echo $adodbConnection->ErrorMsg();
  80           $sql = "INSERT INTO ".GetTablePrefix()."IdGenerator (lastid) VALUES ($Increment)";
  81           $adodbConnection->Execute($sql);
  82           $val = 1;
  83       }
  84       $val = $val-($Increment-1);
  85       return $val;
  86   }
  87  
  88   function AddSlash($s)
  89   {
  90       if(substr($s,-1) != "/")
  91       {
  92           return $s."/";
  93       }
  94       else
  95           return $s;
  96   }
  97  
  98   function StripNewline($s)
  99   {
  100           $bfound = false;
  101           while (strlen($s)>0 && !$bfound)
  102           {
  103                   if(ord(substr($s,-1))<32)
  104                   {
  105                           $s = substr($s,0,-1);
  106                   }
  107                   else
  108                     $bfound = true;
  109           }
  110           return $s;
  111   }
  112  
  113   function DeleteElement($array, $indice)
  114   {
  115     for($i=$indice;$i<count($array)-1;$i++)
  116           $array[$i] = $array[$i+1];
  117     unset($array[count($array)-1]);
  118     return $array;
  119   }
  120  
  121   function DeleteElementValue($needle, &$haystack)
  122   {
  123     while(($gotcha = array_search($needle,$haystack)) > -1)
  124      unset($haystack[$gotcha]);
  125   }       
  126  
  127   function TableCount($TableName, $where="",$JoinCats=1)
  128   {
  129       $db = GetADODBConnection();
  130       if(!$JoinCats)
  131       {   
  132         $sql = "SELECT count(*) as TableCount FROM $TableName";
  133       }
  134       else
  135           $sql = "SELECT count(*) as TableCount FROM $TableName INNER JOIN ".GetTablePrefix()."CategoryItems ON ".GetTablePrefix()."CategoryItems.ItemResourceId=$TableName.ResourceId";
  136       if(strlen($where)>0)
  137           $sql .= " WHERE ".$where;
  138       $rs = $db->Execute($sql);
  139          
  140   //    echo "SQL TABLE COUNT: ".$sql."<br>\n";
  141      
  142       $res = $rs->fields["TableCount"];
  143       return $res;
  144   }
  145  
  146   Function QueryCount($sql)
  147   {
  148     $countsql = "SELECT count(*) as TableCount ".substr($sql,strpos($sql," FROM "));
  149     if(strpos($countsql,"LIMIT"))
  150       $countsql = substr($countsql,0,strpos($countsql,"LIMIT"));
  151     if(strpos($countsql,"ORDER BY"))
  152       $countsql = substr($countsql,0,strpos($countsql,"ORDER BY"));
  153      
  154     $db = GetADODBConnection();
  155     $rs = $db->Execute($countsql);
  156     //echo $countsql."<br>\n";
  157     $res = $rs->fields["TableCount"];
  158     return $res
  159   }
  160      
  161   function GetPageCount($ItemsPerPage,$NumItems)
  162   {
  163    if($ItemsPerPage==0 || $NumItems==0)
  164    {
  165      return 1;
  166    }           
  167    $value = $NumItems/$ItemsPerPage;
  168    return ceil($value);       
  169   }
  170  
  171  
  172   function GetTablePrefix()
  173   {
  174       global $g_TablePrefix;
  175  
  176       return $g_TablePrefix;
  177   }
  178  
  179   function TableHasPrefix($t)
  180   {
  181           $pre = GetTablePrefix();
  182           
  183           if(strlen($pre)>0)
  184           {
  185                   if(substr($t,0,strlen($pre))==$pre)
  186                   {
  187                           return TRUE;
  188                   }
  189                   else
  190                     return FALSE;
  191           }
  192           else
  193             return TRUE;
  194   }
  195  
  196   function AddTablePrefix($t)
  197   {
  198           if(!TableHasPrefix($t))
  199             $t = GetTablePrefix().$t;
  200            
  201           return $t;
  202   }
  203  
  204   function ThisDomain()
  205   {
  206           global $objConfig, $g_Domain;
  207           
  208           if($objConfig->Get("DomainDetect"))
  209           {
  210                   $d = $_SERVER['HTTP_HOST'];
  211           }
  212           else
  213             $d = $g_Domain;
  214            
  215           return $d;
  216   }
  217  
  218   function GetIndexUrl($secure=0)
  219   {
  220       global $indexURL, $rootURL, $secureURL;
  221      
  222       switch($secure)
  223       {
  224           case 0:
  225                   $ret = $indexURL;
  226           break;
  227           case 1:
  228                   $ret = $secureURL."index.php";                  
  229           break;  
  230           case 2:
  231                   $ret = $rootURL."index.php";
  232           break;
  233           default:
  234                   $ret = $i;      
  235       }                                   
  236       return $ret;
  237   }
  238  
  239   function GetLimitSQL($Page,$PerPage)
  240   {
  241     if($Page<1)
  242       $Page=1;
  243  
  244     if(is_numeric($PerPage))
  245     {
  246             if($PerPage==0)        
  247               $PerPage = 20;
  248         $Start = ($Page-1)*$PerPage;
  249         $limit = "LIMIT ".$Start.",".$PerPage;
  250     }
  251     else
  252         $limit = NULL;
  253     return $limit;
  254   }
  255  
  256   function filelist ($currentdir, $startdir=NULL,$ext=NULL)
  257   {
  258     global $pathchar;
  259  
  260     //chdir ($currentdir);
  261  
  262     // remember where we started from
  263     if (!$startdir)
  264     {
  265         $startdir = $currentdir;
  266     }
  267  
  268     $d = @opendir($currentdir);
  269  
  270     $files = array();
  271     if(!$d)
  272       return $files
  273     //list the files in the dir
  274     while (false !== ($file = readdir($d)))
  275     {
  276         if ($file != ".." && $file != ".")
  277         {
  278             if (is_dir($currentdir."/".$file))
  279             {
  280                 // If $file is a directory take a look inside
  281                 $a = filelist ($currentdir."/".$file, $startdir,$ext);
  282                 if(is_array($a))
  283                   $files = array_merge($files,$a);
  284             }
  285             else
  286             {
  287                 if($ext!=NULL)
  288                 {
  289                     $extstr = stristr($file,".".$ext);
  290                     if(strlen($extstr))
  291                         $files[] = $currentdir."/".$file;
  292                 }
  293                 else
  294                   $files[] = $currentdir.'/'.$file;
  295             }
  296         }
  297     }
  298  
  299     closedir ($d);
  300  
  301     return $files;
  302   }       
  303  
  304   function DecimalToBin($dec,$WordLength=8)
  305   {
  306     $bits = array();
  307    
  308     $str = str_pad(decbin($dec),$WordLength,"0",STR_PAD_LEFT);
  309     for($i=$WordLength;$i>0;$i--)
  310     {
  311         $bits[$i-1] = (int)substr($str,$i-1,1);
  312     }
  313     return $bits;
  314   }
  315  
  316   function inp_escape($in, $html_enable=0)
  317   {
  318           $out = stripslashes($in);
  319           $out = str_replace("\n", "\n^br^", $out);
  320           if($html_enable==0)
  321           {
  322                   $out=ereg_replace("<","&lt;",$out);
  323                   $out=ereg_replace(">","&gt;",$out);
  324                   $out=ereg_replace("\"","&quot;",$out);
  325                   $out = str_replace("\n^br^", "\n<br />", $out);
  326           }       
  327           else
  328                   $out = str_replace("\n^br^", "\n", $out);
  329           $out=addslashes($out);
  330  
  331           return $out;
  332   }
  333  
  334   function inp_unescape($in)
  335   {
  336           $out=stripslashes($in);
  337  
  338           return $out;
  339   }
  340  
  341   function inp_textarea_unescape($in)
  342   {
  343           $out=stripslashes($in);
  344           $out = str_replace("\n<br />", "\n", $out);
  345           return $out;
  346   }
  347  
  348   function HighlightKeywords($Keywords, $html, $OpenTag="", $CloseTag="")
  349   {
  350       global $objConfig;
  351  
  352       if(!strlen($OpenTag))
  353           $OpenTag = "<B>";
  354       if(!strlen($CloseTag))
  355               $CloseTag = "</B>"
  356           
  357           $r = preg_split('((>)|(<))', $html, -1, PREG_SPLIT_DELIM_CAPTURE);
  358           
  359           foreach ($Keywords as $k) {             
  360                   for ($i = 0; $i < count($r); $i++) {
  361                  if ($r[$i] == "<") {
  362                      $i++; continue;
  363                  }
  364                  $r[$i] = preg_replace("/($k)/i", "$OpenTag\\1$CloseTag", $r[$i]);
  365               }
  366           }
  367           return join("", $r);
  368   }
  369  
  370   /*
  371   function HighlightKeywords($Keywords,$html, $OpenTag="", $CloseTag="")
  372   {
  373       global $objConfig;
  374  
  375       if(!strlen($OpenTag))
  376           $OpenTag = "<B>";
  377       if(!strlen($CloseTag))
  378               $CloseTag = "</B>";
  379       $ret = strip_tags($html);
  380  
  381       foreach ($Keywords as $k)
  382       {  
  383           if(strlen($k))
  384           {       
  385             //$html = str_replace("<$k>", ":#:", $html);
  386             //$html = str_replace("</$k>", ":##:", $html);
  387             //$html = strip_tags($html);
  388             if ($html = preg_replace("/($k)/Ui","$OpenTag\\1$CloseTag", $html))
  389             //if ($html = preg_replace("/(>[^<]*)($k)([^<]*< )/Ui","$OpenTag\\1$CloseTag", $html))
  390               $ret = $html;
  391             //$ret = str_replace(":#:", "<$k>", $ret);
  392             //$ret = str_replace(":##:", "</$k>", $ret);
  393           }
  394       }
  395       return $ret;       
  396   }
  397   */
  398   function ExtractDatePart($part,$datestamp)
  399   {
  400       switch($part)
  401       {
  402           case "month":
  403               if($datestamp<=0)
  404               {                       
  405                   $ret = "";
  406               }
  407               else
  408                 $ret = adodb_date("m",$datestamp);
  409           break;          
  410           case "day":
  411               if($datestamp<=0)
  412               {                       
  413                   $ret = "";
  414               }
  415               else
  416                   $ret = adodb_date("d", $datestamp);
  417           break;          
  418           case "year":
  419               if($datestamp<=0)
  420               {                       
  421                   $ret = "";
  422               }
  423               else
  424                   $ret = adodb_date("Y", $datestamp);
  425           break;
  426           case "time_24hr":
  427               if($datestamp<=0)
  428               {                       
  429                   $ret = "";
  430               }
  431               else
  432                   $ret = adodb_date("H:i", $datestamp);
  433           break;
  434           case "time_12hr":
  435               if($datestamp<=0)
  436               {
  437                   $ret = "";
  438               }
  439               else
  440                   $ret = adodb_date("g:i a",$datestamp);
  441          break;
  442        }
  443       return $ret;
  444   }
  445  
  446   function GetLocalTime($TimeStamp,$TargetZone=NULL)
  447   {
  448       if($TargetZone==NULL)
  449           $TargetZone = $objConfig->Get("Config_Site_Time");  
  450       $server = $objConfig->Get("Config_Server_Time");
  451       if($TargetZone!=$server)
  452       {   
  453         $offset = ($server - $TargetZone) * -1;
  454         $TimeStamp = $TimeStamp + (3600 * $offset);
  455       }
  456       return $TimeStamp;
  457   }
  458  
  459   function _unhtmlentities ($string)
  460   {
  461       $trans_tbl = get_html_translation_table (HTML_ENTITIES);
  462       $trans_tbl = array_flip ($trans_tbl);
  463       return strtr ($string, $trans_tbl);
  464   }
  465  
  466   function getLastStr($hay, $need){
  467     $getLastStr = 0;
  468     $pos = strpos($hay, $need);
  469     if (is_int ($pos)){ //this is to decide whether it is "false" or "0"
  470      while($pos) {
  471        $getLastStr = $getLastStr + $pos + strlen($need);
  472        $hay = substr ($hay , $pos + strlen($need));
  473        $pos = strpos($hay, $need);
  474      }
  475      return $getLastStr - strlen($need);
  476     } else {
  477      return -1; //if $need wasn´t found it returns "-1" , because it could return "0" if it´s found on position "0".
  478     }
  479   }
  480  
  481   function ReplaceSingleTag($tag,$text)
  482   {
  483     $opentag = "[".$tag;
  484     $closetag = "[/".$tag."]";
  485    
  486     if(strstr($text,$opentag))
  487     {  
  488       $pos = strpos($text,$opentag." ");
  489       if($pos === false)
  490       {
  491           $pos = strpos($text,$opentag."]");
  492       }
  493       $endopen = strpos($text,"]",$pos);
  494       $closepos = strpos($text,$closetag,$pos);
  495      
  496       if($closepos)
  497       {
  498           $taglength = ($closepos - $endopen) + strlen($closetag);
  499           $tagText = substr($text,$pos, $closepos + strlen($closetag) - $pos);      
  500           $innerText = substr($text,$endopen+1,$closepos - $endopen-1);
  501           if($tag=="UL")
  502               $innerText = str_replace("[*]","<LI>",$innerText);
  503           $tagText = substr($tagText,1,($endopen - $pos)-1);  
  504           //echo "Matched $tagText <br>\n";
  505           $tagText = "<".$tagText.">";
  506           $replace_text = $tagText.$innerText."</".$tag.">";
  507           $text = substr($text,0,$pos).$replace_text.substr($text,$closepos+strlen($closetag));
  508           return $text;
  509       }
  510       else
  511           return $text;
  512     }
  513     else
  514         return $text;
  515   }
  516  
  517   function ReplaceTag($tag,$text)
  518   {
  519     $new_text = ReplaceSingleTag($tag,$text);
  520    
  521     while($new_text != $text)
  522     {
  523         $text = $new_text;
  524         $new_text = ReplaceSingleTag($tag,$text);
  525     }
  526     return $new_text;
  527   }
  528  
  529   function ReplaceURL($text)
  530  
  531     while(strstr($text,"[URL"))
  532     {
  533       $urlpos = strpos($text,"[URL");
  534       $endopen = strpos($text,"]",$urlpos);
  535       if($endopen)
  536       {
  537           $url = "<A TARGET=\"_blank\"".substr($text,$urlpos+4,$endopen - ($urlpos+4));
  538           $url .= ">";
  539           $url = _unhtmlentities($url);
  540           $text = substr($text,0,$urlpos).$url.substr($text,$endopen+1);
  541       }
  542     }
  543     $text = str_replace("[/URL]","</A>",$text);
  544     return $text;
  545   }
  546  
  547  
  548   function ReplaceBBCode($text)
  549   {
  550     global $objConfig;
  551  
  552     $tags = explode(",",$objConfig->Get("BBTags"));
  553     for($i=0;$i<count($tags);$i++)
  554     {   
  555       $text = ReplaceTag(strtoupper($tags[$i]),$text);
  556     }
  557     $text = ReplaceURL($text);
  558     return $text;
  559   }
  560  
  561   function GetMinValue($Table,$Field, $Where=NULL)
  562   {
  563       $ret = 0;
  564       $sql = "SELECT min($Field) as val FROM $Table ";
  565       if(strlen($where))
  566           $sql .= "WHERE $Where";
  567       $ado = GetADODBConnection();
  568       $rs = $ado->execute($sql);
  569       if($rs)
  570           $ret = (int)$rs->fields["val"];
  571       return $ret;
  572   }
  573  
  574   function getmicrotime()
  575   {
  576       list($usec, $sec) = explode(" ",microtime());
  577       return ((float)$usec + (float)$sec);
  578   }
  579  
  580   function SetMissingDataErrors($f)
  581   {
  582       global $FormError;
  583  
  584       $count = 0;
  585       if(is_array($_POST))
  586       {   
  587         if(is_array($_POST["required"]))
  588         {     
  589           foreach($_POST["required"] as $r)
  590           {
  591             $found = FALSE;
  592             if(is_array($_FILES))
  593             {
  594               if($_FILES[$r]["size"]>0)
  595                   $found=TRUE;
  596             }
  597          
  598             if(!strlen(trim($_POST[$r])) && !$found)
  599             {          
  600               $count++;
  601              
  602               if (($r == "dob_day") || ($r == "dob_month") || ($r == "dob_year"))
  603                   $r = "dob";             
  604                   
  605               $tag = $_POST["errors"][$r];
  606               if(!strlen($tag))
  607                 $tag = "lu_ferror_".$f."_".$r;
  608               $FormError[$f][$r] = language($tag);
  609             }
  610           }
  611         }
  612       }
  613       return $count;
  614   }
  615  
  616   function makepassword($length=10)
  617   {
  618     $pass_length=$length;
  619  
  620     $p1=array('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z');
  621     $p2=array('a','e','i','o','u');
  622     $p3=array('1','2','3','4','5','6','7','8','9');  
  623     $p4=array('(','&',')',';','%');    // if you need real strong stuff
  624  
  625     // how much elements in the array
  626     // can be done with a array count but counting once here is faster
  627  
  628     $s1=21;// this is the count of $p1   
  629     $s2=5; // this is the count of $p2
  630     $s3=9; // this is the count of $p3
  631     $s4=5; // this is the count of $p4
  632  
  633     // possible readable combinations
  634  
  635     $c1='121';    // will be like 'bab'
  636     $c2='212';      // will be like 'aba'
  637     $c3='12';      // will be like 'ab'
  638     $c4='3';        // will be just a number '1 to 9'  if you dont like number delete the 3
  639   // $c5='4';        // uncomment to active the strong stuff
  640  
  641     $comb='4'; // the amount of combinations you made above (and did not comment out)
  642  
  643  
  644  
  645     for ($p=0;$p<$pass_length;)
  646     {
  647       mt_srand((double)microtime()*1000000);
  648       $strpart=mt_rand(1,$comb);
  649       // checking if the stringpart is not the same as the previous one
  650       if($strpart<>$previous)
  651       {
  652         $pass_structure.=${'c'.$strpart};
  653  
  654         // shortcutting the loop a bit
  655         $p=$p+strlen(${'c'.$strpart});
  656       }
  657       $previous=$strpart;
  658     }
  659  
  660  
  661     // generating the password from the structure defined in $pass_structure
  662     for ($g=0;$g<strlen($pass_structure);$g++)
  663     {
  664       mt_srand((double)microtime()*1000000);
  665       $sel=substr($pass_structure,$g,1);
  666       $pass.=${'p'.$sel}[mt_rand(0,-1+${'s'.$sel})];
  667  
  668     }
  669     return $pass;
  670   }
  671  
  672   function LogEntry($text,$writefile=FALSE)
  673   {
  674     global $g_LogFile,$LogFile, $LogData, $LogLevel, $timestart;
  675    
  676     static $last;
  677  
  678     if(strlen($g_LogFile))
  679     {
  680       $el = str_pad(getmicrotime()- $timestart,10," ");
  681       if($last>0)
  682         $elapsed = getmicrotime() - $last;
  683        
  684       if(strlen($el)>10)
  685           $el = substr($el,0,10);     
  686       $indent = str_repeat("  ",$LogLevel);
  687       $text = str_pad($text,$LogLevel,"==",STR_PAD_LEFT);
  688       $LogData .= "$el:". round($elapsed,6).":$indent $text";
  689       $last = getmicrotime();
  690       if($writefile==TRUE && is_writable($g_LogFile))
  691       {
  692         if(!$LogFile)      
  693         {
  694            if(file_exists($g_LogFile))
  695               unlink($g_LogFile);
  696           $LogFile=@fopen($g_LogFile,"w");
  697         }
  698         if($LogFile)
  699         {   
  700           fputs($LogFile,$LogData);
  701         }
  702       }
  703     }
  704   }
  705  
  706   function ValidEmail($email)
  707   {
  708       if (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $email))
  709       {
  710           return TRUE;
  711       }
  712       else
  713       {
  714           return FALSE;
  715       }
  716   }
  717  
  718   function language($phrase,$LangId=0)
  719   {
  720       global $objSession, $objLanguageCache, $objLanguages;
  721  
  722       if($LangId==0)
  723           $LangId = $objSession->Get("Language");
  724          
  725           if($LangId==0)
  726         $LangId = $objLanguages->GetPrimary();       
  727  
  728       $translation = $objLanguageCache->GetTranslation($phrase,$LangId);
  729  
  730       return $translation;
  731   }
  732  
  733   function admin_language($phrase,$lang=0,$LinkMissing=FALSE)
  734   {
  735       global $objSession, $objLanguageCache, $objLanguages;
  736      
  737           //echo "Language passed: $lang<br>";
  738           
  739       if($lang==0)
  740          $lang = $objSession->Get("Language");
  741  
  742       //echo "Language from session: $lang<br>";
  743      
  744           if($lang==0)
  745         $lang = $objLanguages->GetPrimary();  
  746           
  747       //echo "Language after primary: $lang<br>";
  748       //echo "Phrase: $phrase<br>";
  749           $translation = $objLanguageCache->GetTranslation($phrase,$lang);
  750       if($LinkMissing && substr($translation,0,1)=="!" && substr($translation,-1)=="!")
  751       {           
  752           $res = "<A href=\"javascript:OpenPhraseEditor('&direct=1&label=$phrase'); \">$translation</A>";
  753           return $res;
  754       }
  755       else
  756           return $translation;
  757   }
  758  
  759   function prompt_language($phrase,$lang=0)
  760   {
  761     return admin_language($phrase,$lang,TRUE);    
  762   }
  763  
  764   function GetPrimaryTranslation($Phrase)
  765   {
  766           global $objLanguages;
  767  
  768           $l = $objLanguages->GetPrimary();
  769           return language($Phrase,$l);
  770   }
  771  
  772   function CategoryNameCount($ParentId,$Name)
  773   {
  774           $cat_table = GetTablePrefix()."Category";
  775           $sql = "SELECT Name from $cat_table WHERE ParentId=$ParentId AND ";
  776           $sql .="(Name LIKE '".addslashes($Name)."' OR Name LIKE 'Copy of ".addslashes($Name)."' OR Name LIKE 'Copy % of ".addslashes($Name)."')";
  777  
  778           $ado = GetADODBConnection();
  779           $rs = $ado->Execute($sql);
  780           $ret = array();
  781           while($rs && !$rs->EOF)
  782           {
  783                   $ret[] = $rs->fields["Name"];
  784                   $rs->MoveNext();
  785           }
  786           return $ret;
  787   }       
  788  
  789   function CategoryItemNameCount($CategoryId,$Table,$Field,$Name)
  790   {
  791           $cat_table = GetTablePrefix()."CategoryItems";
  792           $sql = "SELECT $Field FROM $Table INNER JOIN $cat_table ON ($Table.ResourceId=$cat_table.ItemResourceId) ";
  793           $sql .=" WHERE ($Field LIKE 'Copy % of $Name' OR $Field LIKE '$Name' OR $Field LIKE 'Copy of $Name') AND CategoryId=$CategoryId";
  794           //echo $sql."<br>\n ";
  795           $ado = GetADODBConnection();
  796           $rs = $ado->Execute($sql);
  797           $ret = array();
  798           while($rs && !$rs->EOF)
  799           {
  800                   $ret[] = $rs->fields[$Field];
  801                   $rs->MoveNext();
  802           }
  803           return $ret;    
  804   }
  805  
  806   function &GetItemCollection($ItemName)
  807   {
  808     global $objItemTypes;
  809  
  810     if(is_numeric($ItemName))
  811     {
  812           $item = $objItemTypes->GetItem($ItemName);
  813     }
  814     else
  815       $item = $objItemTypes->GetTypeByName($ItemName);
  816     if(is_object($item))
  817     {
  818           $module = $item->Get("Module");
  819           $prefix = ModuleTagPrefix($module);
  820           $func = $prefix."_ItemCollection";
  821           if(function_exists($func))
  822           {
  823             $var =& $func();
  824           }
  825     }
  826     return $var;
  827   }
  828  
  829            
  830   function UpdateCategoryCount($ItemTypeName=0,$ListType=NULL)
  831   {
  832           global $objCountCache, $objItemTypes;
  833  
  834     if(is_numeric($ItemName))
  835     {
  836           $item = $objItemTypes->GetItem($ItemName);
  837     }
  838     else
  839       $item = $objItemTypes->GetTypeByName($ItemName);
  840     if(is_object($item))
  841     {     
  842           $ItemType  = $item->Get("ItemType");
  843           
  844           $sql = "DELETE FROM ".$objCountCache->SourceTable." WHERE ItemType=$ItemType";
  845           if(is_numeric($ListType))
  846           {
  847                   $sql .= " AND ListType=$ListType";
  848           }
  849           $objCountCache->adodbConnection->Execute($sql);
  850     } 
  851   }
  852  
  853   function UpdateModifiedCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$ExtraId=NULL)
  854   {
  855   }
  856  
  857   function UpdateGroupCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$GroupId=NULL)
  858   {
  859   }
  860  
  861   function GetTagCache($module,$tag,$attribs,$env)
  862   {
  863       global $objSystemCache, $objSession, $objConfig;
  864  
  865       if($objConfig->Get("SystemTagCache"))
  866       {
  867           $name = $tag;
  868           if(is_array($attribs))
  869           {   
  870               foreach($attribs as $n => $val)
  871               {   
  872                   $name .= "-".$val;
  873               }
  874           }
  875           $CachedValue = $objSystemCache->GetContextValue($name,$module,$env, $objSession->Get("GroupList"));
  876       }
  877       else
  878           $CachedValue="";
  879       return $CachedValue;
  880   }
  881  
  882   function SaveTagCache($module, $tag, $attribs, $env, $newvalue)
  883   {
  884       global $objSystemCache, $objSession, $objConfig;
  885  
  886       if($objConfig->Get("SystemTagCache"))
  887       {   
  888           $name = $tag;
  889           if(is_array($attribs))
  890           {   
  891               foreach($attribs as $a => $val)
  892               {   
  893                   $name .= "-".$val;
  894               }
  895           }
  896           $objSystemCache->EditCacheItem($name,$newvalue,$module,0,$env,$objSession->Get("GroupList"));
  897       }
  898   }
  899  
  900   function DeleteTagCache($name,$extraparams, $env="")
  901   {
  902       global $objSystemCache, $objConfig;
  903  
  904       if($objConfig->Get("SystemTagCache"))
  905       {
  906           $where = "Name LIKE '$name%".$extraparams."'";
  907           if(strlen($env))
  908               $where .= " AND Context LIKE $env";
  909           $objSystemCache->DeleteCachedItem($where);
  910       }
  911   }
  912  
  913   function ParseTagLibrary()
  914   {
  915           $objTagList = new clsTagList();
  916           $objTagList->ParseInportalTags();
  917           unset($objTagList);
  918   }
  919  
  920   function GetDateFormat($LangId=0)
  921   {
  922     global $objLanguages
  923    
  924     if(!$LangId)
  925       $LangId= $objLanguages->GetPrimary();
  926     $l = $objLanguages->GetItem($LangId); 
  927     if(is_object($l))
  928     {
  929           $fmt = $l->Get("DateFormat");
  930     }
  931     else
  932       $fmt = "m-d-Y";
  933     return $fmt;  
  934   }
  935  
  936   function GetTimeFormat($LangId=0)
  937   {
  938     global $objLanguages
  939    
  940     if(!$LangId)
  941       $LangId= $objLanguages->GetPrimary();
  942     $l = $objLanguages->GetItem($LangId); 
  943     if(is_object($l))
  944     {
  945           $fmt = $l->Get("TimeFormat");
  946     }
  947     else
  948       $fmt = "H:i:s";
  949     return $fmt;  
  950   }
  951  
  952   function LangDate($TimeStamp=NULL,$LangId=0)
  953  
  954     $fmt = GetDateFormat($LangId);
  955     $ret = adodb_date($fmt,$TimeStamp);
  956     return $ret;
  957   }
  958  
  959   function LangTime($TimeStamp=NULL,$LangId=0)
  960   {
  961     $fmt = GetTimeFormat($LangId);
  962     $ret = adodb_date($fmt,$TimeStamp);
  963     return $ret;
  964   }
  965  
  966   function LangNumber($Num,$DecPlaces=NULL,$LangId=0)
  967   {
  968           global $objLanguages;
  969           
  970     if(!$LangId)
  971       $LangId= $objLanguages->GetPrimary();
  972     $l = $objLanguages->GetItem($LangId); 
  973     if(is_object($l))
  974     {
  975           $ret = number_format($Num,$DecPlaces,$l->Get("DecimalPoint"),$l->Get("ThousandSep"));
  976     }
  977     else
  978       $ret = $num;
  979      
  980     return $ret;  
  981   }
  982  
  983   function replacePngTags($x, $spacer="images/spacer.gif")
  984   {
  985           global $rootURL,$pathtoroot;
  986           
  987       // make sure that we are only replacing for the Windows versions of Internet
  988       // Explorer 5+, and not Opera identified as MSIE
  989       $msie='/msie\s([5-9])\.?[0-9]*.*(win)/i';
  990       $opera='/opera\s+[0-9]+/i';
  991       if(!isset($_SERVER['HTTP_USER_AGENT']) ||
  992           !preg_match($msie,$_SERVER['HTTP_USER_AGENT']) ||
  993           preg_match($opera,$_SERVER['HTTP_USER_AGENT']))
  994           return $x;
  995      
  996       // find all the png images in backgrounds
  997       preg_match_all('/background-image:\s*url\(\'(.*\.png)\'\);/Uis',$x,$background);
  998       for($i=0;$i<count($background[0]);$i++){
  999           // simply replace:
  1000           //  "background-image: url('image.png');"
  1001           // with:
  1002           //  "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(
  1003           //      enabled=true, sizingMethod=scale src='image.png');"
  1004           // haven't tested to see if background-repeat styles work...
  1005           $x=str_replace($background[0][$i],'filter:progid:DXImageTransform.'.
  1006                   'Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale'.
  1007                   ' src=\''.$background[1][$i].'\');',$x);
  1008       }
  1009  
  1010       // OK, time to find all the IMG tags with ".png" in them
  1011       preg_match_all('/(<img.*\.png.*>|<input.*type=([\'"])image\\2.*\.png.*>)/Uis',$x,$images);
  1012       while(list($imgnum,$v)=@each($images[0])){
  1013           $original=$v;
  1014           $atts=''; $width=0; $height=0;
  1015           // If the size is defined by styles, find
  1016           preg_match_all('/style=".*(width: ([0-9]+))px.*'.
  1017                           '(height: ([0-9]+))px.*"/Ui',$v,$arr2);
  1018           if(is_array($arr2) && count($arr2[0])){
  1019               // size was defined by styles, get values
  1020               $width=$arr2[2][0];
  1021               $height=$arr2[4][0];
  1022           }
  1023           // size was not defined by styles, get values
  1024           preg_match_all('/width=\"?([0-9]+)\"?/i',$v,$arr2);
  1025           if(is_array($arr2) && count($arr2[0])){
  1026               $width=$arr2[1][0];
  1027           }
  1028           preg_match_all('/height=\"?([0-9]+)\"?/i',$v,$arr2);
  1029           if(is_array($arr2) && count($arr2[0])){
  1030               $height=$arr2[1][0];
  1031           }
  1032           preg_match_all('/src=\"([^\"]+\.png)\"/i',$v,$arr2);
  1033           if(isset($arr2[1][0]) && !empty($arr2[1][0]))
  1034               $image=$arr2[1][0];
  1035           else
  1036               $image=NULL;
  1037  
  1038           // We do this so that we can put our spacer.gif image in the same
  1039           // directory as the image
  1040           $tmp=split('[\\/]',$image);
  1041           array_pop($tmp);
  1042           $image_path=join('/',$tmp);
  1043              if(substr($image,0,strlen($rootURL))==$rootURL)
  1044              {
  1045                           $path = str_replace($rootURL,$pathtoroot,$image);
  1046              }
  1047             else
  1048             {
  1049                           $path = $pathtoroot."themes/telestial/$image";
  1050             }     
  1051   //        echo "Sizing $path.. <br>\n";
  1052   //        echo "Full Tag: ".htmlentities($image)."<br>\n";       
  1053           //if(!$height || !$width)
  1054           //{
  1055  
  1056             $g = imagecreatefrompng($path);
  1057             if($g)
  1058             {
  1059                   $height = imagesy($g);
  1060                   $width = imagesx($g);
  1061             }     
  1062           //}
  1063           if(strlen($image_path)) $image_path.='/';
  1064  
  1065           // end quote is already supplied by originial src attribute
  1066           $replace_src_with=$spacer.'" style="width: '.$width.
  1067               'px; height: '.$height.'px; filter: progid:DXImageTransform.'.
  1068               'Microsoft.AlphaImageLoader(src=\''.$image.'\', sizingMethod='.
  1069               '\'scale\')';
  1070          
  1071           // now create the new tag from the old
  1072           $new_tag=str_replace($image,$replace_src_with,$original);
  1073          
  1074           // now place the new tag into the content
  1075           $x=str_replace($original,$new_tag,$x);
  1076       }
  1077       return $x;
  1078   }
  1079  
  1080   function print_pre($str)
  1081   {
  1082           // no comments here :)
  1083           echo '<pre>'.print_r($str, true).'</pre>';
  1084   }
  1085  
  1086   function GetOptions($field) // by Alex
  1087   {
  1088           // get dropdown values from custom field
  1089           $tmp =& new clsCustomField();
  1090           
  1091           $tmp->LoadFromDatabase($field, 'FieldName');
  1092           $tmp_values = $tmp->Get('ValueList');
  1093           unset($tmp);
  1094           $tmp_values = explode(',', $tmp_values);
  1095           
  1096           foreach($tmp_values as $mixed)
  1097           {
  1098                   $elem = explode('=', trim($mixed));
  1099                   $ret[ $elem[0] ] = $elem[1];
  1100           }
  1101           return $ret;
  1102   }
  1103  
  1104   function ResetPage($module_prefix, $page_variable = 'p')
  1105   {
  1106           // resets page in specific module when category is changed      
  1107           if(!is_object($objSession)) // when changing pages session doesn't exist -> InPortal BUG
  1108           {
  1109                   global $var_list, $SessionQueryString, $FrontEnd;
  1110                   //if(!$var_list["sid"]) $var_list["sid"] = $_COOKIE["sid"];
  1111                   $objSession = new clsUserSession($var_list["sid"],($SessionQueryString && $FrontEnd==1));
  1112           }
  1113           //echo "SID_RESET: ".$GLOBALS['var_list']["sid"].'(COOKIE_SID: '.$_COOKIE["sid"].')<br>';
  1114           $last_cat = $objSession->GetVariable('last_category');
  1115           $prev_cat = $objSession->GetVariable('prev_category');
  1116           //echo "Resetting Page [$prev_cat] -> [$last_cat]<br>";
  1117           
  1118           if($prev_cat != $last_cat) $GLOBALS[$module_prefix.'_var_list'][$page_variable] = 1;
  1119   }
  1120  
  1121   function GetVar($name)
  1122   {
  1123           return isset($_REQUEST[$name]) ? $_REQUEST[$name] : false;
  1124   }
  1125  
  1126   function PassVar(&$source)
  1127   {
  1128           // source array + any count of key names in passed array        
  1129           $params = func_get_args();
  1130           array_shift($params);
  1131           
  1132           if( count($params) )
  1133           {
  1134                   $ret = Array();
  1135                   foreach($params as $var_name)
  1136                           if( isset($source[$var_name]) )
  1137                                   $ret[] = $var_name.'='.$source[$var_name];
  1138                   $ret = '&'.implode('&', $ret);
  1139           }
  1140           return $ret;
  1141   }
  1142  
  1143   function GetSubmitVariable(&$array, $postfix)
  1144   {
  1145           // gets edit status of module
  1146           // used in case if some modules share
  1147           // common action parsed by kernel parser,
  1148           // but each module uses own EditStatus variable
  1149           
  1150           $modules = Array('In-Link' => 'Link', 'In-News' => 'News', 'In-Bulletin' => 'Topic');
  1151           foreach($modules as $module => $prefix)
  1152                   if( isset($array[$prefix.$postfix]) )
  1153                           return Array('Module' => $module, 'variable' => $array[$prefix.$postfix]);
  1154           return false;
  1155   }
  1156  
  1157   function GetModuleByAction()
  1158   {
  1159           $prefix2module = Array('m' => 'In-Portal', 'l' => 'In-Link', 'n' => 'In-News', 'bb' => 'In-Bulletin');
  1160           $action = $_REQUEST['Action'];
  1161           $module_prefix = explode('_', $action);
  1162           return $prefix2module[ $module_prefix[0] ];
  1163   }
  1164  
  1165   function dir_size($dir) {
  1166      // calculates folder size based on filesizes inside it (recursively)
  1167      $totalsize=0;
  1168      if ($dirstream = @opendir($dir)) {
  1169          while (false !== ($filename = readdir($dirstream))) {
  1170              if ($filename!="." && $filename!="..")
  1171              {
  1172                  if (is_file($dir."/".$filename))
  1173                      $totalsize+=filesize($dir."/".$filename);
  1174                 
  1175                  if (is_dir($dir."/".$filename))
  1176                      $totalsize+=dir_size($dir."/".$filename);
  1177              }
  1178          }
  1179      }
  1180      closedir($dirstream);
  1181      return $totalsize;
  1182   }
  1183  
  1184   function size($bytes) {
  1185     // shows formatted file/directory size
  1186     $types =  Array("la_bytes","la_kilobytes","la_megabytes","la_gigabytes","la_terabytes");
  1187      $current = 0;
  1188     while ($bytes > 1024) {
  1189      $current++;
  1190      $bytes /= 1024;
  1191     }
  1192     return round($bytes,2)." ".language($types[$current]);
  1193   }
  1194  
  1195   function echod($str)
  1196   {
  1197           // echo debug output
  1198           echo str_replace( Array('[',']'), Array('[<b>', '</b>]'), $str).'<br>'
  1199   }
  1200  
  1201  
  1202   function PrepareParams($source, $to_lower, $mapping)
  1203   {
  1204           // prepare array with form values to use with item
  1205           $result = Array();
  1206           foreach($to_lower as $field)
  1207                   $result[ $field ] = $source[ strtolower($field) ];
  1208           
  1209           if( is_array($mapping) )
  1210           {
  1211                   foreach($mapping as $field_from => $field_to)
  1212                           $result[$field_to] = $source[$field_from];
  1213           }
  1214           
  1215           return $result;
  1216   }
  1217  
  1218   function GetELT($field, $phrases = Array())
  1219   {
  1220           // returns FieldOptions equivalent in In-Portal
  1221           $ret = Array();
  1222           foreach($phrases as $phrase)
  1223                   $ret[] = admin_language($phrase);
  1224           $ret = "'".implode("','", $ret)."'";
  1225           return 'ELT('.$field.','.$ret.')';
  1226   }
  1227  
  1228   function GetModuleImgPath($module)
  1229   {
  1230           global $rootURL, $admin;
  1231           return $rootURL.$module.'/'.$admin.'/images';
  1232   }
  1233  
  1234   function ActionPostProcess($StatusField, $ListClass, $ListObjectName = '', $IDField = null)
  1235   {
  1236           // each action postprocessing stuff from admin
  1237           if( !isset($_REQUEST[$StatusField]) ) return false;
  1238           
  1239           $list =& $GLOBALS[$ListObjectName];
  1240           if( !is_object($list) ) $list = new $ListClass();
  1241           $SFValue = $_REQUEST[$StatusField]; // status field value
  1242           switch($SFValue)
  1243           {
  1244                   case 1: // User hit "Save" button
  1245                   $list->CopyFromEditTable($IDField);    
  1246                   break;
  1247                   case 2: // User hit "Cancel" button
  1248                           $list->PurgeEditTable($IDField);
  1249                           break;
  1250           }
  1251           if( function_exists('SpecificProcessing') ) SpecificProcessing($StatusField, $SFValue);
  1252           if($SFValue == 1 || $SFValue == 2) $list->Clear();
  1253   }
  1254  
  1255   function GetElem(&$array, $index)
  1256   {
  1257           // returns array element by index if
  1258           // such index exists
  1259           return isset($array[$index]) ? $array[$index] : false;
  1260   }
  1261  
  1262   function MakeHTMLTag($element, $attrib_prefix)
  1263   {
  1264           $result = Array();
  1265           $ap_length = strlen($attrib_prefix);
  1266           foreach($element->attributes as $attib_name => $attr_value)
  1267                   if( substr($attib_name, $ap_length) == $ap_length )
  1268                           $result[] = substr($attib_name, $ap_length, strlen($attib_name)).'="'.$attr_value.'"';
  1269           return count($result) ? implode(' ', $result) : false;
  1270   }
  1271  
  1272   /* so I dont forget:
  1273      - the decrypt function is defined in adodb-time and is called xp()
  1274      - the keygen function is also declared in adodb-time as $b
  1275        and eval'd() in dates.php
  1276   */    
  1277  
  1278  
  1279  
  1280   /* //this comes from line 15; moved by PSK for readability
  1281  
  1282     $g_DBType = "mysql";
  1283     $g_DBHost = "kiev";
  1284  
  1285     $g_DBUser = "root";
  1286     $g_DBUserPassword = "";
  1287     $g_DBName = "inportal";
  1288  
  1289  
  1290   //$g_DBUser = "bloopered";
  1291   //$g_DBUserPassword = "vFWPqJT017";
  1292   //$g_DBName = "inportal";
  1293  
  1294     $g_TablePrefix = "";
  1295  
  1296     $g_EnableCookies = FALSE;
  1297     $g_SessionExpirationLimit = 3600*1; // 1 hour
  1298  
  1299   //$g_PrivateMessageExpirationLimit = 2592000; // 30 days
  1300   //$g_PrivateMessageThreadLimit = 50;
  1301   //$g_DebugMode=0;
  1302  
  1303   //$g_defaultLanguage = "English";
  1304   //$g_defaultTheme = "default";
  1305  
  1306     $g_TopRate = 4;
  1307     $g_PopRate = 80;
  1308     $g_NewDate = 5;
  1309  
  1310    
  1311     $g_adodbConnection=NULL;
  1312   */
  1313   ?>