<?php

if (!function_exists('parse_portal_ini')) {
	function parse_portal_ini($file, $parse_section = false) {

			if (!file_exists($file)) return false;

	    if(file_exists($file) && !is_readable($file))
	        die('Could Not Open Ini File');

	    $contents = file($file);

	    $retval = array();

	    $section = '';
	    $ln = 1;
	    $resave = false;
	    foreach($contents as $line) {
	    		if ($ln == 1 && $line != '<'.'?'.'php die() ?'.">\n") {
	    			$resave = true;
	    		}
	    		$ln++;
	        $line = trim($line);
	        $line = eregi_replace(';[.]*','',$line);
	        if(strlen($line) > 0) {
	            //echo $line . " - ";
	            if(eregi('^[[a-z]+]$',str_replace(' ', '', $line))) {
	                //echo 'section';
	                $section = substr($line,1,(strlen($line)-2));
	                if ($parse_section) {
	                	$retval[$section] = array();
	                }
	                continue;
	            } elseif(eregi('=',$line)) {
	                //echo 'main element';
	                list($key,$val) = explode(' = ',$line);
	                if (!$parse_section) {
	                	$retval[trim($key)] = str_replace('"', '', $val);
	                }
	                else {
						$retval[$section][trim($key)] = str_replace('"', '', $val);
	                }
	            } //end if
	            //echo '<br />';
	        } //end if
	    } //end foreach
	    if ($resave) {
	    	$fp = fopen($file, "w");
	    	reset($contents);
				fwrite($fp,'<'.'?'.'php die() ?'.">\n\n");
				foreach($contents as $line) fwrite($fp,"$line");
				fclose($fp);
			}

	    return $retval;
	}
}

	$vars = parse_portal_ini(FULL_PATH.'/config.php');
	if ($vars) {
		foreach ($vars as $config_key => $config_value) {
			$GLOBALS['g_'.$config_key] = $config_value;
		}
		unset($config_key, $config_value);
	}

/*list the tables which contain item data */
$ItemTables = array();

$KeywordIgnore = array();
global $debuglevel;

$debuglevel = 0;
//$GLOBALS['debuglevel'] = 0;

/*New, Hot, Pop field values */
define('NEVER', 0);
define('ALWAYS', 1);
define('AUTO', 2);

/*Status Values */
if( !defined('STATUS_DISABLED') ) define('STATUS_DISABLED', 0);
if( !defined('STATUS_ACTIVE') ) define('STATUS_ACTIVE', 1);
if( !defined('STATUS_PENDING') ) define('STATUS_PENDING', 2);

$LogLevel = 0;
$LogFile = NULL;

/**
 * Returns reference to database connection
 *
 * @param bool $new_type Return Kernel4 or in-portal connection object
 * @return kDBConnection
 */
function &GetADODBConnection($new_type = false)
{
	static $DB = null;

	global $g_DBType, $g_DBHost, $g_DBUser, $g_DBUserPassword, $g_DBName, $g_DebugMode;
	global $ADODB_FETCH_MODE, $ADODB_COUNTRECS, $ADODB_CACHE_DIR, $pathtoroot;

	if ($new_type) {
		$application =& kApplication::Instance();
		return $application->GetADODBConnection();
	}
	
	if( !isset($DB) && strlen($g_DBType) > 0 )
	{
		$DB = ADONewConnection($g_DBType);
		$connected = $DB->Connect($g_DBHost, $g_DBUser, $g_DBUserPassword, $g_DBName);
		if(!$connected) die("Error connecting to database $g_DBHost <br>\n");

		$ADODB_CACHE_DIR = $pathtoroot."cache";
		$ADODB_FETCH_MODE = 2;
		$ADODB_COUNTRECS = false;
		$DB->debug = defined('ADODB_OUTP') ? 1 : 0;
		$DB->cacheSecs = 3600;
		$DB->Execute('SET SQL_BIG_SELECTS = 1');
	}
	elseif( !strlen($g_DBType) )
	{
		global $rootURL;
		echo 'In-Portal is probably not installed, or configuration file is missing.<br>';
		echo 'Please use the installation script to fix the problem.<br><br>';
		if ( !preg_match('/admin/', __FILE__) ) $ins = 'admin/';

		echo '<a href="'.$rootURL.$ins.'install.php">Go to installation script</a><br><br>';
		flush();
		exit;
	}
	return $DB;
}

function GetNextResourceId($Increment=1)
{
	global $objModules, $pathtoroot;
	$table_name = GetTablePrefix().'IdGenerator';

	$db = &GetADODBConnection();

	// dummy protection: get maximal resource id used actually and fix last_id used
	$max_resourceid = 0;

	$m = GetModuleArray();
	foreach($m as $key=>$value)
	{
		$path = $pathtoroot. $value."admin/include/parser.php";
		if(file_exists($path))
		{
			include_once($path);
		}
	}

	$table_info = $objModules->ExecuteFunction('GetModuleInfo', 'dupe_resourceids');
	$sql_template = 'SELECT MAX(ResourceId) FROM '.GetTablePrefix().'%s';

	foreach($table_info as $module_name => $module_info)
	{
		foreach($module_info as $module_sub_info)
		{
			$sql = sprintf($sql_template,$module_sub_info['Table']);
			$tmp_resourceid = $db->GetOne($sql);
			if($tmp_resourceid > $max_resourceid) $max_resourceid = $tmp_resourceid;
		}
	}

	// update lastid to be next resourceid available
	$db->Execute('LOCK TABLES '.$table_name.' WRITE');

	$last_id = $db->GetOne('SELECT lastid FROM '.$table_name);
	if ($last_id - 1 > $max_resourceid) $max_resourceid = $last_id - 1;

	$id_diff = $db->GetOne('SELECT '.$max_resourceid.' + 1 - lastid FROM '.$table_name);
	if($id_diff) $Increment += $id_diff;

	$sql = 'UPDATE '.$table_name.' SET lastid = lastid + '.$Increment; // set new id in db
	$db->Execute($sql);

	$val = $db->GetOne('SELECT lastid FROM '.$table_name);
	if($val === false)
	{
		$db->Execute('INSERT INTO '.$table_name.' (lastid) VALUES ('.$Increment.')');
		$val = $Increment;
	}
	$db->Execute('UNLOCK TABLES');

	return $val - $Increment  + $id_diff; // return previous free id (-1) ?
}

function AddSlash($s)
{
    if(substr($s,-1) != "/")
    {
        return $s."/";
    }
    else
        return $s;
}

function StripNewline($s)
{
	$bfound = false;
	while (strlen($s)>0 && !$bfound)
	{
		if(ord(substr($s,-1))<32)
		{
			$s = substr($s,0,-1);
		}
		else
		  $bfound = true;
	}
	return $s;
}

function DeleteElement($array, $indice)
{
  for($i=$indice;$i<count($array)-1;$i++)
        $array[$i] = $array[$i+1];
  unset($array[count($array)-1]);
  return $array;
}

function DeleteElementValue($needle, &$haystack)
{
  while(($gotcha = array_search($needle,$haystack)) > -1)
   unset($haystack[$gotcha]);
}

function TableCount($TableName, $where="",$JoinCats=1)
{
    $db = &GetADODBConnection();
    if(!$JoinCats)
    {
      $sql = "SELECT count(*) as TableCount FROM $TableName";
    }
    else
        $sql = "SELECT count(*) as TableCount FROM $TableName INNER JOIN ".GetTablePrefix()."CategoryItems ON ".GetTablePrefix()."CategoryItems.ItemResourceId=$TableName.ResourceId";
    if(strlen($where)>0)
        $sql .= " WHERE ".$where;

    $rs = $db->Execute($sql);

//    echo "SQL TABLE COUNT: ".$sql."<br>\n";

    $res = $rs->fields["TableCount"];
    return $res;
}

Function QueryCount($sql)
{
	$sql = preg_replace('/SELECT(.*)FROM[ \n\r](.*)/is','SELECT COUNT(*) AS TableCount FROM $2', $sql);
	$sql = preg_replace('/(.*)LIMIT(.*)/is','$1', $sql);
	$sql = preg_replace('/(.*)ORDER BY(.*)/is','$1', $sql);

	//echo $sql;

	$db =& GetADODBConnection();
  	return $db->GetOne($sql);
}

function GetPageCount($ItemsPerPage,$NumItems)
{
 if($ItemsPerPage==0 || $NumItems==0)
 {
   return 1;
 }
 $value = $NumItems/$ItemsPerPage;
 return ceil($value);
}


/**
 * @return string
 * @desc Returns database table prefix entered while installation
*/
function GetTablePrefix()
{
    global $g_TablePrefix;

    return $g_TablePrefix;
}

function TableHasPrefix($t)
{
	$pre = GetTablePrefix();

	if(strlen($pre)>0)
	{
		if(substr($t,0,strlen($pre))==$pre)
		{
			return TRUE;
		}
		else
		  return FALSE;
	}
	else
	  return TRUE;
}

function AddTablePrefix($t)
{
	if(!TableHasPrefix($t))
	  $t = GetTablePrefix().$t;

	return $t;
}

function ThisDomain()
{
	global $objConfig, $g_Domain;

	if($objConfig->Get("DomainDetect"))
	{
		$d = $_SERVER['HTTP_HOST'];
	}
	else
	  $d = $g_Domain;

	return $d;
}

function GetIndexUrl($secure=0)
{
    global $indexURL, $rootURL, $secureURL;

    if ( class_exists('kApplication') )
    {
    	$application =& kApplication::Instance();
    	return $application->BaseURL().'index.php';
    }

    switch($secure)
    {
    	case 0:
    		$ret = $indexURL;
    		break;

    	case 1:
    		$ret = $secureURL."index.php";
    		break;

    	case 2:
    		$ret = $rootURL."index.php";
    		break;

    	default:
    		$ret = $i;
    		break;
    }
    return $ret;
}

function GetLimitSQL($Page,$PerPage)
{
  if($Page<1)
    $Page=1;

  if(is_numeric($PerPage))
  {
  	  if($PerPage==0)
  	    $PerPage = 20;
      $Start = ($Page-1)*$PerPage;
      $limit = "LIMIT ".$Start.",".$PerPage;
  }
  else
      $limit = NULL;
  return $limit;
}

function filelist ($currentdir, $startdir=NULL,$ext=NULL)
{
  global $pathchar;

  //chdir ($currentdir);

  // remember where we started from
  if (!$startdir)
  {
      $startdir = $currentdir;
  }

  $d = @opendir($currentdir);

  $files = array();
  if(!$d)
    return $files;
  //list the files in the dir
  while (false !== ($file = readdir($d)))
  {
      if ($file != ".." && $file != ".")
      {
          if (is_dir($currentdir."/".$file))
          {
              // If $file is a directory take a look inside
              $a = filelist ($currentdir."/".$file, $startdir,$ext);
              if(is_array($a))
                $files = array_merge($files,$a);
          }
          else
          {
              if($ext!=NULL)
              {
                  $extstr = stristr($file,".".$ext);
                  if(strlen($extstr))
                      $files[] = $currentdir."/".$file;
              }
              else
                $files[] = $currentdir.'/'.$file;
          }
      }
  }

  closedir ($d);

  return $files;
}

function DecimalToBin($dec,$WordLength=8)
{
  $bits = array();

  $str = str_pad(decbin($dec),$WordLength,"0",STR_PAD_LEFT);
  for($i=$WordLength;$i>0;$i--)
  {
      $bits[$i-1] = (int)substr($str,$i-1,1);
  }
  return $bits;
}
/*
function inp_escape($in, $html_enable=0)
{
	$out = stripslashes($in);
	$out = str_replace("\n", "\n^br^", $out);
	if($html_enable==0)
	{
		$out=ereg_replace("<","&lt;",$out);
		$out=ereg_replace(">","&gt;",$out);
		$out=ereg_replace("\"","&quot;",$out);
		$out = str_replace("\n^br^", "\n<br />", $out);
	}
	else
		$out = str_replace("\n^br^", "\n", $out);
	$out=addslashes($out);

	return $out;
}
*/
function inp_escape($var,$html=0)
{
	if($html)return $var;
	if(is_array($var))
		foreach($var as $k=>$v)
			$var[$k]=inp_escape($v);
	else
//		$var=htmlspecialchars($var,ENT_NOQUOTES);
		$var=strtr($var,Array('<'=>'&lt;','>'=>'&gt;',));
	return $var;
}
function inp_striptags($var,$html=0)
{
	if($html)return $var;
	if(is_array($var))
		foreach($var as $k=>$v)
			$var[$k]=inp_striptags($v);
	else
		$var=strip_tags($var);
	return $var;
}

function inp_unescape($in)
{
//	if (get_magic_quotes_gpc())
		return $in;
	$out=stripslashes($in);
	return $out;
}

function inp_textarea_unescape($in)
{
//	if (get_magic_quotes_gpc())
		return $in;
	$out=stripslashes($in);
	$out = str_replace("\n<br />", "\n", $out);
	return $out;
}

function HighlightKeywords($Keywords, $html, $OpenTag="", $CloseTag="")
{
    global $objConfig;

    if(!strlen($OpenTag))
        $OpenTag = "<B>";
    if(!strlen($CloseTag))
            $CloseTag = "</B>";

   	$r = preg_split('((>)|(<))', $html, -1, PREG_SPLIT_DELIM_CAPTURE);

   	foreach ($Keywords as $k) {
	   	for ($i = 0; $i < count($r); $i++) {
	       if ($r[$i] == "<") {
	           $i++; continue;
	       }
	       $r[$i] = preg_replace("/($k)/i", "$OpenTag\\1$CloseTag", $r[$i]);
	    }
   	}
   	return join("", $r);
}

/*
function HighlightKeywords($Keywords,$html, $OpenTag="", $CloseTag="")
{
    global $objConfig;

    if(!strlen($OpenTag))
        $OpenTag = "<B>";
    if(!strlen($CloseTag))
            $CloseTag = "</B>";
    $ret = strip_tags($html);

    foreach ($Keywords as $k)
    {
        if(strlen($k))
        {
          //$html = str_replace("<$k>", ":#:", $html);
          //$html = str_replace("</$k>", ":##:", $html);
          //$html = strip_tags($html);
          if ($html = preg_replace("/($k)/Ui","$OpenTag\\1$CloseTag", $html))
          //if ($html = preg_replace("/(>[^<]*)($k)([^<]*< )/Ui","$OpenTag\\1$CloseTag", $html))
            $ret = $html;
          //$ret = str_replace(":#:", "<$k>", $ret);
          //$ret = str_replace(":##:", "</$k>", $ret);
        }
    }
    return $ret;
}
*/
function ExtractDatePart($part, $datestamp)
{
	if ($datestamp <= 0) return '';
		
	$formats = Array(	'month' => 'm', 'day' => 'd', 'year' => 'Y',
						'time_24hr' => 'H:i', 'time_12hr' => 'g:i a', 'time' => GetTimeFormat(), 'date' => GetDateFormat() );
	
	$format = isset($formats[$part]) ? $formats[$part] : $part;
	return adodb_date($format, $datestamp);
}

function GetLocalTime($TimeStamp, $TargetZone = null)
{
	global $objConfig;
	
    if ($TargetZone == null) {
		$TargetZone = $objConfig->Get('Config_Site_Time');
    }
    
    $server = $objConfig->Get('Config_Server_Time');
    if ($TargetZone != $server) {
    	$offset = ($server - $TargetZone) * -1;
    	$TimeStamp = $TimeStamp + (3600 * $offset);
    }
    
    return $TimeStamp;
}

function _unhtmlentities ($string)
{
    $trans_tbl = get_html_translation_table (HTML_ENTITIES);
    $trans_tbl = array_flip ($trans_tbl);
    return strtr ($string, $trans_tbl);
}

function getLastStr($hay, $need){
  $getLastStr = 0;
  $pos = strpos($hay, $need);
  if (is_int ($pos)){ //this is to decide whether it is "false" or "0"
   while($pos) {
     $getLastStr = $getLastStr + $pos + strlen($need);
     $hay = substr ($hay , $pos + strlen($need));
     $pos = strpos($hay, $need);
   }
   return $getLastStr - strlen($need);
  } else {
   return -1; //if $need wasn´t found it returns "-1" , because it could return "0" if it´s found on position "0".
  }
}

// --- bbcode processing function: begin ----
function PreformatBBCodes($text)
{
	// convert phpbb url bbcode to valid in-bulletin's format
	// 1. urls
	$text = preg_replace('/\[url=(.*)\](.*)\[\/url\]/Ui','[url href="$1"]$2[/url]',$text);
	$text = preg_replace('/\[url\](.*)\[\/url\]/Ui','[url href="$1"]$1[/url]',$text);
	// 2. images
	$text = preg_replace('/\[img\](.*)\[\/img\]/Ui','[img src="$1" border="0"][/img]',$text);
	// 3. color
	$text = preg_replace('/\[color=(.*)\](.*)\[\/color\]/Ui','[font color="$1"]$2[/font]',$text);
	// 4. size
	$text = preg_replace('/\[size=(.*)\](.*)\[\/size\]/Ui','[font size="$1"]$2[/font]',$text);
	// 5. lists
	$text = preg_replace('/\[list(.*)\](.*)\[\/list\]/Uis','[ul]$2[/ul]',$text);
	// 6. email to link
	$text = preg_replace('/\[email\](.*)\[\/email\]/Ui','[url href="mailto:$1"]$1[/url]',$text);
	//7. b tag
	$text = preg_replace('/\[(b|i|u):(.*)\](.*)\[\/(b|i|u):(.*)\]/Ui','[$1]$3[/$4]',$text);
	//8. code tag
	$text = preg_replace('/\[code:(.*)\](.*)\[\/code:(.*)\]/Uis','[code]$2[/code]',$text);
	return $text;
}

/**
 * @return string
 * @param string $BBCode
 * @param string $TagParams
 * @param string $TextInside
 * @param string $ParamsAllowed
 * @desc Removes not allowed params from tag and returns result
*/
function CheckBBCodeAttribs($BBCode, $TagParams, $TextInside, $ParamsAllowed)
{
	//	$BBCode - bbcode to check, $TagParams - params string entered by user
	//	$TextInside - text between opening and closing bbcode tag
	//	$ParamsAllowed - list of allowed parameter names ("|" separated)
	$TagParams=str_replace('\"','"',$TagParams);
	$TextInside=str_replace('\"','"',$TextInside);
	if( $ParamsAllowed && preg_match_all('/ +([^=]*)=["\']?([^ "\']*)["\']?/is',$TagParams,$params,PREG_SET_ORDER) )
	{
		$ret = Array();
		foreach($params as $param)
		{
			// remove spaces in both parameter name & value & lowercase parameter name
			$param[1] = strtolower(trim($param[1]));	// name lowercased
			if(($BBCode=='url')&&($param[1]=='href'))
				if(false!==strpos(strtolower($param[2]),'script:'))
					return $TextInside;
//					$param[2]='about:blank';
			if( isset($ParamsAllowed[ $param[1] ]) )
				$ret[] = $param[1].'="'.$param[2].'"';
		}
		$ret = count($ret) ? ' '.implode(' ',$ret) : '';
		return '<'.$BBCode.$ret.'>'.$TextInside.'</'.$BBCode.'>';
	}
	else
		return '<'.$BBCode.'>'.$TextInside.'</'.$BBCode.'>';
	return false;
}
function ReplaceBBCode($text)
{
	global $objConfig;
  	// convert phpbb bbcodes to in-bulletin bbcodes
  	$text = PreformatBBCodes($text);

//	$tag_defs = 'b:;i:;u:;ul:type|align;font:color|face|size;url:href;img:src|border';

  	$tags_defs = $objConfig->Get('BBTags');
 	foreach(explode(';',$tags_defs) as $tag)
 	{
  		$tag = explode(':',$tag);
  		$tag_name = $tag[0];
  		$tag_params = $tag[1]?array_flip(explode('|',$tag[1])):0;
		$text = preg_replace('/\['.$tag_name.'(.*)\](.*)\[\/'.$tag_name.' *\]/Uise','CheckBBCodeAttribs("'.$tag_name.'",\'$1\',\'$2\',$tag_params);', $text);
  	}

  	// additional processing for [url], [*], [img] bbcode
	$text = preg_replace('/<url>(.*)<\/url>/Usi','<url href="$1">$1</url>',$text);
	$text = preg_replace('/<font>(.*)<\/font>/Usi','$1',$text); // skip empty fonts
  	$text = str_replace(	Array('<url','</url>','[*]'),
  							Array('<a target="_blank"','</a>','<li>'),
  							$text);

  	// bbcode [code]xxx[/code] processing
  	$text = preg_replace('/\[code\](.*)\[\/code\]/Uise', "ReplaceCodeBBCode('$1')", $text);
  	return $text;
}
function leadSpace2nbsp($x)
{
	return "\n".str_repeat('&nbsp;',strlen($x));
}
function ReplaceCodeBBCode($input_string)
{
	$input_string=str_replace('\"','"',$input_string);
	$input_string=$GLOBALS['objSmileys']->UndoSmileys(_unhtmlentities($input_string));
	$input_string=trim($input_string);
	$input_string=inp_htmlize($input_string);
	$input_string=str_replace("\r",'',$input_string);
  	$input_string = str_replace("\t", "    ", $input_string);
	$input_string = preg_replace('/\n( +)/se',"leadSpace2nbsp('$1')",$input_string);
	$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>';
//	$input_string='<textarea wrap="off" style="border:1px solid #888888;width:100%;height:200px;background-color:#eeeeee;">'.inp_htmlize($input_string).'</textarea>';
	return $input_string;

	if(false!==strpos($input_string,'<'.'?'))
	{
		$input_string=str_replace('<'.'?','<'.'?php',$input_string);
		$input_string=str_replace('<'.'?phpphp','<'.'?php',$input_string);
		$input_string=@highlight_string($input_string,1);
	}
	else
	{
		$input_string = @highlight_string('<'.'?php'.$input_string.'?'.'>',1);
		$input_string = str_replace('&lt;?php', '', str_replace('?&gt;', '', $input_string));
	}
	return str_replace('<br />','',$input_string);

}


// --- bbcode processing function: end ----

function GetMinValue($Table,$Field, $Where=NULL)
{
    $ret = 0;
    $sql = "SELECT min($Field) as val FROM $Table ";
    if(strlen($where))
        $sql .= "WHERE $Where";
    $ado = &GetADODBConnection();
    $rs = $ado->execute($sql);
    if($rs)
        $ret = (int)$rs->fields["val"];
    return $ret;
}


if (!function_exists( 'getmicrotime' ) ) {
	function getmicrotime()
	{
	    list($usec, $sec) = explode(" ",microtime());
	    return ((float)$usec + (float)$sec);
	}
}

function SetMissingDataErrors($f)
{
    global $FormError;

    $count = 0;
    if(is_array($_POST))
    {
      if(is_array($_POST["required"]))
      {
        foreach($_POST["required"] as $r)
        {
          $found = FALSE;
          if(is_array($_FILES))
          {
            if( isset($_FILES[$r]) && $_FILES[$r]['size'] > 0 ) $found = TRUE;
          }

          if(!strlen(trim($_POST[$r])) && !$found)
          {
            $count++;

            if (($r == "dob_day") || ($r == "dob_month") || ($r == "dob_year"))
            	$r = "dob";

            $tag = isset($_POST["errors"]) ? $_POST["errors"][$r] : '';
            if(!strlen($tag))
              $tag = "lu_ferror_".$f."_".$r;
            $FormError[$f][$r] = language($tag);
          }
        }
      }
    }
    return $count;
}

function makepassword($length=10)
{
  $pass_length=$length;

  $p1=array('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z');
  $p2=array('a','e','i','o','u');
  $p3=array('1','2','3','4','5','6','7','8','9');
  $p4=array('(','&',')',';','%');    // if you need real strong stuff

  // how much elements in the array
  // can be done with a array count but counting once here is faster

  $s1=21;// this is the count of $p1
  $s2=5; // this is the count of $p2
  $s3=9; // this is the count of $p3
  $s4=5; // this is the count of $p4

  // possible readable combinations

  $c1='121';    // will be like 'bab'
  $c2='212';      // will be like 'aba'
  $c3='12';      // will be like 'ab'
  $c4='3';        // will be just a number '1 to 9'  if you dont like number delete the 3
// $c5='4';        // uncomment to active the strong stuff

  $comb='4'; // the amount of combinations you made above (and did not comment out)



  for ($p=0;$p<$pass_length;)
  {
    mt_srand((double)microtime()*1000000);
    $strpart=mt_rand(1,$comb);
    // checking if the stringpart is not the same as the previous one
    if($strpart<>$previous)
    {
      $pass_structure.=${'c'.$strpart};

      // shortcutting the loop a bit
      $p=$p+strlen(${'c'.$strpart});
    }
    $previous=$strpart;
  }


  // generating the password from the structure defined in $pass_structure
  for ($g=0;$g<strlen($pass_structure);$g++)
  {
    mt_srand((double)microtime()*1000000);
    $sel=substr($pass_structure,$g,1);
    $pass.=${'p'.$sel}[mt_rand(0,-1+${'s'.$sel})];

  }
  return $pass;
}

function LogEntry($text,$writefile=FALSE)
{
  global $g_LogFile,$LogFile, $LogData, $LogLevel, $timestart;

  static $last;

  if(strlen($g_LogFile))
  {
    $el = str_pad(getmicrotime()- $timestart,10," ");
    if($last>0)
      $elapsed = getmicrotime() - $last;

    if(strlen($el)>10)
        $el = substr($el,0,10);
    $indent = str_repeat("  ",$LogLevel);
    $text = str_pad($text,$LogLevel,"==",STR_PAD_LEFT);
    $LogData .= "$el:". round($elapsed,6).":$indent $text";
    $last = getmicrotime();
    if($writefile==TRUE && is_writable($g_LogFile))
    {
      if(!$LogFile)
      {
         if(file_exists($g_LogFile))
            unlink($g_LogFile);
        $LogFile=@fopen($g_LogFile,"w");
      }
      if($LogFile)
      {
        fputs($LogFile,$LogData);
      }
    }
  }
}

function ValidEmail($email)
{
    if (eregi("^[a-z0-9]+([-_\.]?[a-z0-9])+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,4}", $email))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

function language($phrase,$LangId=0)
{
    global $objSession, $objLanguageCache, $objLanguages;

    if ($LangId == 0) {
        $LangId = $objSession->Get('Language');
    }
    
	if ($LangId == 0) {
		$LangId = $objLanguages->GetPrimary();
	}
    
    return $objLanguageCache->GetTranslation($phrase,$LangId);
}

function admin_language($phrase,$lang=0,$LinkMissing=FALSE)
{
    global $objSession, $objLanguageCache, $objLanguages;

	//echo "Language passed: $lang<br>";

    if($lang==0)
       $lang = $objSession->Get("Language");

    //echo "Language from session: $lang<br>";

	if($lang==0)
      $lang = $objLanguages->GetPrimary();

    //echo "Language after primary: $lang<br>";
    //echo "Phrase: $phrase<br>";
	$translation = $objLanguageCache->GetTranslation($phrase,$lang);
    if($LinkMissing && substr($translation,0,1)=="!" && substr($translation,-1)=="!")
    {
    	$res = "<A href=\"javascript:OpenPhraseEditor('&direct=1&label=$phrase'); \">$translation</A>";
    	return $res;
    }
    else
    	return $translation;
}

function prompt_language($phrase,$lang=0)
{
  return admin_language($phrase,$lang,TRUE);
}

function GetPrimaryTranslation($Phrase)
{
	global $objLanguages;

	$l = $objLanguages->GetPrimary();
	return language($Phrase,$l);
}

function CategoryNameCount($ParentId,$Name)
{
	$cat_table = GetTablePrefix()."Category";
	$sql = "SELECT Name from $cat_table WHERE ParentId=$ParentId AND ";
	$sql .="(Name LIKE '".addslashes($Name)."' OR Name LIKE 'Copy of ".addslashes($Name)."' OR Name LIKE 'Copy % of ".addslashes($Name)."')";

	$ado = &GetADODBConnection();
	$rs = $ado->Execute($sql);
	$ret = array();
	while($rs && !$rs->EOF)
	{
		$ret[] = $rs->fields["Name"];
		$rs->MoveNext();
	}
   	return $ret;
}

function CategoryItemNameCount($CategoryId,$Table,$Field,$Name)
{
	$Name=addslashes($Name);
	$cat_table = GetTablePrefix()."CategoryItems";
	$sql = "SELECT $Field FROM $Table INNER JOIN $cat_table ON ($Table.ResourceId=$cat_table.ItemResourceId) ";
	$sql .=" WHERE ($Field LIKE 'Copy % of $Name' OR $Field LIKE '$Name' OR $Field LIKE 'Copy of $Name') AND CategoryId=$CategoryId";
	//echo $sql."<br>\n ";
	$ado = &GetADODBConnection();
	$rs = $ado->Execute($sql);
	$ret = array();
	while($rs && !$rs->EOF)
	{
		$ret[] = $rs->fields[$Field];
		$rs->MoveNext();
	}
   	return $ret;
}

function &GetItemCollection($ItemName)
{
  global $objItemTypes;

  if(is_numeric($ItemName))
  {
  	$item = $objItemTypes->GetItem($ItemName);
  }
  else
    $item = $objItemTypes->GetTypeByName($ItemName);
  if(is_object($item))
  {
  	$module = $item->Get("Module");
  	$prefix = ModuleTagPrefix($module);
  	$func = $prefix."_ItemCollection";
  	if(function_exists($func))
  	{
  	  $var =& $func();
  	}
  }
  return $var;
}


function UpdateCategoryCount($item_type,$CategoriesIds,$ListType='')
{
	global $objCountCache, $objItemTypes;
	$db=&GetADODBConnection();
	if( !is_numeric($item_type) )
	{
		$sql = 'SELECT ItemType FROM '.$objItemTypes->SourceTable.' WHERE ItemName=\''.$item_type.'\'';
		$item_type=$db->GetOne($sql);
	}
	$objCountCache->EraseGlobalTypeCache($item_type);
	if($item_type)
	{
		if(is_array($CategoriesIds))
		{
			$CategoriesIds=implode(',',$CategoriesIds);
		}
		if (!$CategoriesIds)
		{

		}

		if(!is_array($ListType)) $ListType=Array($ListType=>'opa');

		$sql = 'SELECT ParentPath FROM '.GetTablePrefix().'Category WHERE CategoryId IN ('.$CategoriesIds.')';
		$rs = $db->Execute($sql);
		$parents = Array();
		while (!$rs->EOF)
		{
			$tmp=$rs->fields['ParentPath'];
			$tmp=substr($tmp,1,strlen($tmp)-2);
			$tmp=explode('|',$tmp);
			foreach ($tmp as $tmp_cat_id) {
				$parents[$tmp_cat_id]=1;
			}
			$rs->MoveNext();
		}
		$parents=array_keys($parents);
		$list_types=array_keys($ListType);
		foreach($parents as $ParentCategoryId)
		{
			foreach ($list_types as $list_type) {
				$objCountCache->DeleteValue($list_type, $item_type, $ParentCategoryId, 0);	// total count
				$objCountCache->DeleteValue($list_type, $item_type, $ParentCategoryId, 1);	// total count today
			}
		}
	}
	else
	{
		die('wrong item type passed to "UpdateCategoryCount"');
	}

/*  	if(is_object($item))
  	{
  		$ItemType  = $item->Get("ItemType");

		$sql = "DELETE FROM ".$objCountCache->SourceTable." WHERE ItemType=$ItemType";
		if( is_numeric($ListType) ) $sql .= " AND ListType=$ListType";
		$objCountCache->adodbConnection->Execute($sql);
  	}  */
}

function ResetCache($CategoryId)
{
	global $objCountCache;
	$db =& GetADODBConnection();
	$sql = 'SELECT ParentPath FROM '.GetTablePrefix().'Category WHERE CategoryId = '.$CategoryId;
	$parents = $db->GetOne($sql);
	$parents = substr($parents,1,strlen($parents)-2);
	$parents = explode('|',$parents);
	foreach($parents as $ParentCategoryId)
	{
		$objCountCache->DeleteValue('_', TYPE_TOPIC, $ParentCategoryId, 0);	// total topic count
		$objCountCache->DeleteValue('_', TYPE_TOPIC, $ParentCategoryId, 1);	// total
	}
}

function UpdateModifiedCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$ExtraId=NULL)
{
}

function UpdateGroupCategoryCount($ItemTypeName,$CatId=NULL,$Modifier=0,$GroupId=NULL)
{
}

function GetTagCache($module,$tag,$attribs,$env)
{
    global $objSystemCache, $objSession, $objConfig;

    if($objConfig->Get("SystemTagCache") && !$objSession->Get('PortalUserId'))
    {
        $name = $tag;
        if(is_array($attribs))
        {
            foreach($attribs as $n => $val)
            {
                $name .= "-".$val;
            }
        }
        $CachedValue = $objSystemCache->GetContextValue($name,$module,$env, $objSession->Get("GroupList"));
    }
    else
        $CachedValue="";
    return $CachedValue;
}

function SaveTagCache($module, $tag, $attribs, $env, $newvalue)
{
    global $objSystemCache, $objSession, $objConfig;

    if($objConfig->Get("SystemTagCache"))
    {
        $name = $tag;
        if(is_array($attribs))
        {
            foreach($attribs as $a => $val)
            {
                $name .= "-".$val;
            }
        }
        $objSystemCache->EditCacheItem($name,$newvalue,$module,0,$env,$objSession->Get("GroupList"));
    }
}

function DeleteTagCache($name,$extraparams, $env="")
{
    global $objSystemCache, $objConfig;

    if($objConfig->Get("SystemTagCache"))
    {
        $where = "Name LIKE '$name%".$extraparams."'";
        if(strlen($env))
            $where .= " AND Context LIKE $env";
        $objSystemCache->DeleteCachedItem($where);
    }
}

/**
 * Deletes whole tag cache for
 * selected module
 *
 * @param string $module
 * @param string $name
 * @access public
 */
function DeleteModuleTagCache($module, $tagname='')
{
    global $objSystemCache, $objConfig;

    if($objConfig->Get("SystemTagCache"))
    {
        $where = 'Module LIKE \''.$module.'\'';
        if(strlen($tagname))
        {
            $where .= ' AND Name LIKE \''.$tagname.'\'';
        }
        $objSystemCache->DeleteCachedItem($where);
    }
}



/*function ClearTagCache()
{
    global $objSystemCache, $objConfig;

    if($objConfig->Get("SystemTagCache"))
    {
        $where = '';
        $objSystemCache->DeleteCachedItem($where);
    }
}*/

/*function EraseCountCache()
{
//  global $objSystemCache, $objConfig;

    $db =& GetADODBConnection();
    $sql = 'DELETE * FROM '.GetTablePrefix().'CountCache';
    return $db->Execute($sql) ? true : false;
}*/


function ParseTagLibrary()
{
	$objTagList = new clsTagList();
	$objTagList->ParseInportalTags();
	unset($objTagList);
}

	function GetDateFormat($LangId = 0, $is_input = false)
	{
		global $objLanguages;
	
		if (!$LangId) {
			$LangId = $objLanguages->GetPrimary();
		}
		
		$l = $objLanguages->GetItem($LangId);
		$fmt = is_object($l) ? $l->Get(($is_input ? 'Input' : '').'DateFormat') : 'm-d-Y';
	
		if (getArrayValue($GLOBALS, 'FrontEnd')) {
			return $fmt;
		}
		return preg_replace('/y+/i','Y', $fmt);
	}

	function GetTimeFormat($LangId = 0, $is_input = false)
	{
		global $objLanguages;

		if (!$LangId) {
			$LangId = $objLanguages->GetPrimary();
		}
		$l = $objLanguages->GetItem($LangId);
		
		$fmt = is_object($l) ? $l->Get(($is_input ? 'Input' : '').'TimeFormat') : 'H:i:s';
		return $fmt;
	}

/**
 * Gets one of currently selected language options
 *
 * @param string $optionName
 * @param int $LangId
 * @return string
 * @access public
 */
function GetRegionalOption($optionName,$LangId=0)
{
	global $objLanguages, $objSession;

	if(!$LangId) $LangId=$objSession->Get('Language');
	if(!$LangId) $LangId=$objLanguages->GetPrimary();
	$l = $objLanguages->GetItem($LangId);
	return is_object($l)?$l->Get($optionName):false;
}

/**
 * Returns formatted timestamp
 *
 * @param int $TimeStamp
 * @param int $LangId
 * @param bool $is_input use input date format instead of display date format
 * @return string
 */
function LangDate($TimeStamp = null, $LangId = 0, $is_input = false)
{
  $fmt = GetDateFormat($LangId, $is_input);
  return adodb_date($fmt, $TimeStamp);
}

/**
 * Returns formatted timestamp
 *
 * @param int $TimeStamp
 * @param int $LangId
 * @param bool $is_input use input time format instead of display time format
 * @return string
 */
function LangTime($TimeStamp = null, $LangId = 0, $is_input = false)
{
  $fmt = GetTimeFormat($LangId, $is_input);
  return adodb_date($fmt, $TimeStamp);
}

function LangNumber($Num,$DecPlaces=NULL,$LangId=0)
{
	global $objLanguages;

  if(!$LangId)
    $LangId= $objLanguages->GetPrimary();
  $l = $objLanguages->GetItem($LangId);
  if(is_object($l))
  {
  	$ret = number_format($Num,$DecPlaces,$l->Get("DecimalPoint"),$l->Get("ThousandSep"));
  }
  else
    $ret = $num;

  return $ret;
}

function replacePngTags($x, $spacer="images/spacer.gif")
{
	global $rootURL,$pathtoroot;

    // make sure that we are only replacing for the Windows versions of Internet
    // Explorer 5+, and not Opera identified as MSIE
    $msie='/msie\s([5-9])\.?[0-9]*.*(win)/i';
    $opera='/opera\s+[0-9]+/i';
    if(!isset($_SERVER['HTTP_USER_AGENT']) ||
        !preg_match($msie,$_SERVER['HTTP_USER_AGENT']) ||
        preg_match($opera,$_SERVER['HTTP_USER_AGENT']))
        return $x;

    // find all the png images in backgrounds
    preg_match_all('/background-image:\s*url\(\'(.*\.png)\'\);/Uis',$x,$background);
    for($i=0;$i<count($background[0]);$i++){
        // simply replace:
        //  "background-image: url('image.png');"
        // with:
        //  "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(
        //      enabled=true, sizingMethod=scale src='image.png');"
        // haven't tested to see if background-repeat styles work...
        $x=str_replace($background[0][$i],'filter:progid:DXImageTransform.'.
                'Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale'.
                ' src=\''.$background[1][$i].'\');',$x);
    }

    // OK, time to find all the IMG tags with ".png" in them
    preg_match_all('/(<img.*\.png.*>|<input.*type=([\'"])image\\2.*\.png.*>)/Uis',$x,$images);
    while(list($imgnum,$v)=@each($images[0])){
        $original=$v;
        $atts=''; $width=0; $height=0;
        // If the size is defined by styles, find
        preg_match_all('/style=".*(width: ([0-9]+))px.*'.
                        '(height: ([0-9]+))px.*"/Ui',$v,$arr2);
        if(is_array($arr2) && count($arr2[0])){
            // size was defined by styles, get values
            $width=$arr2[2][0];
            $height=$arr2[4][0];
        }
        // size was not defined by styles, get values
        preg_match_all('/width=\"?([0-9]+)\"?/i',$v,$arr2);
        if(is_array($arr2) && count($arr2[0])){
            $width=$arr2[1][0];
        }
        preg_match_all('/height=\"?([0-9]+)\"?/i',$v,$arr2);
        if(is_array($arr2) && count($arr2[0])){
            $height=$arr2[1][0];
        }
        preg_match_all('/src=\"([^\"]+\.png)\"/i',$v,$arr2);
        if(isset($arr2[1][0]) && !empty($arr2[1][0]))
            $image=$arr2[1][0];
        else
            $image=NULL;

        // We do this so that we can put our spacer.gif image in the same
        // directory as the image
        $tmp=split('[\\/]',$image);
        array_pop($tmp);
        $image_path=join('/',$tmp);
           if(substr($image,0,strlen($rootURL))==$rootURL)
           {
          		$path = str_replace($rootURL,$pathtoroot,$image);
           }
          else
          {
        		$path = $pathtoroot."themes/telestial/$image";
          }
//        echo "Sizing $path.. <br>\n";
//        echo "Full Tag: ".htmlentities($image)."<br>\n";
        //if(!$height || !$width)
        //{

          $g = imagecreatefrompng($path);
          if($g)
          {
          	$height = imagesy($g);
          	$width = imagesx($g);
          }
        //}
        if(strlen($image_path)) $image_path.='/';

        // end quote is already supplied by originial src attribute
        $replace_src_with=$spacer.'" style="width: '.$width.
            'px; height: '.$height.'px; filter: progid:DXImageTransform.'.
            'Microsoft.AlphaImageLoader(src=\''.$image.'\', sizingMethod='.
            '\'scale\')';

        // now create the new tag from the old
        $new_tag=str_replace($image,$replace_src_with,$original);

        // now place the new tag into the content
        $x=str_replace($original,$new_tag,$x);
    }
    return $x;
}

if (!function_exists('print_pre')) {
	function print_pre($str)
	{
		// no comments here :)
		echo '<pre>'.print_r($str, true).'</pre>';
	}
}

function GetOptions($field) // by Alex
{
	// get dropdown values from custom field
	$tmp =& new clsCustomField();

	$tmp->LoadFromDatabase($field, 'FieldName');
	$tmp_values = $tmp->Get('ValueList');
	unset($tmp);
	$tmp_values = explode(',', $tmp_values);

	foreach($tmp_values as $mixed)
	{
		$elem = explode('=', trim($mixed));
		$ret[ $elem[0] ] = $elem[1];
	}
	return $ret;
}

function ResetPage($module_prefix, $page_variable = 'p')
{
	// resets page in specific module when category is changed
	global $objSession;
	if( !is_object($objSession) ) // when changing pages session doesn't exist -> InPortal BUG
	{
		global $var_list, $SessionQueryString, $FrontEnd;
		$objSession = new clsUserSession($var_list["sid"],($SessionQueryString && $FrontEnd==1));
	}

	$last_cat = $objSession->GetVariable('last_category');
	$prev_cat = $objSession->GetVariable('prev_category');
	//echo "Resetting Page [$prev_cat] -> [$last_cat]<br>";

	if($prev_cat != $last_cat) $GLOBALS[$module_prefix.'_var_list'][$page_variable] = 1;
}

if( !function_exists('GetVar') )
{
	/**
	* @return string
	* @param string $name
	* @param bool $post_priority
	* @desc Get's variable from http query
	*/
	function GetVar($name, $post_priority = false)
	{
		if(!$post_priority) // follow gpc_order in php.ini
			return isset($_REQUEST[$name]) ? $_REQUEST[$name] : false;
		else	// get variable from post 1stly if not found then from get
			return isset($_POST[$name]) && $_POST[$name] !== false ? $_POST[$name] : ( isset($_GET[$name]) && $_GET[$name] ? $_GET[$name] : false );
	}
}

function SetVar($VarName, $VarValue)
{
	$_REQUEST[$VarName] = $VarValue;
	$_POST[$VarName] = $VarValue;
	$_GET[$VarName] = $VarValue;
}

function PassVar(&$source)
{
	// source array + any count of key names in passed array
	$params = func_get_args();
	array_shift($params);

	if( count($params) )
	{
		$ret = Array();
		foreach($params as $var_name)
			if( isset($source[$var_name]) )
				$ret[] = $var_name.'='.$source[$var_name];
		$ret = '&'.implode('&', $ret);
	}
	return $ret;
}

function GetSubmitVariable(&$array, $postfix)
{
	// gets edit status of module
	// used in case if some modules share
	// common action parsed by kernel parser,
	// but each module uses own EditStatus variable

	$modules = Array('In-Link' => 'Link', 'In-News' => 'News', 'In-Bulletin' => 'Topic', 'In-Portal'=>'Review');
	foreach($modules as $module => $prefix)
		if( isset($array[$prefix.$postfix]) )
			return Array('Module' => $module, 'variable' => $array[$prefix.$postfix]);
	return false;
}

function GetModuleByAction()
{
	$prefix2module = Array('m' => 'In-Portal', 'l' => 'In-Link', 'n' => 'In-News', 'bb' => 'In-Bulletin');
	$action = GetVar('Action');
	if($action)
	{
		$module_prefix = explode('_', $action);
		return $prefix2module[ $module_prefix[0] ];
	}
	else
		return false;
}

function dir_size($dir) {
   // calculates folder size based on filesizes inside it (recursively)
   $totalsize=0;
   if ($dirstream = @opendir($dir)) {
       while (false !== ($filename = readdir($dirstream))) {
           if ($filename!="." && $filename!="..")
           {
               if (is_file($dir."/".$filename))
                   $totalsize+=filesize($dir."/".$filename);

               if (is_dir($dir."/".$filename))
                   $totalsize+=dir_size($dir."/".$filename);
           }
       }
   }
   closedir($dirstream);
   return $totalsize;
}

function size($bytes) {
  // shows formatted file/directory size
  $types =  Array("la_bytes","la_kilobytes","la_megabytes","la_gigabytes","la_terabytes");
   $current = 0;
  while ($bytes > 1024) {
   $current++;
   $bytes /= 1024;
  }
  return round($bytes,2)." ".language($types[$current]);
}

function echod($str)
{
	// echo debug output
	echo str_replace( Array('[',']'), Array('[<b>', '</b>]'), $str).'<br>';
}


function PrepareParams($source, $to_lower, $mapping)
{
	// prepare array with form values to use with item
	$result = Array();
	foreach($to_lower as $field)
		$result[ $field ] = $source[ strtolower($field) ];

	if( is_array($mapping) )
	{
		foreach($mapping as $field_from => $field_to)
			$result[$field_to] = $source[$field_from];
	}

	return $result;
}

function GetELT($field, $phrases = Array())
{
	// returns FieldOptions equivalent in In-Portal
	$ret = Array();
	foreach($phrases as $phrase)
		$ret[] = admin_language($phrase);
	$ret = "'".implode("','", $ret)."'";
	return 'ELT('.$field.','.$ret.')';
}

function GetModuleImgPath($module)
{
	global $rootURL, $admin;
	return $rootURL.$module.'/'.$admin.'/images';
}

function ActionPostProcess($StatusField, $ListClass, $ListObjectName = '', $IDField = null)
{
	// each action postprocessing stuff from admin
	if( !isset($_REQUEST[$StatusField]) ) return false;

	$list =& $GLOBALS[$ListObjectName];
	if( !is_object($list) ) $list = new $ListClass();
	$SFValue = $_REQUEST[$StatusField]; // status field value
 	switch($SFValue)
	{
 		case 1: // User hit "Save" button
    		$list->CopyFromEditTable($IDField);
    		break;
		case 2: // User hit "Cancel" button
			$list->PurgeEditTable($IDField);
			break;
 	}
	if( function_exists('SpecificProcessing') ) SpecificProcessing($StatusField, $SFValue);
 	if($SFValue == 1 || $SFValue == 2) $list->Clear();
}

if( !function_exists('getArrayValue') )
{
	/**
	 * Returns array value if key exists
	 *
	 * @param Array $array searchable array
	 * @param int $key array key
	 * @return string
	 * @access public
	 */
	//
	function getArrayValue(&$array,$key)
	{
		$ret = isset($array[$key]) ? $array[$key] : false;
		if ($ret && func_num_args() > 2) {
			for ($i = 2; $i < func_num_args(); $i++) {
				$cur_key = func_get_arg($i);
				$ret = getArrayValue( $ret, $cur_key );
				if ($ret === false) break;
			}
		}
		return $ret;
	}
}
function MakeHTMLTag($element, $attrib_prefix)
{
	$result = Array();
	$ap_length = strlen($attrib_prefix);
	foreach($element->attributes as $attib_name => $attr_value)
		if( substr($attib_name, $ap_length) == $ap_length )
			$result[] = substr($attib_name, $ap_length, strlen($attib_name)).'="'.$attr_value.'"';
	return count($result) ? implode(' ', $result) : false;
}

function GetImportScripts()
{
	// return currently installed import scripts
	static $import_scripts = Array();
	if( count($import_scripts) == 0 )
	{
		
		$sql = 'SELECT imp.* , m.LoadOrder
				FROM '.TABLE_PREFIX.'ImportScripts imp
				LEFT JOIN '.TABLE_PREFIX.'Modules m ON m.Name = imp.is_Module
				ORDER BY m.LoadOrder';
		
		$db =& GetADODBConnection();
		$rs = $db->Execute($sql);
		if ($rs && $rs->RecordCount() > 0) {
			while (!$rs->EOF) {
				$rec =& $rs->fields;
				$import_scripts[ $rec['is_id'] ] = Array(	'label' => $rec['is_label'], 'url' => $rec['is_script'],
											'enabled' => $rec['is_enabled'], 'field_prefix' => $rec['is_field_prefix'],
											'id' => $rec['is_string_id'], 'required_fields' => $rec['is_requred_fields'],
											'module' => strtolower($rec['is_Module']) );
				$rs->MoveNext();
			}
		}
		else {
			$import_scripts = Array();
		}
	}
	return $import_scripts;
}

function GetImportScript($id)
{
	$scripts = GetImportScripts();
	return isset($scripts[$id]) ? $scripts[$id] : false;
}
function GetNextTemplate($current_template)
{
	// used on front, returns next template to make
	// redirect to
	$dest = GetVar('dest', true);
	if(!$dest) $dest = GetVar('DestTemplate', true);
	return $dest ? $dest : $current_template;
}


// functions for dealign with enviroment variable construction
function GenerateModuleEnv($prefix, $var_list)
{
	// globalize module varible arrays
	$main =& $GLOBALS[$prefix.'_var_list'];
	$update =& $GLOBALS[$prefix.'_var_list_update'];
	//echo "VAR: [$main]; VAR_UPDATE: [$update]<br>";
	
	// if update var count is zero, then do nothing
	if( !is_array($update) || count($update) == 0 ) return '';
	
	// ensure that we have no empty values in enviroment variable
	foreach($update as $vl_key => $vl_value) {
    	if(!$vl_value) $update[$vl_key] = '0'; // unset($update[$vl_key]);
	}

  	foreach($main as $vl_key => $vl_value) {
    	if(!$vl_value) $main[$vl_key] = '0'; // unset($main[$vl_key]);
  	}
    
	$ret = Array();
	foreach($var_list as $var_name) {
		$value = GetEnvVar($prefix, $var_name);
		if(!$value && $var_name == 'id') $value = '0';
		$ret[] = $value;
	}

	// Removing all var_list_udpate
	$keys = array_keys($update);
	foreach ($keys as $key) {
		unset($update[$key]);
	}
	
	return ':'.$prefix.implode('-',$ret);
}

// functions for dealign with enviroment variable construction
function GenerateModuleEnv_NEW($prefix, $var_list)
{ 
	// globalize module varible arrays
	$main =& $GLOBALS[$prefix.'_var_list'];
	$update =& $GLOBALS[$prefix.'_var_list_update'];
	//echo "VAR: [$main]; VAR_UPDATE: [$update]<br>";
	
	if ( isset($update) && $update )
	{
		// ensure that we have no empty values in enviroment variable
		foreach($update as $vl_key => $vl_value) {
	    	if(!$vl_value) $update[$vl_key] = '0'; // unset($update[$vl_key]);
		}
		
		$app =& kApplication::Instance();
		$passed = $app->GetVar('prefixes_passed');
		$passed[] = $prefix;
		$app->SetVar('prefixes_passed', $passed);
	}
	else
	{
		return Array();
	}
	
	if ($main) {
		foreach($main as $vl_key => $vl_value) {
    		if(!$vl_value) $main[$vl_key] = '0'; // unset($main[$vl_key]);
  		}
	}
    
	$ret = Array();
	foreach($var_list as $src_name => $dst_name) {
		$ret[$dst_name] = GetEnvVar($prefix, $src_name);
	}

	// Removing all var_list_udpate
	if ( isset($update) && $update )
	{
		$keys = array_keys($update);
		foreach ($keys as $key) unset($update[$key]);
	}
	return $ret;
}

function GetEnvVar($prefix, $name)
{
	// get variable from template variable's list
	// (used in module parsers to build env string)
	$main =& $GLOBALS[$prefix.'_var_list'];
	$update =& $GLOBALS[$prefix.'_var_list_update'];

	return isset($update[$name]) ? $update[$name] : ( isset($main[$name]) ? $main[$name] : '');
}

/**
 * Checks if debug mode is active
 *
 * @return bool
 */
function IsDebugMode($check_debugger = true)
{
	$application =& kApplication::Instance();
	return $application->isDebugMode($check_debugger);
}

/**
 * Checks if we are in admin
 *
 * @return bool
 */
function IsAdmin()
{
	$application =& kApplication::Instance();
	return $application->IsAdmin();
}

/**
 * Two strings in-case-sensitive compare.
 * Returns >0, when string1 > string2,
 *         <0, when string1 > string2,
 *          0, when string1 = string2
 *
 * @param string $string1
 * @param string $string2
 * @return int
 */
function stricmp ($string1, $string2) {
	return strcmp(strtolower($string1), strtolower($string2));
}

/**
 * Generates unique code
 *
 * @return string
 */
function GenerateCode()
{
	list($usec, $sec) = explode(" ",microtime());

	$id_part_1 = substr($usec, 4, 4);
	$id_part_2 = mt_rand(1,9);
	$id_part_3 = substr($sec, 6, 4);
	$digit_one = substr($id_part_1, 0, 1);
	if ($digit_one == 0) {
		$digit_one = mt_rand(1,9);
		$id_part_1 = ereg_replace("^0","",$id_part_1);
		$id_part_1=$digit_one.$id_part_1;
	}
	return $id_part_1.$id_part_2.$id_part_3;
}

function bracket_comp($elem1, $elem2)
{
	if( ($elem1['End']>$elem2['End'] || $elem1['End'] == -1) && $elem2['End'] != -1 )
	{
		return 1;
	}
	elseif ( ($elem1['End']<$elem2['End'] || $elem2['End'] == -1) && $elem1['End'] != -1 )
	{
		return -1;
	}
	else
	{
		return 0;
	}
}

function bracket_id_sort($first_id, $second_id)
{
	$first_abs = abs($first_id);
	$second_abs = abs($second_id);
	$first_sign = ($first_id == 0) ? 0 : $first_id / $first_abs;
	$second_sign = ($second_id == 0) ? 0 : $second_id / $second_abs;
	if($first_sign != $second_sign)
	{
		if($first_id > $second_id) {
			$bigger =& $first_abs;
			$smaller =& $second_abs;
		}
		else {
			$bigger =& $second_abs;
			$smaller =& $first_abs;
		}
		$smaller = $bigger + $smaller;
	}

	if($first_abs > $second_abs) {
		return 1;
	}
	elseif ($first_abs < $second_abs)
	{
		return -1;
	}
	else
	{
		return 0;
	}
}

function pr_bracket_comp($elem1, $elem2)
{

	if ($elem1['MinQty']!="" && $elem1['MaxQty']=="" && $elem2['MinQty']!="" && $elem2['MaxQty']!="")	return 1;
	if ($elem1['MinQty']!="" && $elem1['MaxQty']=="" && $elem2['MinQty']=="" && $elem2['MaxQty']=="")	return -1;


	if ($elem1['MaxQty']=="" && $elem2['MaxQty']!="")	return 1;
	if ($elem1['MaxQty']!="" && $elem2['MaxQty']=="")	return -1;


	if( ($elem1['MaxQty']>$elem2['MaxQty'] && $elem2['MaxQty']!=-1) || ($elem1['MaxQty'] == -1 && $elem2['MaxQty'] != -1 ))
	{
		return 1;
	}
	elseif ( ($elem1['MaxQty']<$elem2['MaxQty']) || ($elem2['MaxQty'] == -1 && $elem1['MaxQty'] != -1 ))
	{
		return -1;
	}
	else
	{
		return 0;
	}
}

function ap_bracket_comp($elem1, $elem2)
{

	if ($elem1['FromAmount']!="" && $elem1['ToAmount']=="" && $elem2['FromAmount']!="" && $elem2['ToAmount']!="")	return 1;
	if ($elem1['FromAmount']!="" && $elem1['ToAmount']=="" && $elem2['FromAmount']=="" && $elem2['ToAmount']=="")	return -1;


	if ($elem1['ToAmount']=="" && $elem2['ToAmount']!="")	return 1;
	if ($elem1['ToAmount']!="" && $elem2['ToAmount']=="")	return -1;


	if( ($elem1['ToAmount']>$elem2['ToAmount'] && $elem2['ToAmount']!=-1) || ($elem1['ToAmount'] == -1 && $elem2['ToAmount'] != -1 ))
	{
		return 1;
	}
	elseif ( ($elem1['ToAmount']<$elem2['ToAmount']) || ($elem2['ToAmount'] == -1 && $elem1['ToAmount'] != -1 ))
	{
		return -1;
	}
	else
	{
		return 0;
	}
}

function pr_bracket_id_sort($first_id, $second_id)
{
	$first_abs = abs($first_id);
	$second_abs = abs($second_id);
	$first_sign = ($first_id == 0) ? 0 : $first_id / $first_abs;
	$second_sign = ($second_id == 0) ? 0 : $second_id / $second_abs;
	if($first_sign != $second_sign)
	{
		if($first_id > $second_id) {
			$bigger =& $first_abs;
			$smaller =& $second_abs;
		}
		else {
			$bigger =& $second_abs;
			$smaller =& $first_abs;
		}
		$smaller = $bigger + $smaller;
	}

	if($first_abs > $second_abs) {
		return 1;
	}
	elseif ($first_abs < $second_abs)
	{
		return -1;
	}
	else
	{
		return 0;
	}
}

	function inp_htmlize($var, $strip = 0)
	{
		if( is_array($var) )
		{
			foreach($var as $k => $v) $var[$k] = inp_htmlize($v, $strip);
		}
		else
		{
			$var = htmlspecialchars($strip ? stripslashes($var) : $var);
		}
		return $var;
	}

	/**
	 * Sets in-portal cookies, that will not harm K4 to breath free :)
	 *
	 * @param string $name
	 * @param mixed $value
	 * @param int $expire
	 * @author Alex
	 */
	function set_cookie($name, $value, $expire = 0, $cookie_path = null)
	{
		if (!isset($cookie_path))
		{
			$cookie_path = IsAdmin() ? rtrim(BASE_PATH, '/').'/admin' : BASE_PATH;
		}
		setcookie($name, $value, $expire, $cookie_path, $_SERVER['HTTP_HOST']);
	}

	/**
	 * If we are on login required template, but we are not logged in, then logout user
	 *
	 * @return bool
	 */
	function require_login($condition = null, $redirect_params = 'logout=1', $pass_env = false)
	{
		if( !isset($condition) ) $condition = !admin_login();
		if(!$condition) return false;

		global $objSession, $adminURL;
	    if( !headers_sent() ) set_cookie(SESSION_COOKIE_NAME, ' ', adodb_mktime() - 3600);
	    $objSession->Logout();
	    if($pass_env) $redirect_params = 'env='.BuildEnv().'&'.$redirect_params;
	    header('Location: '.$adminURL.'/index.php?'.$redirect_params);
	    exit;
	}

	if( !function_exists('safeDefine') )
	{
		/**
		 * Define constant if it was not already defined before
		 *
		 * @param string $const_name
		 * @param string $const_value
		 * @access public
		 */
		function safeDefine($const_name, $const_value)
		{
			if(!defined($const_name)) define($const_name,$const_value);
		}
	}
	
	/**
	 * Builds up K4 url from data supplied by in-portal
	 *
	 * @param string $t template
	 * @param Array $params
	 * @param string $index_file
	 * @return string
	 */
	function HREF_Wrapper($t = '', $params = null, $index_file = null)
	{
		$url_params = BuildEnv_NEW();
		if( isset($params) ) $url_params = array_merge_recursive2($url_params, $params);
		if(!$t)
		{
			$t = $url_params['t'];
			unset($url_params['t']);
		}
		$app =& kApplication::Instance();
		return $app->HREF($t, '', $url_params, $index_file);
	}
	
	/**
	 * Set url params based on tag params & mapping hash passed
	 *
	 * @param Array $url_params - url params before change
	 * @param Array $tag_attribs - tag attributes
	 * @param Array $params_map key - tag_param, value - url_param
	 */
	function MapTagParams(&$url_params, $tag_attribs, $params_map)
	{
		foreach ($params_map as $tag_param => $url_param)
        {
        	if( getArrayValue($tag_attribs, $tag_param) ) $url_params[$url_param] = $tag_attribs[$tag_param];
        }
	}
	
	function ExtractParams($params_str, $separator = '&')
	{
    	if(!$params_str) return Array();
    	
    	$ret = Array();
		$parts = explode($separator, trim($params_str, $separator) );
    	foreach ($parts as $part)
    	{
    		list($var_name, $var_value) = explode('=', $part);
    		$ret[$var_name] = $var_value;
    	}
    	return $ret;
	}
	
	if( !function_exists('constOn') )
	{
		/**
		 * Checks if constant is defined and has positive value
		 *
		 * @param string $const_name
		 * @return bool
		 */
		function constOn($const_name)
		{
			return defined($const_name) && constant($const_name);
		}
	}
	
	function &recallObject($var_name, $class_name)
	{
		if (!isset($GLOBALS[$var_name]) || !is_object($GLOBALS[$var_name]))
		{
			$GLOBALS[$var_name] = new $class_name();
		}
		return $GLOBALS[$var_name];
	}
	
	/**
	 * Returns true in case of AM/PM time
	 *
	 * @return bool
	 */
	function is12HourMode()
	{
		return preg_match('/(a|A)/', GetTimeFormat() );
	}

?>