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(FULL_PATH.'/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       if ( class_exists('kApplication') )
  322       {
  323           $application =& kApplication::Instance();
  324           return $application->BaseURL().'index.php';
  325       }
  326  
  327       switch($secure)
  328       {
  329           case 0:
  330                   $ret = $indexURL;
  331                   break;
  332  
  333           case 1:
  334                   $ret = $secureURL."index.php";
  335                   break;
  336  
  337           case 2:
  338                   $ret = $rootURL."index.php";
  339                   break;
  340  
  341           default:
  342                   $ret = $i;
  343                   break;
  344       }
  345       return $ret;
  346   }
  347  
  348   function GetLimitSQL($Page,$PerPage)
  349   {
  350     if($Page<1)
  351       $Page=1;
  352  
  353     if(is_numeric($PerPage))
  354     {
  355             if($PerPage==0)
  356               $PerPage = 20;
  357         $Start = ($Page-1)*$PerPage;
  358         $limit = "LIMIT ".$Start.",".$PerPage;
  359     }
  360     else
  361         $limit = NULL;
  362     return $limit;
  363   }
  364  
  365   function filelist ($currentdir, $startdir=NULL,$ext=NULL)
  366   {
  367     global $pathchar;
  368  
  369     //chdir ($currentdir);
  370  
  371     // remember where we started from
  372     if (!$startdir)
  373     {
  374         $startdir = $currentdir;
  375     }
  376  
  377     $d = @opendir($currentdir);
  378  
  379     $files = array();
  380     if(!$d)
  381       return $files;
  382     //list the files in the dir
  383     while (false !== ($file = readdir($d)))
  384     {
  385         if ($file != ".." && $file != ".")
  386         {
  387             if (is_dir($currentdir."/".$file))
  388             {
  389                 // If $file is a directory take a look inside
  390                 $a = filelist ($currentdir."/".$file, $startdir,$ext);
  391                 if(is_array($a))
  392                   $files = array_merge($files,$a);
  393             }
  394             else
  395             {
  396                 if($ext!=NULL)
  397                 {
  398                     $extstr = stristr($file,".".$ext);
  399                     if(strlen($extstr))
  400                         $files[] = $currentdir."/".$file;
  401                 }
  402                 else
  403                   $files[] = $currentdir.'/'.$file;
  404             }
  405         }
  406     }
  407  
  408     closedir ($d);
  409  
  410     return $files;
  411   }
  412  
  413   function DecimalToBin($dec,$WordLength=8)
  414   {
  415     $bits = array();
  416  
  417     $str = str_pad(decbin($dec),$WordLength,"0",STR_PAD_LEFT);
  418     for($i=$WordLength;$i>0;$i--)
  419     {
  420         $bits[$i-1] = (int)substr($str,$i-1,1);
  421     }
  422     return $bits;
  423   }
  424   /*
  425   function inp_escape($in, $html_enable=0)
  426   {
  427           $out = stripslashes($in);
  428           $out = str_replace("\n", "\n^br^", $out);
  429           if($html_enable==0)
  430           {
  431                   $out=ereg_replace("<","&lt;",$out);
  432                   $out=ereg_replace(">","&gt;",$out);
  433                   $out=ereg_replace("\"","&quot;",$out);
  434                   $out = str_replace("\n^br^", "\n<br />", $out);
  435           }
  436           else
  437                   $out = str_replace("\n^br^", "\n", $out);
  438           $out=addslashes($out);
  439  
  440           return $out;
  441   }
  442   */
  443   function inp_escape($var,$html=0)
  444   {
  445           if($html)return $var;
  446           if(is_array($var))
  447                   foreach($var as $k=>$v)
  448                           $var[$k]=inp_escape($v);
  449           else
  450   //              $var=htmlspecialchars($var,ENT_NOQUOTES);
  451                   $var=strtr($var,Array('<'=>'&lt;','>'=>'&gt;',));
  452           return $var;
  453   }
  454   function inp_striptags($var,$html=0)
  455   {
  456           if($html)return $var;
  457           if(is_array($var))
  458                   foreach($var as $k=>$v)
  459                           $var[$k]=inp_striptags($v);
  460           else
  461                   $var=strip_tags($var);
  462           return $var;
  463   }
  464  
  465   function inp_unescape($in)
  466   {
  467   //      if (get_magic_quotes_gpc())
  468                   return $in;
  469           $out=stripslashes($in);
  470           return $out;
  471   }
  472  
  473   function inp_textarea_unescape($in)
  474   {
  475   //      if (get_magic_quotes_gpc())
  476                   return $in;
  477           $out=stripslashes($in);
  478           $out = str_replace("\n<br />", "\n", $out);
  479           return $out;
  480   }
  481  
  482   function HighlightKeywords($Keywords, $html, $OpenTag="", $CloseTag="")
  483   {
  484       global $objConfig;
  485  
  486       if(!strlen($OpenTag))
  487           $OpenTag = "<B>";
  488       if(!strlen($CloseTag))
  489               $CloseTag = "</B>";
  490  
  491           $r = preg_split('((>)|(<))', $html, -1, PREG_SPLIT_DELIM_CAPTURE);
  492  
  493           foreach ($Keywords as $k) {
  494                   for ($i = 0; $i < count($r); $i++) {
  495                  if ($r[$i] == "<") {
  496                      $i++; continue;
  497                  }
  498                  $r[$i] = preg_replace("/($k)/i", "$OpenTag\\1$CloseTag", $r[$i]);
  499               }
  500           }
  501           return join("", $r);
  502   }
  503  
  504   /*
  505   function HighlightKeywords($Keywords,$html, $OpenTag="", $CloseTag="")
  506   {
  507       global $objConfig;
  508  
  509       if(!strlen($OpenTag))
  510           $OpenTag = "<B>";
  511       if(!strlen($CloseTag))
  512               $CloseTag = "</B>";
  513       $ret = strip_tags($html);
  514  
  515       foreach ($Keywords as $k)
  516       {
  517           if(strlen($k))
  518           {
  519             //$html = str_replace("<$k>", ":#:", $html);
  520             //$html = str_replace("</$k>", ":##:", $html);
  521             //$html = strip_tags($html);
  522             if ($html = preg_replace("/($k)/Ui","$OpenTag\\1$CloseTag", $html))
  523             //if ($html = preg_replace("/(>[^<]*)($k)([^<]*< )/Ui","$OpenTag\\1$CloseTag", $html))
  524               $ret = $html;
  525             //$ret = str_replace(":#:", "<$k>", $ret);
  526             //$ret = str_replace(":##:", "</$k>", $ret);
  527           }
  528       }
  529       return $ret;
  530   }
  531   */
  532   function ExtractDatePart($part,$datestamp)
  533   {
  534       switch($part)
  535       {
  536           case "month":
  537               if($datestamp<=0)
  538               {
  539                   $ret = "";
  540               }
  541               else
  542                 $ret = adodb_date("m",$datestamp);
  543           break;
  544           case "day":
  545               if($datestamp<=0)
  546               {
  547                   $ret = "";
  548               }
  549               else
  550                   $ret = adodb_date("d", $datestamp);
  551           break;
  552           case "year":
  553               if($datestamp<=0)
  554               {
  555                   $ret = "";
  556               }
  557               else
  558                   $ret = adodb_date("Y", $datestamp);
  559           break;
  560           case "time_24hr":
  561               if($datestamp<=0)
  562               {
  563                   $ret = "";
  564               }
  565               else
  566                   $ret = adodb_date("H:i", $datestamp);
  567           break;
  568           case "time_12hr":
  569               if($datestamp<=0)
  570               {
  571                   $ret = "";
  572               }
  573               else
  574                   $ret = adodb_date("g:i a",$datestamp);
  575                   break;
  576           default:
  577                   $ret = adodb_date($part, $datestamp);
  578                   break;
  579        }
  580       return $ret;
  581   }
  582  
  583   function GetLocalTime($TimeStamp,$TargetZone=NULL)
  584   {
  585       if($TargetZone==NULL)
  586           $TargetZone = $objConfig->Get("Config_Site_Time");
  587       $server = $objConfig->Get("Config_Server_Time");
  588       if($TargetZone!=$server)
  589       {
  590         $offset = ($server - $TargetZone) * -1;
  591         $TimeStamp = $TimeStamp + (3600 * $offset);
  592       }
  593       return $TimeStamp;
  594   }
  595  
  596   function _unhtmlentities ($string)
  597   {
  598       $trans_tbl = get_html_translation_table (HTML_ENTITIES);
  599       $trans_tbl = array_flip ($trans_tbl);
  600       return strtr ($string, $trans_tbl);
  601   }
  602  
  603   function getLastStr($hay, $need){
  604     $getLastStr = 0;
  605     $pos = strpos($hay, $need);
  606     if (is_int ($pos)){ //this is to decide whether it is "false" or "0"
  607      while($pos) {
  608        $getLastStr = $getLastStr + $pos + strlen($need);
  609        $hay = substr ($hay , $pos + strlen($need));
  610        $pos = strpos($hay, $need);
  611      }
  612      return $getLastStr - strlen($need);
  613     } else {
  614      return -1; //if $need wasn´t found it returns "-1" , because it could return "0" if it´s found on position "0".
  615     }
  616   }
  617  
  618   // --- bbcode processing function: begin ----
  619   function PreformatBBCodes($text)
  620   {
  621           // convert phpbb url bbcode to valid in-bulletin's format
  622           // 1. urls
  623           $text = preg_replace('/\[url=(.*)\](.*)\[\/url\]/Ui','[url href="$1"]$2[/url]',$text);
  624           $text = preg_replace('/\[url\](.*)\[\/url\]/Ui','[url href="$1"]$1[/url]',$text);
  625           // 2. images
  626           $text = preg_replace('/\[img\](.*)\[\/img\]/Ui','[img src="$1" border="0"][/img]',$text);
  627           // 3. color
  628           $text = preg_replace('/\[color=(.*)\](.*)\[\/color\]/Ui','[font color="$1"]$2[/font]',$text);
  629           // 4. size
  630           $text = preg_replace('/\[size=(.*)\](.*)\[\/size\]/Ui','[font size="$1"]$2[/font]',$text);
  631           // 5. lists
  632           $text = preg_replace('/\[list(.*)\](.*)\[\/list\]/Uis','[ul]$2[/ul]',$text);
  633           // 6. email to link
  634           $text = preg_replace('/\[email\](.*)\[\/email\]/Ui','[url href="mailto:$1"]$1[/url]',$text);
  635           //7. b tag
  636           $text = preg_replace('/\[(b|i|u):(.*)\](.*)\[\/(b|i|u):(.*)\]/Ui','[$1]$3[/$4]',$text);
  637           //8. code tag
  638           $text = preg_replace('/\[code:(.*)\](.*)\[\/code:(.*)\]/Uis','[code]$2[/code]',$text);
  639           return $text;
  640   }
  641  
  642   /**
  643    * @return string
  644    * @param string $BBCode
  645    * @param string $TagParams
  646    * @param string $TextInside
  647    * @param string $ParamsAllowed
  648    * @desc Removes not allowed params from tag and returns result
  649   */
  650   function CheckBBCodeAttribs($BBCode, $TagParams, $TextInside, $ParamsAllowed)
  651   {
  652           //      $BBCode - bbcode to check, $TagParams - params string entered by user
  653           //      $TextInside - text between opening and closing bbcode tag
  654           //      $ParamsAllowed - list of allowed parameter names ("|" separated)
  655           $TagParams=str_replace('\"','"',$TagParams);
  656           $TextInside=str_replace('\"','"',$TextInside);
  657           if( $ParamsAllowed && preg_match_all('/ +([^=]*)=["\']?([^ "\']*)["\']?/is',$TagParams,$params,PREG_SET_ORDER) )
  658           {
  659                   $ret = Array();
  660                   foreach($params as $param)
  661                   {
  662                           // remove spaces in both parameter name & value & lowercase parameter name
  663                           $param[1] = strtolower(trim($param[1]));        // name lowercased
  664                           if(($BBCode=='url')&&($param[1]=='href'))
  665                                   if(false!==strpos(strtolower($param[2]),'script:'))
  666                                           return $TextInside;
  667   //                                      $param[2]='about:blank';
  668                           if( isset($ParamsAllowed[ $param[1] ]) )
  669                                   $ret[] = $param[1].'="'.$param[2].'"';
  670                   }
  671                   $ret = count($ret) ? ' '.implode(' ',$ret) : '';
  672                   return '<'.$BBCode.$ret.'>'.$TextInside.'</'.$BBCode.'>';
  673           }
  674           else
  675                   return '<'.$BBCode.'>'.$TextInside.'</'.$BBCode.'>';
  676           return false;
  677   }
  678   function ReplaceBBCode($text)
  679   {
  680           global $objConfig;
  681           // convert phpbb bbcodes to in-bulletin bbcodes
  682           $text = PreformatBBCodes($text);
  683  
  684   //      $tag_defs = 'b:;i:;u:;ul:type|align;font:color|face|size;url:href;img:src|border';
  685  
  686           $tags_defs = $objConfig->Get('BBTags');
  687           foreach(explode(';',$tags_defs) as $tag)
  688           {
  689                   $tag = explode(':',$tag);
  690                   $tag_name = $tag[0];
  691                   $tag_params = $tag[1]?array_flip(explode('|',$tag[1])):0;
  692                   $text = preg_replace('/\['.$tag_name.'(.*)\](.*)\[\/'.$tag_name.' *\]/Uise','CheckBBCodeAttribs("'.$tag_name.'",\'$1\',\'$2\',$tag_params);', $text);
  693           }
  694  
  695           // additional processing for [url], [*], [img] bbcode
  696           $text = preg_replace('/<url>(.*)<\/url>/Usi','<url href="$1">$1</url>',$text);
  697           $text = preg_replace('/<font>(.*)<\/font>/Usi','$1',$text); // skip empty fonts
  698           $text = str_replace(    Array('<url','</url>','[*]'),
  699                                                           Array('<a target="_blank"','</a>','<li>'),
  700                                                           $text);
  701  
  702           // bbcode [code]xxx[/code] processing
  703           $text = preg_replace('/\[code\](.*)\[\/code\]/Uise', "ReplaceCodeBBCode('$1')", $text);
  704           return $text;
  705   }
  706   function leadSpace2nbsp($x)
  707   {
  708           return "\n".str_repeat('&nbsp;',strlen($x));
  709   }
  710   function ReplaceCodeBBCode($input_string)
  711   {
  712           $input_string=str_replace('\"','"',$input_string);
  713           $input_string=$GLOBALS['objSmileys']->UndoSmileys(_unhtmlentities($input_string));
  714           $input_string=trim($input_string);
  715           $input_string=inp_htmlize($input_string);
  716           $input_string=str_replace("\r",'',$input_string);
  717           $input_string = str_replace("\t", "    ", $input_string);
  718           $input_string = preg_replace('/\n( +)/se',"leadSpace2nbsp('$1')",$input_string);
  719           $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>';
  720   //      $input_string='<textarea wrap="off" style="border:1px solid #888888;width:100%;height:200px;background-color:#eeeeee;">'.inp_htmlize($input_string).'</textarea>';
  721           return $input_string;
  722  
  723           if(false!==strpos($input_string,'<'.'?'))
  724           {
  725                   $input_string=str_replace('<'.'?','<'.'?php',$input_string);
  726                   $input_string=str_replace('<'.'?phpphp','<'.'?php',$input_string);
  727                   $input_string=@highlight_string($input_string,1);
  728           }
  729           else
  730           {
  731                   $input_string = @highlight_string('<'.'?php'.$input_string.'?'.'>',1);
  732                   $input_string = str_replace('&lt;?php', '', str_replace('?&gt;', '', $input_string));
  733           }
  734           return str_replace('<br />','',$input_string);
  735  
  736   }
  737  
  738  
  739   // --- bbcode processing function: end ----
  740  
  741   function GetMinValue($Table,$Field, $Where=NULL)
  742   {
  743       $ret = 0;
  744       $sql = "SELECT min($Field) as val FROM $Table ";
  745       if(strlen($where))
  746           $sql .= "WHERE $Where";
  747       $ado = &GetADODBConnection();
  748       $rs = $ado->execute($sql);
  749       if($rs)
  750           $ret = (int)$rs->fields["val"];
  751       return $ret;
  752   }
  753  
  754  
  755   if (!function_exists( 'getmicrotime' ) ) {
  756           function getmicrotime()
  757           {
  758               list($usec, $sec) = explode(" ",microtime());
  759               return ((float)$usec + (float)$sec);
  760           }
  761   }
  762  
  763   function SetMissingDataErrors($f)
  764   {
  765       global $FormError;
  766  
  767       $count = 0;
  768       if(is_array($_POST))
  769       {
  770         if(is_array($_POST["required"]))
  771         {
  772           foreach($_POST["required"] as $r)
  773           {
  774             $found = FALSE;
  775             if(is_array($_FILES))
  776             {
  777               if( isset($_FILES[$r]) && $_FILES[$r]['size'] > 0 ) $found = TRUE;
  778             }
  779  
  780             if(!strlen(trim($_POST[$r])) && !$found)
  781             {
  782               $count++;
  783  
  784               if (($r == "dob_day") || ($r == "dob_month") || ($r == "dob_year"))
  785                   $r = "dob";
  786  
  787               $tag = isset($_POST["errors"]) ? $_POST["errors"][$r] : '';
  788               if(!strlen($tag))
  789                 $tag = "lu_ferror_".$f."_".$r;
  790               $FormError[$f][$r] = language($tag);
  791             }
  792           }
  793         }
  794       }
  795       return $count;
  796   }
  797  
  798   function makepassword($length=10)
  799   {
  800     $pass_length=$length;
  801  
  802     $p1=array('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z');
  803     $p2=array('a','e','i','o','u');
  804     $p3=array('1','2','3','4','5','6','7','8','9');
  805     $p4=array('(','&',')',';','%');    // if you need real strong stuff
  806  
  807     // how much elements in the array
  808     // can be done with a array count but counting once here is faster
  809  
  810     $s1=21;// this is the count of $p1
  811     $s2=5; // this is the count of $p2
  812     $s3=9; // this is the count of $p3
  813     $s4=5; // this is the count of $p4
  814  
  815     // possible readable combinations
  816  
  817     $c1='121';    // will be like 'bab'
  818     $c2='212';      // will be like 'aba'
  819     $c3='12';      // will be like 'ab'
  820     $c4='3';        // will be just a number '1 to 9'  if you dont like number delete the 3
  821   // $c5='4';        // uncomment to active the strong stuff
  822  
  823     $comb='4'; // the amount of combinations you made above (and did not comment out)
  824  
  825  
  826  
  827     for ($p=0;$p<$pass_length;)
  828     {
  829       mt_srand((double)microtime()*1000000);
  830       $strpart=mt_rand(1,$comb);
  831       // checking if the stringpart is not the same as the previous one
  832       if($strpart<>$previous)
  833       {
  834         $pass_structure.=${'c'.$strpart};
  835  
  836         // shortcutting the loop a bit
  837         $p=$p+strlen(${'c'.$strpart});
  838       }
  839       $previous=$strpart;
  840     }
  841  
  842  
  843     // generating the password from the structure defined in $pass_structure
  844     for ($g=0;$g<strlen($pass_structure);$g++)
  845     {
  846       mt_srand((double)microtime()*1000000);
  847       $sel=substr($pass_structure,$g,1);
  848       $pass.=${'p'.$sel}[mt_rand(0,-1+${'s'.$sel})];
  849  
  850     }
  851     return $pass;
  852   }
  853  
  854   function LogEntry($text,$writefile=FALSE)
  855   {
  856     global $g_LogFile,$LogFile, $LogData, $LogLevel, $timestart;
  857  
  858     static $last;
  859  
  860     if(strlen($g_LogFile))
  861     {
  862       $el = str_pad(getmicrotime()- $timestart,10," ");
  863       if($last>0)
  864         $elapsed = getmicrotime() - $last;
  865  
  866       if(strlen($el)>10)
  867           $el = substr($el,0,10);
  868       $indent = str_repeat("  ",$LogLevel);
  869       $text = str_pad($text,$LogLevel,"==",STR_PAD_LEFT);
  870       $LogData .= "$el:". round($elapsed,6).":$indent $text";
  871       $last = getmicrotime();
  872       if($writefile==TRUE && is_writable($g_LogFile))
  873       {
  874         if(!$LogFile)
  875         {
  876            if(file_exists($g_LogFile))
  877               unlink($g_LogFile);
  878           $LogFile=@fopen($g_LogFile,"w");
  879         }
  880         if($LogFile)
  881         {
  882           fputs($LogFile,$LogData);
  883         }
  884       }
  885     }
  886   }
  887  
  888   function ValidEmail($email)
  889   {
  890       if (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $email))
  891       {
  892           return TRUE;
  893       }
  894       else
  895       {
  896           return FALSE;
  897       }
  898   }
  899  
  900   function language($phrase,$LangId=0)
  901   {
  902       global $objSession, $objLanguageCache, $objLanguages;
  903  
  904       if($LangId==0)
  905           $LangId = $objSession->Get("Language");
  906  
  907           if($LangId==0)
  908         $LangId = $objLanguages->GetPrimary();
  909  
  910       $translation = $objLanguageCache->GetTranslation($phrase,$LangId);
  911  
  912       return $translation;
  913   }
  914  
  915   function admin_language($phrase,$lang=0,$LinkMissing=FALSE)
  916   {
  917       global $objSession, $objLanguageCache, $objLanguages;
  918  
  919           //echo "Language passed: $lang<br>";
  920  
  921       if($lang==0)
  922          $lang = $objSession->Get("Language");
  923  
  924       //echo "Language from session: $lang<br>";
  925  
  926           if($lang==0)
  927         $lang = $objLanguages->GetPrimary();
  928  
  929       //echo "Language after primary: $lang<br>";
  930       //echo "Phrase: $phrase<br>";
  931           $translation = $objLanguageCache->GetTranslation($phrase,$lang);
  932       if($LinkMissing && substr($translation,0,1)=="!" && substr($translation,-1)=="!")
  933       {
  934           $res = "<A href=\"javascript:OpenPhraseEditor('&direct=1&label=$phrase'); \">$translation</A>";
  935           return $res;
  936       }
  937       else
  938           return $translation;
  939   }
  940  
  941   function prompt_language($phrase,$lang=0)
  942   {
  943     return admin_language($phrase,$lang,TRUE);
  944   }
  945  
  946   function GetPrimaryTranslation($Phrase)
  947   {
  948           global $objLanguages;
  949  
  950           $l = $objLanguages->GetPrimary();
  951           return language($Phrase,$l);
  952   }
  953  
  954   function CategoryNameCount($ParentId,$Name)
  955   {
  956           $cat_table = GetTablePrefix()."Category";
  957           $sql = "SELECT Name from $cat_table WHERE ParentId=$ParentId AND ";
  958           $sql .="(Name LIKE '".addslashes($Name)."' OR Name LIKE 'Copy of ".addslashes($Name)."' OR Name LIKE 'Copy % of ".addslashes($Name)."')";
  959  
  960           $ado = &GetADODBConnection();
  961           $rs = $ado->Execute($sql);
  962           $ret = array();
  963           while($rs && !$rs->EOF)
  964           {
  965                   $ret[] = $rs->fields["Name"];
  966                   $rs->MoveNext();
  967           }
  968           return $ret;
  969   }
  970  
  971   function CategoryItemNameCount($CategoryId,$Table,$Field,$Name)
  972   {
  973           $Name=addslashes($Name);
  974           $cat_table = GetTablePrefix()."CategoryItems";
  975           $sql = "SELECT $Field FROM $Table INNER JOIN $cat_table ON ($Table.ResourceId=$cat_table.ItemResourceId) ";
  976           $sql .=" WHERE ($Field LIKE 'Copy % of $Name' OR $Field LIKE '$Name' OR $Field LIKE 'Copy of $Name') AND CategoryId=$CategoryId";
  977           //echo $sql."<br>\n ";
  978           $ado = &GetADODBConnection();
  979           $rs = $ado->Execute($sql);
  980           $ret = array();
  981           while($rs && !$rs->EOF)
  982           {
  983                   $ret[] = $rs->fields[$Field];
  984                   $rs->MoveNext();
  985           }
  986           return $ret;
  987   }
  988  
  989   function &GetItemCollection($ItemName)
  990   {
  991     global $objItemTypes;
  992  
  993     if(is_numeric($ItemName))
  994     {
  995           $item = $objItemTypes->GetItem($ItemName);
  996     }
  997     else
  998       $item = $objItemTypes->GetTypeByName($ItemName);
  999     if(is_object($item))
  1000     {
  1001           $module = $item->Get("Module");
  1002           $prefix = ModuleTagPrefix($module);
  1003           $func = $prefix."_ItemCollection";
  1004           if(function_exists($func))
  1005           {
  1006             $var =& $func();
  1007           }
  1008     }
  1009     return $var;
  1010   }
  1011  
  1012  
  1013   function UpdateCategoryCount($item_type,$CategoriesIds,$ListType='')
  1014   {
  1015           global $objCountCache, $objItemTypes;
  1016           $db=&GetADODBConnection();
  1017           if( !is_numeric($item_type) )
  1018           {
  1019                   $sql = 'SELECT ItemType FROM '.$objItemTypes->SourceTable.' WHERE ItemName=\''.$item_type.'\'';
  1020                   $item_type=$db->GetOne($sql);
  1021           }
  1022           $objCountCache->EraseGlobalTypeCache($item_type);
  1023           if($item_type)
  1024           {
  1025                   if(is_array($CategoriesIds))
  1026                   {
  1027                           $CategoriesIds=implode(',',$CategoriesIds);
  1028                   }
  1029                   if (!$CategoriesIds)
  1030                   {
  1031  
  1032                   }
  1033  
  1034                   if(!is_array($ListType)) $ListType=Array($ListType=>'opa');
  1035  
  1036                   $sql = 'SELECT ParentPath FROM '.GetTablePrefix().'Category WHERE CategoryId IN ('.$CategoriesIds.')';
  1037                   $rs = $db->Execute($sql);
  1038                   $parents = Array();
  1039                   while (!$rs->EOF)
  1040                   {
  1041                           $tmp=$rs->fields['ParentPath'];
  1042                           $tmp=substr($tmp,1,strlen($tmp)-2);
  1043                           $tmp=explode('|',$tmp);
  1044                           foreach ($tmp as $tmp_cat_id) {
  1045                                   $parents[$tmp_cat_id]=1;
  1046                           }
  1047                           $rs->MoveNext();
  1048                   }
  1049                   $parents=array_keys($parents);
  1050                   $list_types=array_keys($ListType);
  1051                   foreach($parents as $ParentCategoryId)
  1052                   {
  1053                           foreach ($list_types as $list_type) {
  1054                                   $objCountCache->DeleteValue($list_type, $item_type, $ParentCategoryId, 0);      // total count
  1055                                   $objCountCache->DeleteValue($list_type, $item_type, $ParentCategoryId, 1);      // total count today
  1056                           }
  1057                   }
  1058           }
  1059           else
  1060           {
  1061                   die('wrong item type passed to "UpdateCategoryCount"');
  1062           }
  1063  
  1064   /*      if(is_object($item))
  1065           {
  1066                   $ItemType  = $item->Get("ItemType");
  1067  
  1068                   $sql = "DELETE FROM ".$objCountCache->SourceTable." WHERE ItemType=$ItemType";
  1069                   if( is_numeric($ListType) ) $sql .= " AND ListType=$ListType";
  1070                   $objCountCache->adodbConnection->Execute($sql);
  1071           }  */
  1072   }
  1073  
  1074   function ResetCache($CategoryId)
  1075   {
  1076           global $objCountCache;
  1077           $db =& GetADODBConnection();
  1078           $sql = 'SELECT ParentPath FROM '.GetTablePrefix().'Category WHERE CategoryId = '.$CategoryId;
  1079           $parents = $db->GetOne($sql);
  1080           $parents = substr($parents,1,strlen($parents)-2);
  1081           $parents = explode('|',$parents);
  1082           foreach($parents as $ParentCategoryId)
  1083           {
  1084                   $objCountCache->DeleteValue('_', TYPE_TOPIC, $ParentCategoryId, 0);     // total topic count
  1085                   $objCountCache->DeleteValue('_', TYPE_TOPIC, $ParentCategoryId, 1);     // total
  1086           }
  1087   }
  1088  
  1089   function UpdateModifiedCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$ExtraId=NULL)
  1090   {
  1091   }
  1092  
  1093   function UpdateGroupCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$GroupId=NULL)
  1094   {
  1095   }
  1096  
  1097   function GetTagCache($module,$tag,$attribs,$env)
  1098   {
  1099       global $objSystemCache, $objSession, $objConfig;
  1100  
  1101       if($objConfig->Get("SystemTagCache") && !$objSession->Get('PortalUserId'))
  1102       {
  1103           $name = $tag;
  1104           if(is_array($attribs))
  1105           {
  1106               foreach($attribs as $n => $val)
  1107               {
  1108                   $name .= "-".$val;
  1109               }
  1110           }
  1111           $CachedValue = $objSystemCache->GetContextValue($name,$module,$env, $objSession->Get("GroupList"));
  1112       }
  1113       else
  1114           $CachedValue="";
  1115       return $CachedValue;
  1116   }
  1117  
  1118   function SaveTagCache($module, $tag, $attribs, $env, $newvalue)
  1119   {
  1120       global $objSystemCache, $objSession, $objConfig;
  1121  
  1122       if($objConfig->Get("SystemTagCache"))
  1123       {
  1124           $name = $tag;
  1125           if(is_array($attribs))
  1126           {
  1127               foreach($attribs as $a => $val)
  1128               {
  1129                   $name .= "-".$val;
  1130               }
  1131           }
  1132           $objSystemCache->EditCacheItem($name,$newvalue,$module,0,$env,$objSession->Get("GroupList"));
  1133       }
  1134   }
  1135  
  1136   function DeleteTagCache($name,$extraparams, $env="")
  1137   {
  1138       global $objSystemCache, $objConfig;
  1139  
  1140       if($objConfig->Get("SystemTagCache"))
  1141       {
  1142           $where = "Name LIKE '$name%".$extraparams."'";
  1143           if(strlen($env))
  1144               $where .= " AND Context LIKE $env";
  1145           $objSystemCache->DeleteCachedItem($where);
  1146       }
  1147   }
  1148  
  1149   /**
  1150    * Deletes whole tag cache for
  1151    * selected module
  1152    *
  1153    * @param string $module
  1154    * @param string $name
  1155    * @access public
  1156    */
  1157   function DeleteModuleTagCache($module, $tagname='')
  1158   {
  1159       global $objSystemCache, $objConfig;
  1160  
  1161       if($objConfig->Get("SystemTagCache"))
  1162       {
  1163           $where = 'Module LIKE \''.$module.'\'';
  1164           if(strlen($tagname))
  1165           {
  1166               $where .= ' AND Name LIKE \''.$tagname.'\'';
  1167           }
  1168           $objSystemCache->DeleteCachedItem($where);
  1169       }
  1170   }
  1171  
  1172  
  1173  
  1174   /*function ClearTagCache()
  1175   {
  1176       global $objSystemCache, $objConfig;
  1177  
  1178       if($objConfig->Get("SystemTagCache"))
  1179       {
  1180           $where = '';
  1181           $objSystemCache->DeleteCachedItem($where);
  1182       }
  1183   }*/
  1184  
  1185   /*function EraseCountCache()
  1186   {
  1187   //  global $objSystemCache, $objConfig;
  1188  
  1189       $db =& GetADODBConnection();
  1190       $sql = 'DELETE * FROM '.GetTablePrefix().'CountCache';
  1191       return $db->Execute($sql) ? true : false;
  1192   }*/
  1193  
  1194  
  1195   function ParseTagLibrary()
  1196   {
  1197           $objTagList = new clsTagList();
  1198           $objTagList->ParseInportalTags();
  1199           unset($objTagList);
  1200   }
  1201  
  1202   function GetDateFormat($LangId=0)
  1203   {
  1204     global $objLanguages;
  1205  
  1206     if(!$LangId)
  1207       $LangId= $objLanguages->GetPrimary();
  1208     $l = $objLanguages->GetItem($LangId);
  1209     if(is_object($l))
  1210     {
  1211           $fmt = $l->Get("DateFormat");
  1212     }
  1213     else
  1214       $fmt = "m-d-Y";
  1215  
  1216           if(isset($GLOBALS['FrontEnd'])&&$GLOBALS['FrontEnd'])
  1217                   return $fmt;
  1218           return preg_replace('/y+/i','Y',$fmt);
  1219   }
  1220  
  1221   function GetTimeFormat($LangId=0)
  1222   {
  1223     global $objLanguages;
  1224  
  1225     if(!$LangId)
  1226       $LangId= $objLanguages->GetPrimary();
  1227     $l = $objLanguages->GetItem($LangId);
  1228     if(is_object($l))
  1229     {
  1230           $fmt = $l->Get("TimeFormat");
  1231     }
  1232     else
  1233       $fmt = "H:i:s";
  1234     return $fmt;
  1235   }
  1236  
  1237   /**
  1238    * Gets one of currently selected language options
  1239    *
  1240    * @param string $optionName
  1241    * @param int $LangId
  1242    * @return string
  1243    * @access public
  1244    */
  1245   function GetRegionalOption($optionName,$LangId=0)
  1246   {
  1247           global $objLanguages, $objSession;
  1248  
  1249           if(!$LangId) $LangId=$objSession->Get('Language');
  1250           if(!$LangId) $LangId=$objLanguages->GetPrimary();
  1251           $l = $objLanguages->GetItem($LangId);
  1252           return is_object($l)?$l->Get($optionName):false;
  1253   }
  1254  
  1255   function LangDate($TimeStamp=NULL,$LangId=0)
  1256   {
  1257     $fmt = GetDateFormat($LangId);
  1258     $ret = adodb_date($fmt,$TimeStamp);
  1259     return $ret;
  1260   }
  1261  
  1262   function LangTime($TimeStamp=NULL,$LangId=0)
  1263   {
  1264     $fmt = GetTimeFormat($LangId);
  1265     $ret = adodb_date($fmt,$TimeStamp);
  1266     return $ret;
  1267   }
  1268  
  1269   function LangNumber($Num,$DecPlaces=NULL,$LangId=0)
  1270   {
  1271           global $objLanguages;
  1272  
  1273     if(!$LangId)
  1274       $LangId= $objLanguages->GetPrimary();
  1275     $l = $objLanguages->GetItem($LangId);
  1276     if(is_object($l))
  1277     {
  1278           $ret = number_format($Num,$DecPlaces,$l->Get("DecimalPoint"),$l->Get("ThousandSep"));
  1279     }
  1280     else
  1281       $ret = $num;
  1282  
  1283     return $ret;
  1284   }
  1285  
  1286   function replacePngTags($x, $spacer="images/spacer.gif")
  1287   {
  1288           global $rootURL,$pathtoroot;
  1289  
  1290       // make sure that we are only replacing for the Windows versions of Internet
  1291       // Explorer 5+, and not Opera identified as MSIE
  1292       $msie='/msie\s([5-9])\.?[0-9]*.*(win)/i';
  1293       $opera='/opera\s+[0-9]+/i';
  1294       if(!isset($_SERVER['HTTP_USER_AGENT']) ||
  1295           !preg_match($msie,$_SERVER['HTTP_USER_AGENT']) ||
  1296           preg_match($opera,$_SERVER['HTTP_USER_AGENT']))
  1297           return $x;
  1298  
  1299       // find all the png images in backgrounds
  1300       preg_match_all('/background-image:\s*url\(\'(.*\.png)\'\);/Uis',$x,$background);
  1301       for($i=0;$i<count($background[0]);$i++){
  1302           // simply replace:
  1303           //  "background-image: url('image.png');"
  1304           // with:
  1305           //  "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(
  1306           //      enabled=true, sizingMethod=scale src='image.png');"
  1307           // haven't tested to see if background-repeat styles work...
  1308           $x=str_replace($background[0][$i],'filter:progid:DXImageTransform.'.
  1309                   'Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale'.
  1310                   ' src=\''.$background[1][$i].'\');',$x);
  1311       }
  1312  
  1313       // OK, time to find all the IMG tags with ".png" in them
  1314       preg_match_all('/(<img.*\.png.*>|<input.*type=([\'"])image\\2.*\.png.*>)/Uis',$x,$images);
  1315       while(list($imgnum,$v)=@each($images[0])){
  1316           $original=$v;
  1317           $atts=''; $width=0; $height=0;
  1318           // If the size is defined by styles, find
  1319           preg_match_all('/style=".*(width: ([0-9]+))px.*'.
  1320                           '(height: ([0-9]+))px.*"/Ui',$v,$arr2);
  1321           if(is_array($arr2) && count($arr2[0])){
  1322               // size was defined by styles, get values
  1323               $width=$arr2[2][0];
  1324               $height=$arr2[4][0];
  1325           }
  1326           // size was not defined by styles, get values
  1327           preg_match_all('/width=\"?([0-9]+)\"?/i',$v,$arr2);
  1328           if(is_array($arr2) && count($arr2[0])){
  1329               $width=$arr2[1][0];
  1330           }
  1331           preg_match_all('/height=\"?([0-9]+)\"?/i',$v,$arr2);
  1332           if(is_array($arr2) && count($arr2[0])){
  1333               $height=$arr2[1][0];
  1334           }
  1335           preg_match_all('/src=\"([^\"]+\.png)\"/i',$v,$arr2);
  1336           if(isset($arr2[1][0]) && !empty($arr2[1][0]))
  1337               $image=$arr2[1][0];
  1338           else
  1339               $image=NULL;
  1340  
  1341           // We do this so that we can put our spacer.gif image in the same
  1342           // directory as the image
  1343           $tmp=split('[\\/]',$image);
  1344           array_pop($tmp);
  1345           $image_path=join('/',$tmp);
  1346              if(substr($image,0,strlen($rootURL))==$rootURL)
  1347              {
  1348                           $path = str_replace($rootURL,$pathtoroot,$image);
  1349              }
  1350             else
  1351             {
  1352                           $path = $pathtoroot."themes/telestial/$image";
  1353             }
  1354   //        echo "Sizing $path.. <br>\n";
  1355   //        echo "Full Tag: ".htmlentities($image)."<br>\n";
  1356           //if(!$height || !$width)
  1357           //{
  1358  
  1359             $g = imagecreatefrompng($path);
  1360             if($g)
  1361             {
  1362                   $height = imagesy($g);
  1363                   $width = imagesx($g);
  1364             }
  1365           //}
  1366           if(strlen($image_path)) $image_path.='/';
  1367  
  1368           // end quote is already supplied by originial src attribute
  1369           $replace_src_with=$spacer.'" style="width: '.$width.
  1370               'px; height: '.$height.'px; filter: progid:DXImageTransform.'.
  1371               'Microsoft.AlphaImageLoader(src=\''.$image.'\', sizingMethod='.
  1372               '\'scale\')';
  1373  
  1374           // now create the new tag from the old
  1375           $new_tag=str_replace($image,$replace_src_with,$original);
  1376  
  1377           // now place the new tag into the content
  1378           $x=str_replace($original,$new_tag,$x);
  1379       }
  1380       return $x;
  1381   }
  1382  
  1383   if (!function_exists('print_pre')) {
  1384           function print_pre($str)
  1385           {
  1386                   // no comments here :)
  1387                   echo '<pre>'.print_r($str, true).'</pre>';
  1388           }
  1389   }
  1390  
  1391   function GetOptions($field) // by Alex
  1392   {
  1393           // get dropdown values from custom field
  1394           $tmp =& new clsCustomField();
  1395  
  1396           $tmp->LoadFromDatabase($field, 'FieldName');
  1397           $tmp_values = $tmp->Get('ValueList');
  1398           unset($tmp);
  1399           $tmp_values = explode(',', $tmp_values);
  1400  
  1401           foreach($tmp_values as $mixed)
  1402           {
  1403                   $elem = explode('=', trim($mixed));
  1404                   $ret[ $elem[0] ] = $elem[1];
  1405           }
  1406           return $ret;
  1407   }
  1408  
  1409   function ResetPage($module_prefix, $page_variable = 'p')
  1410   {
  1411           // resets page in specific module when category is changed
  1412           global $objSession;
  1413           if( !is_object($objSession) ) // when changing pages session doesn't exist -> InPortal BUG
  1414           {
  1415                   global $var_list, $SessionQueryString, $FrontEnd;
  1416                   $objSession = new clsUserSession($var_list["sid"],($SessionQueryString && $FrontEnd==1));
  1417           }
  1418  
  1419           $last_cat = $objSession->GetVariable('last_category');
  1420           $prev_cat = $objSession->GetVariable('prev_category');
  1421           //echo "Resetting Page [$prev_cat] -> [$last_cat]<br>";
  1422  
  1423           if($prev_cat != $last_cat) $GLOBALS[$module_prefix.'_var_list'][$page_variable] = 1;
  1424   }
  1425  
  1426   if( !function_exists('GetVar') )
  1427   {
  1428           /**
  1429           * @return string
  1430           * @param string $name
  1431           * @param bool $post_priority
  1432           * @desc Get's variable from http query
  1433           */
  1434           function GetVar($name, $post_priority = false)
  1435           {
  1436                   if(!$post_priority) // follow gpc_order in php.ini
  1437                           return isset($_REQUEST[$name]) ? $_REQUEST[$name] : false;
  1438                   else    // get variable from post 1stly if not found then from get
  1439                           return isset($_POST[$name]) && $_POST[$name] !== false ? $_POST[$name] : ( isset($_GET[$name]) && $_GET[$name] ? $_GET[$name] : false );
  1440           }
  1441   }
  1442  
  1443   function SetVar($VarName, $VarValue)
  1444   {
  1445           $_REQUEST[$VarName] = $VarValue;
  1446           $_POST[$VarName] = $VarValue;
  1447           $_GET[$VarName] = $VarValue;
  1448   }
  1449  
  1450   function PassVar(&$source)
  1451   {
  1452           // source array + any count of key names in passed array
  1453           $params = func_get_args();
  1454           array_shift($params);
  1455  
  1456           if( count($params) )
  1457           {
  1458                   $ret = Array();
  1459                   foreach($params as $var_name)
  1460                           if( isset($source[$var_name]) )
  1461                                   $ret[] = $var_name.'='.$source[$var_name];
  1462                   $ret = '&'.implode('&', $ret);
  1463           }
  1464           return $ret;
  1465   }
  1466  
  1467   function GetSubmitVariable(&$array, $postfix)
  1468   {
  1469           // gets edit status of module
  1470           // used in case if some modules share
  1471           // common action parsed by kernel parser,
  1472           // but each module uses own EditStatus variable
  1473  
  1474           $modules = Array('In-Link' => 'Link', 'In-News' => 'News', 'In-Bulletin' => 'Topic', 'In-Portal'=>'Review');
  1475           foreach($modules as $module => $prefix)
  1476                   if( isset($array[$prefix.$postfix]) )
  1477                           return Array('Module' => $module, 'variable' => $array[$prefix.$postfix]);
  1478           return false;
  1479   }
  1480  
  1481   function GetModuleByAction()
  1482   {
  1483           $prefix2module = Array('m' => 'In-Portal', 'l' => 'In-Link', 'n' => 'In-News', 'bb' => 'In-Bulletin');
  1484           $action = GetVar('Action');
  1485           if($action)
  1486           {
  1487                   $module_prefix = explode('_', $action);
  1488                   return $prefix2module[ $module_prefix[0] ];
  1489           }
  1490           else
  1491                   return false;
  1492   }
  1493  
  1494   function dir_size($dir) {
  1495      // calculates folder size based on filesizes inside it (recursively)
  1496      $totalsize=0;
  1497      if ($dirstream = @opendir($dir)) {
  1498          while (false !== ($filename = readdir($dirstream))) {
  1499              if ($filename!="." && $filename!="..")
  1500              {
  1501                  if (is_file($dir."/".$filename))
  1502                      $totalsize+=filesize($dir."/".$filename);
  1503  
  1504                  if (is_dir($dir."/".$filename))
  1505                      $totalsize+=dir_size($dir."/".$filename);
  1506              }
  1507          }
  1508      }
  1509      closedir($dirstream);
  1510      return $totalsize;
  1511   }
  1512  
  1513   function size($bytes) {
  1514     // shows formatted file/directory size
  1515     $types =  Array("la_bytes","la_kilobytes","la_megabytes","la_gigabytes","la_terabytes");
  1516      $current = 0;
  1517     while ($bytes > 1024) {
  1518      $current++;
  1519      $bytes /= 1024;
  1520     }
  1521     return round($bytes,2)." ".language($types[$current]);
  1522   }
  1523  
  1524   function echod($str)
  1525   {
  1526           // echo debug output
  1527           echo str_replace( Array('[',']'), Array('[<b>', '</b>]'), $str).'<br>';
  1528   }
  1529  
  1530  
  1531   function PrepareParams($source, $to_lower, $mapping)
  1532   {
  1533           // prepare array with form values to use with item
  1534           $result = Array();
  1535           foreach($to_lower as $field)
  1536                   $result[ $field ] = $source[ strtolower($field) ];
  1537  
  1538           if( is_array($mapping) )
  1539           {
  1540                   foreach($mapping as $field_from => $field_to)
  1541                           $result[$field_to] = $source[$field_from];
  1542           }
  1543  
  1544           return $result;
  1545   }
  1546  
  1547   function GetELT($field, $phrases = Array())
  1548   {
  1549           // returns FieldOptions equivalent in In-Portal
  1550           $ret = Array();
  1551           foreach($phrases as $phrase)
  1552                   $ret[] = admin_language($phrase);
  1553           $ret = "'".implode("','", $ret)."'";
  1554           return 'ELT('.$field.','.$ret.')';
  1555   }
  1556  
  1557   function GetModuleImgPath($module)
  1558   {
  1559           global $rootURL, $admin;
  1560           return $rootURL.$module.'/'.$admin.'/images';
  1561   }
  1562  
  1563   function ActionPostProcess($StatusField, $ListClass, $ListObjectName = '', $IDField = null)
  1564   {
  1565           // each action postprocessing stuff from admin
  1566           if( !isset($_REQUEST[$StatusField]) ) return false;
  1567  
  1568           $list =& $GLOBALS[$ListObjectName];
  1569           if( !is_object($list) ) $list = new $ListClass();
  1570           $SFValue = $_REQUEST[$StatusField]; // status field value
  1571           switch($SFValue)
  1572           {
  1573                   case 1: // User hit "Save" button
  1574                   $list->CopyFromEditTable($IDField);
  1575                   break;
  1576                   case 2: // User hit "Cancel" button
  1577                           $list->PurgeEditTable($IDField);
  1578                           break;
  1579           }
  1580           if( function_exists('SpecificProcessing') ) SpecificProcessing($StatusField, $SFValue);
  1581           if($SFValue == 1 || $SFValue == 2) $list->Clear();
  1582   }
  1583  
  1584   if( !function_exists('getArrayValue') )
  1585   {
  1586           /**
  1587            * Returns array value if key exists
  1588            *
  1589            * @param Array $aArray
  1590            * @param int $aIndex
  1591            * @return string
  1592            */
  1593           function getArrayValue(&$aArray, $aIndex)
  1594           {
  1595                   return isset($aArray[$aIndex]) ? $aArray[$aIndex] : false;
  1596           }
  1597   }
  1598   function MakeHTMLTag($element, $attrib_prefix)
  1599   {
  1600           $result = Array();
  1601           $ap_length = strlen($attrib_prefix);
  1602           foreach($element->attributes as $attib_name => $attr_value)
  1603                   if( substr($attib_name, $ap_length) == $ap_length )
  1604                           $result[] = substr($attib_name, $ap_length, strlen($attib_name)).'="'.$attr_value.'"';
  1605           return count($result) ? implode(' ', $result) : false;
  1606   }
  1607  
  1608   function GetImportScripts()
  1609   {
  1610           // return currently installed import scripts
  1611           static $import_scripts = Array();
  1612           if( count($import_scripts) == 0 )
  1613           {
  1614                   
  1615                   $sql = 'SELECT imp.* , m.LoadOrder
  1616                                   FROM '.TABLE_PREFIX.'ImportScripts imp
  1617                                   LEFT JOIN '.TABLE_PREFIX.'Modules m ON m.Name = imp.is_Module
  1618                                   ORDER BY m.LoadOrder';
  1619                   
  1620                   $db =& GetADODBConnection();
  1621                   $rs = $db->Execute($sql);
  1622                   if ($rs && $rs->RecordCount() > 0) {
  1623                           while (!$rs->EOF) {
  1624                                   $rec =& $rs->fields;
  1625                                   $import_scripts[ $rec['is_id'] ] = Array(       'label' => $rec['is_label'], 'url' => $rec['is_script'],
  1626                                                                                           'enabled' => $rec['is_enabled'], 'field_prefix' => $rec['is_field_prefix'],
  1627                                                                                           'id' => $rec['is_string_id'], 'required_fields' => $rec['is_requred_fields'],
  1628                                                                                           'module' => strtolower($rec['is_Module']) );
  1629                                   $rs->MoveNext();
  1630                           }
  1631                   }
  1632                   else {
  1633                           $import_scripts = Array();
  1634                   }
  1635           }
  1636           return $import_scripts;
  1637   }
  1638  
  1639   function GetImportScript($id)
  1640   {
  1641           $scripts = GetImportScripts();
  1642           return isset($scripts[$id]) ? $scripts[$id] : false;
  1643   }
  1644   function GetNextTemplate($current_template)
  1645   {
  1646           // used on front, returns next template to make
  1647           // redirect to
  1648           $dest = GetVar('dest', true);
  1649           if(!$dest) $dest = GetVar('DestTemplate', true);
  1650           return $dest ? $dest : $current_template;
  1651   }
  1652  
  1653  
  1654   // functions for dealign with enviroment variable construction
  1655   function GenerateModuleEnv($prefix, $var_list)
  1656   {
  1657           // globalize module varible arrays
  1658           $main =& $GLOBALS[$prefix.'_var_list'];
  1659           $update =& $GLOBALS[$prefix.'_var_list_update'];
  1660           //echo "VAR: [$main]; VAR_UPDATE: [$update]<br>";
  1661           
  1662           // if update var count is zero, then do nothing
  1663           if( !is_array($update) || count($update) == 0 ) return '';
  1664           
  1665           // ensure that we have no empty values in enviroment variable
  1666           foreach($update as $vl_key => $vl_value) {
  1667           if(!$vl_value) $update[$vl_key] = '0'; // unset($update[$vl_key]);
  1668           }
  1669  
  1670           foreach($main as $vl_key => $vl_value) {
  1671           if(!$vl_value) $main[$vl_key] = '0'; // unset($main[$vl_key]);
  1672           }
  1673      
  1674           $ret = Array();
  1675           foreach($var_list as $var_name) {
  1676                   $value = GetEnvVar($prefix, $var_name);
  1677                   if(!$value && $var_name == 'id') $value = '0';
  1678                   $ret[] = $value;
  1679           }
  1680  
  1681           // Removing all var_list_udpate
  1682           $keys = array_keys($update);
  1683           foreach ($keys as $key) {
  1684                   unset($update[$key]);
  1685           }
  1686           
  1687           return ':'.$prefix.implode('-',$ret);
  1688   }
  1689  
  1690   // functions for dealign with enviroment variable construction
  1691   function GenerateModuleEnv_NEW($prefix, $var_list)
  1692   {
  1693           // globalize module varible arrays
  1694           $main =& $GLOBALS[$prefix.'_var_list'];
  1695           $update =& $GLOBALS[$prefix.'_var_list_update'];
  1696           //echo "VAR: [$main]; VAR_UPDATE: [$update]<br>";
  1697           
  1698           if ( isset($update) && $update )
  1699           {
  1700                   // ensure that we have no empty values in enviroment variable
  1701                   foreach($update as $vl_key => $vl_value) {
  1702                   if(!$vl_value) $update[$vl_key] = '0'; // unset($update[$vl_key]);
  1703                   }
  1704                   
  1705                   $app =& kApplication::Instance();
  1706                   $passed = $app->GetVar('prefixes_passed');
  1707                   $passed[] = $prefix;
  1708                   $app->SetVar('prefixes_passed', $passed);
  1709           }
  1710           else
  1711           {
  1712                   return Array();
  1713           }
  1714           
  1715           foreach($main as $vl_key => $vl_value) {
  1716           if(!$vl_value) $main[$vl_key] = '0'; // unset($main[$vl_key]);
  1717           }
  1718      
  1719           $ret = Array();
  1720           foreach($var_list as $src_name => $dst_name) {
  1721                   $ret[$dst_name] = GetEnvVar($prefix, $src_name);
  1722           }
  1723  
  1724           // Removing all var_list_udpate
  1725           if ( isset($update) && $update )
  1726           {
  1727                   $keys = array_keys($update);
  1728                   foreach ($keys as $key) unset($update[$key]);
  1729           }
  1730           return $ret;
  1731   }
  1732  
  1733   function GetEnvVar($prefix, $name)
  1734   {
  1735           // get variable from template variable's list
  1736           // (used in module parsers to build env string)
  1737           $main =& $GLOBALS[$prefix.'_var_list'];
  1738           $update =& $GLOBALS[$prefix.'_var_list_update'];
  1739  
  1740           return isset($update[$name]) ? $update[$name] : ( isset($main[$name]) ? $main[$name] : '');
  1741   }
  1742  
  1743   /**
  1744    * Checks if debug mode is active
  1745    *
  1746    * @return bool
  1747    */
  1748   function IsDebugMode($check_debugger = true)
  1749   {
  1750           $debug_mode = defined('DEBUG_MODE') && DEBUG_MODE;
  1751           if($check_debugger) $debug_mode = $debug_mode && isset($GLOBALS['debugger']);
  1752           return $debug_mode;
  1753   }
  1754  
  1755   /**
  1756    * Checks if we are in admin
  1757    *
  1758    * @return bool
  1759    */
  1760   function IsAdmin()
  1761   {
  1762           return defined('ADMIN') && constant('ADMIN') == 1 ? 1 : 0;
  1763   }
  1764  
  1765   /**
  1766    * Two strings in-case-sensitive compare.
  1767    * Returns >0, when string1 > string2,
  1768    *         <0, when string1 > string2,
  1769    *          0, when string1 = string2
  1770    *
  1771    * @param string $string1
  1772    * @param string $string2
  1773    * @return int
  1774    */
  1775   function stricmp ($string1, $string2) {
  1776           return strcmp(strtolower($string1), strtolower($string2));
  1777   }
  1778  
  1779   /**
  1780    * Generates unique code
  1781    *
  1782    * @return string
  1783    */
  1784   function GenerateCode()
  1785   {
  1786           list($usec, $sec) = explode(" ",microtime());
  1787  
  1788           $id_part_1 = substr($usec, 4, 4);
  1789           $id_part_2 = mt_rand(1,9);
  1790           $id_part_3 = substr($sec, 6, 4);
  1791           $digit_one = substr($id_part_1, 0, 1);
  1792           if ($digit_one == 0) {
  1793                   $digit_one = mt_rand(1,9);
  1794                   $id_part_1 = ereg_replace("^0","",$id_part_1);
  1795                   $id_part_1=$digit_one.$id_part_1;
  1796           }
  1797           return $id_part_1.$id_part_2.$id_part_3;
  1798   }
  1799  
  1800   function bracket_comp($elem1, $elem2)
  1801   {
  1802           if( ($elem1['End']>$elem2['End'] || $elem1['End'] == -1) && $elem2['End'] != -1 )
  1803           {
  1804                   return 1;
  1805           }
  1806           elseif ( ($elem1['End']<$elem2['End'] || $elem2['End'] == -1) && $elem1['End'] != -1 )
  1807           {
  1808                   return -1;
  1809           }
  1810           else
  1811           {
  1812                   return 0;
  1813           }
  1814   }
  1815  
  1816   function bracket_id_sort($first_id, $second_id)
  1817   {
  1818           $first_abs = abs($first_id);
  1819           $second_abs = abs($second_id);
  1820           $first_sign = ($first_id == 0) ? 0 : $first_id / $first_abs;
  1821           $second_sign = ($second_id == 0) ? 0 : $second_id / $second_abs;
  1822           if($first_sign != $second_sign)
  1823           {
  1824                   if($first_id > $second_id) {
  1825                           $bigger =& $first_abs;
  1826                           $smaller =& $second_abs;
  1827                   }
  1828                   else {
  1829                           $bigger =& $second_abs;
  1830                           $smaller =& $first_abs;
  1831                   }
  1832                   $smaller = $bigger + $smaller;
  1833           }
  1834  
  1835           if($first_abs > $second_abs) {
  1836                   return 1;
  1837           }
  1838           elseif ($first_abs < $second_abs)
  1839           {
  1840                   return -1;
  1841           }
  1842           else
  1843           {
  1844                   return 0;
  1845           }
  1846   }
  1847  
  1848   function pr_bracket_comp($elem1, $elem2)
  1849   {
  1850  
  1851           if ($elem1['MinQty']!="" && $elem1['MaxQty']=="" && $elem2['MinQty']!="" && $elem2['MaxQty']!="")       return 1;
  1852           if ($elem1['MinQty']!="" && $elem1['MaxQty']=="" && $elem2['MinQty']=="" && $elem2['MaxQty']=="")       return -1;
  1853  
  1854  
  1855           if ($elem1['MaxQty']=="" && $elem2['MaxQty']!="")       return 1;
  1856           if ($elem1['MaxQty']!="" && $elem2['MaxQty']=="")       return -1;
  1857  
  1858  
  1859           if( ($elem1['MaxQty']>$elem2['MaxQty'] && $elem2['MaxQty']!=-1) || ($elem1['MaxQty'] == -1 && $elem2['MaxQty'] != -1 ))
  1860           {
  1861                   return 1;
  1862           }
  1863           elseif ( ($elem1['MaxQty']<$elem2['MaxQty']) || ($elem2['MaxQty'] == -1 && $elem1['MaxQty'] != -1 ))
  1864           {
  1865                   return -1;
  1866           }
  1867           else
  1868           {
  1869                   return 0;
  1870           }
  1871   }
  1872  
  1873   function ap_bracket_comp($elem1, $elem2)
  1874   {
  1875  
  1876           if ($elem1['FromAmount']!="" && $elem1['ToAmount']=="" && $elem2['FromAmount']!="" && $elem2['ToAmount']!="")   return 1;
  1877           if ($elem1['FromAmount']!="" && $elem1['ToAmount']=="" && $elem2['FromAmount']=="" && $elem2['ToAmount']=="")   return -1;
  1878  
  1879  
  1880           if ($elem1['ToAmount']=="" && $elem2['ToAmount']!="")   return 1;
  1881           if ($elem1['ToAmount']!="" && $elem2['ToAmount']=="")   return -1;
  1882  
  1883  
  1884           if( ($elem1['ToAmount']>$elem2['ToAmount'] && $elem2['ToAmount']!=-1) || ($elem1['ToAmount'] == -1 && $elem2['ToAmount'] != -1 ))
  1885           {
  1886                   return 1;
  1887           }
  1888           elseif ( ($elem1['ToAmount']<$elem2['ToAmount']) || ($elem2['ToAmount'] == -1 && $elem1['ToAmount'] != -1 ))
  1889           {
  1890                   return -1;
  1891           }
  1892           else
  1893           {
  1894                   return 0;
  1895           }
  1896   }
  1897  
  1898   function pr_bracket_id_sort($first_id, $second_id)
  1899   {
  1900           $first_abs = abs($first_id);
  1901           $second_abs = abs($second_id);
  1902           $first_sign = ($first_id == 0) ? 0 : $first_id / $first_abs;
  1903           $second_sign = ($second_id == 0) ? 0 : $second_id / $second_abs;
  1904           if($first_sign != $second_sign)
  1905           {
  1906                   if($first_id > $second_id) {
  1907                           $bigger =& $first_abs;
  1908                           $smaller =& $second_abs;
  1909                   }
  1910                   else {
  1911                           $bigger =& $second_abs;
  1912                           $smaller =& $first_abs;
  1913                   }
  1914                   $smaller = $bigger + $smaller;
  1915           }
  1916  
  1917           if($first_abs > $second_abs) {
  1918                   return 1;
  1919           }
  1920           elseif ($first_abs < $second_abs)
  1921           {
  1922                   return -1;
  1923           }
  1924           else
  1925           {
  1926                   return 0;
  1927           }
  1928   }
  1929  
  1930           function inp_htmlize($var, $strip = 0)
  1931           {
  1932                   if( is_array($var) )
  1933                   {
  1934                           foreach($var as $k => $v) $var[$k] = inp_htmlize($v, $strip);
  1935                   }
  1936                   else
  1937                   {
  1938                           $var = htmlspecialchars($strip ? stripslashes($var) : $var);
  1939                   }
  1940                   return $var;
  1941           }
  1942  
  1943           /**
  1944            * Sets in-portal cookies, that will not harm K4 to breath free :)
  1945            *
  1946            * @param string $name
  1947            * @param mixed $value
  1948            * @param int $expire
  1949            * @author Alex
  1950            */
  1951           function set_cookie($name, $value, $expire = 0, $cookie_path = null)
  1952           {
  1953                   if (!isset($cookie_path))
  1954                   {
  1955                           $cookie_path = IsAdmin() ? rtrim(BASE_PATH, '/').'/admin' : BASE_PATH;
  1956                   }
  1957                   setcookie($name, $value, $expire, $cookie_path, $_SERVER['HTTP_HOST']);
  1958           }
  1959  
  1960           /**
  1961            * If we are on login required template, but we are not logged in, then logout user
  1962            *
  1963            * @return bool
  1964            */
  1965           function require_login($condition = null, $redirect_params = 'logout=1', $pass_env = false)
  1966           {
  1967                   if( !isset($condition) ) $condition = !admin_login();
  1968                   if(!$condition) return false;
  1969  
  1970                   global $objSession, $adminURL;
  1971               if( !headers_sent() ) set_cookie(SESSION_COOKIE_NAME, ' ', adodb_mktime() - 3600);
  1972               $objSession->Logout();
  1973               if($pass_env) $redirect_params = 'env='.BuildEnv().'&'.$redirect_params;
  1974               header('Location: '.$adminURL.'/index.php?'.$redirect_params);
  1975               exit;
  1976           }
  1977  
  1978           if( !function_exists('safeDefine') )
  1979           {
  1980                   /**
  1981                    * Define constant if it was not already defined before
  1982                    *
  1983                    * @param string $const_name
  1984                    * @param string $const_value
  1985                    * @access public
  1986                    */
  1987                   function safeDefine($const_name, $const_value)
  1988                   {
  1989                           if(!defined($const_name)) define($const_name,$const_value);
  1990                   }
  1991           }
  1992           
  1993           /**
  1994            * Builds up K4 url from data supplied by in-portal
  1995            *
  1996            * @param string $t template
  1997            * @param Array $params
  1998            * @param string $index_file
  1999            * @return string
  2000            */
  2001           function HREF_Wrapper($t = '', $params = null, $index_file = null)
  2002           {
  2003                   $url_params = BuildEnv_NEW();
  2004                   if( isset($params) ) $url_params = array_merge_recursive2($url_params, $params);
  2005                   if(!$t)
  2006                   {
  2007                           $t = $url_params['t'];
  2008                           unset($url_params['t']);
  2009                   }
  2010                   $app =& kApplication::Instance();
  2011                   return $app->HREF($t, '', $url_params, $index_file);
  2012           }
  2013           
  2014           /**
  2015            * Set url params based on tag params & mapping hash passed
  2016            *
  2017            * @param Array $url_params - url params before change
  2018            * @param Array $tag_attribs - tag attributes
  2019            * @param Array $params_map key - tag_param, value - url_param
  2020            */
  2021           function MapTagParams(&$url_params, $tag_attribs, $params_map)
  2022           {
  2023                   foreach ($params_map as $tag_param => $url_param)
  2024           {
  2025                   if( getArrayValue($tag_attribs, $tag_param) ) $url_params[$url_param] = $tag_attribs[$tag_param];
  2026           }
  2027           }
  2028           
  2029           function ExtractParams($params_str, $separator = '&')
  2030           {
  2031           if(!$params_str) return Array();
  2032           
  2033           $ret = Array();
  2034                   $parts = explode($separator, trim($params_str, $separator) );
  2035           foreach ($parts as $part)
  2036           {
  2037                   list($var_name, $var_value) = explode('=', $part);
  2038                   $ret[$var_name] = $var_value;
  2039           }
  2040           return $ret;
  2041           }
  2042           
  2043           if( !function_exists('constOn') )
  2044           {
  2045                   /**
  2046                    * Checks if constant is defined and has positive value
  2047                    *
  2048                    * @param string $const_name
  2049                    * @return bool
  2050                    */
  2051                   function constOn($const_name)
  2052                   {
  2053                           return defined($const_name) && constant($const_name);
  2054                   }
  2055           }
  2056           
  2057           function &recallObject($var_name, $class_name)
  2058           {
  2059                   if (!isset($GLOBALS[$var_name]) || !is_object($GLOBALS[$var_name]))
  2060                   {
  2061                           $GLOBALS[$var_name] = new $class_name();
  2062                   }
  2063                   return $GLOBALS[$var_name];
  2064           }
  2065  
  2066   ?>