<?php

class SiteLibs {

	function SiteLibs() {
		
	}

	function redirect($VarRefreshPage, $VarRefreshTime = 1){
		echo "<meta http-equiv='REFRESH' content='". $VarRefreshTime ."; URL=". $VarRefreshPage ."'>";
		return true;
	}

	function GetVarDump($Arr, $VarDisplayMode = 'HTML4_Text'){
		require_once('Var_Dump.php');
		Var_Dump::displayInit(array('display_mode' => $VarDisplayMode));
		Var_Dump::display($Arr);
	}

	function GetFileExt($VarFile = ''){
		if('' != $VarFile){
			return substr($VarFile,strrpos($VarFile,'.'));
		}
		else {
			return false;
		}
	}

  function GetFileStripExt($VarFile = ''){
		if('' != $VarFile){
			return substr($VarFile, 0, strrpos($VarFile,'.'));
		}
		else {
			return false;
		}
	}

  function ConvertInBytes($val = '') {
    if ('' != $val){
      $val = trim($val);
      $last = strtolower($val{strlen($val)-1});
      switch($last) {
          case 'g':
              $val *= 1024;
          case 'm':
              $val *= 1024;
          case 'k':
              $val *= 1024;
      }
      return $val;
    }
    else{
      return false;
    }
  }
  
  function ConvertSizeToStr($size = 0, $ArrLang){
    $kb = 1024;
    $mb = 1024 * $kb;
    $gb = 1024 * $mb;
    $tb = 1024 * $gb;

    if ($size < $kb) {
      return $size .' '. $ArrLang['b'];
    }
    else if ($size < $mb) {
      return round($size / $kb, 2) .' '. $ArrLang['kb'];
    }
    else if ($size < $gb) {
      return round($size / $mb, 2) .' '. $ArrLang['mb'];
    }
    else if ($size < $tb) {
      return round($size / $gb, 2) .' '. $ArrLang['gb'];
    }
    else {
      return round($size / $tb, 2) .' '. $ArrLang['tb'];
    }
  }

  function toUpper($content) {
    return strtr($content,
    "abcdefghijklmnopqrstuvwxyz".
    "\xE0\xE1\xE2\xE3\xE4\xE5".
    "\xb8\xe6\xe7\xe8\xe9\xea".
    "\xeb\xeC\xeD\xeE\xeF\xf0".
    "\xf1\xf2\xf3\xf4\xf5\xf6".
    "\xf7\xf8\xf9\xfA\xfB\xfC".
    "\xfD\xfE\xfF",
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
    "\xC0\xC1\xC2\xC3\xC4\xC5".
    "\xA8\xC6\xC7\xC8\xC9\xCA".
    "\xCB\xCC\xCD\xCE\xCF\xD0".
    "\xD1\xD2\xD3\xD4\xD5\xD6".
    "\xD7\xD8\xD9\xDA\xDB\xDC".
    "\xDD\xDE\xDF");
  }

  function RuleCheckSqlTextDataField($VarValue){
    if (preg_match('/^[0-9,\/\\\.-]+$/', $VarValue) && (8 == strlen($VarValue) || 10 == strlen($VarValue))) {
      return true;
    }
    return false;
  }

  function RuleCheckSqlTextField($VarValue){
    if (preg_match('/^[a-zA-Z�������������������������������������Ũ��������������������������0-9,;()\/\\\._-\s&|]+$/', $VarValue)) {
      return true;
    }
    return false;
  }

  function RuleCheckSqlPasswordField($VarValue){
    //$zzz = preg_match('/^[a-zA-Z0-9\._-\s]+$/', $VarValue);
    //echo "zzz: ". $zzz ."<br />";
    //echo "VarValue: ". $VarValue ."<br />";
    if (preg_match('/^[a-zA-Z0-9\._-]+$/', $VarValue)) {
      return true;
    }
    return false;
  }

  function RuleCaptcha($VarValue){
    //echo "RuleVarValue: ". $VarValue ."<br />";
    //echo "Rule_SESSION['SiteAuthReg']['CaptchaPhrase']: ". $_SESSION['SiteAuthReg']['CaptchaPhrase'] ."<br />";
    //echo "Rule_SESSION['SiteAuthReg']['CaptchaPhrasePrev']: ". $_SESSION['SiteAuthReg']['CaptchaPhrasePrev'] ."<br />";
    if ($_SESSION['SiteAuthReg']['CaptchaPhrasePrev'] == $VarValue) {
      return true;
    }
    return false;
  }

//  function BuildSqlFromArray($ArrSqlArray = ''){
//    if (true === is_array($ArrSqlArray) && '' != @$ArrSqlArray['select'] && '' != @$ArrSqlArray['from']){
//      $VarSql = 'SELECT '. $ArrSqlArray['select'];
//      $VarSql .= ' FROM '. $ArrSqlArray['from'];
//      if('' != $ArrSqlArray['leftjoin']){
//        $VarSql .= ' LEFT JOIN '. $ArrSqlArray['leftjoin'];
//      }
//      if('' != $ArrSqlArray['rightjoin']){
//        $VarSql .= ' RIGHT JOIN '. $ArrSqlArray['rightjoin'];
//      }
//      if('' != $ArrSqlArray['where']){
//        $VarSql .= ' WHERE '. SiteLibs::StripAndOrFirst($ArrSqlArray['where']);
//      }
//      if('' != $ArrSqlArray['group']){
//        $VarSql .= ' GROUP BY '. $ArrSqlArray['group'];
//      }
//      if('' != $ArrSqlArray['order']){
//        $VarSql .= ' ORDER BY '. $ArrSqlArray['order'];
//      }
//      if('' != $ArrSqlArray['limit']){
//        $VarSql .= ' LIMIT '. $ArrSqlArray['limit'];
//      }
//      return $VarSql;
//    }
//    else{
//      return false;
//    }
//  }

  function BuildSqlFromArray($ArrSqlArray = ''){
    if (true === is_array($ArrSqlArray) && '' != @$ArrSqlArray['select'] && '' != @$ArrSqlArray['from'] && (false === isset($ArrSqlArray['query']) || '' == @$ArrSqlArray['query'])){
      $VarSql = 'SELECT '. $ArrSqlArray['select'];
      $VarSql .= ' FROM '. $ArrSqlArray['from'];
      if(true === isset($ArrSqlArray['leftjoin']) && '' != $ArrSqlArray['leftjoin']){
        $VarSql .= ' LEFT JOIN '. $ArrSqlArray['leftjoin'];
      }
      if(true === isset($ArrSqlArray['rightjoin']) && '' != $ArrSqlArray['rightjoin']){
        $VarSql .= ' RIGHT JOIN '. $ArrSqlArray['rightjoin'];
      }
      if(true === isset($ArrSqlArray['where']) && '' != $ArrSqlArray['where']){
        $VarSql .= ' WHERE '. SiteLibs::StripAndOrFirst($ArrSqlArray['where']);
      }
      if(true === isset($ArrSqlArray['group']) && '' != $ArrSqlArray['group']){
        $VarSql .= ' GROUP BY '. $ArrSqlArray['group'];
      }
      if(true === isset($ArrSqlArray['order']) && '' != $ArrSqlArray['order']){
        $VarSql .= ' ORDER BY '. $ArrSqlArray['order'];
      }
      if(true === isset($ArrSqlArray['limit']) && '' != $ArrSqlArray['limit']){
        $VarSql .= ' LIMIT '. $ArrSqlArray['limit'];


//        SELECT top 20 * FROM [some_table] WHERE [primary_key_field] NOT IN
//        (
//        SELECT top 10 [primary_key_field] FROM [some_table] ORDER BY [primary_key_field]
//        )
//        ORDER BY [primary_key_field]

      }
      return $VarSql;
    }
    elseif (true === is_array($ArrSqlArray) && true === isset($ArrSqlArray['query']) && '' != @$ArrSqlArray['query']){
      if('' != $ArrSqlArray['query']){
        $VarSql = $ArrSqlArray['query'];
      }
      return $VarSql;
    }
    else{
      return false;
    }
  }

  function ConvertStringToSql($VarFieldName = '', $VarFieldValue = '', $VarFieldUnion = 'AND'){
    if ('' != $VarFieldName && '' != $VarFieldValue){
      $VarFieldName = 'UPPER('. $VarFieldName .')';
      $VarReturn = strtoupper($VarFieldValue);
      //$VarReturn = SiteLibs::toUpper($VarFieldValue);
      $VarReturn = preg_replace('/\s+/', ' ', $VarReturn);
      $VarReturn = preg_replace('/ &&+ /', '&&', $VarReturn);
      $VarReturn = preg_replace('/ \|\|+ /', '||', $VarReturn);
      $VarReturn = preg_replace('/ /', '&&', $VarReturn);
      $VarReturn = preg_replace('/&&/', "%') AND ". $VarFieldName ." LIKE ('%", $VarReturn);
      $VarReturn = preg_replace('/\|\|/', "%') OR ". $VarFieldName ." LIKE ('%", $VarReturn);
      $VarReturn = " ". $VarFieldUnion ." (". $VarFieldName ." LIKE ('%" . $VarReturn . "%'))";
      //echo "VarReturn: ". $VarReturn ."<br />";
      return $VarReturn;
    }
    else {
      return false;
    }
  }

  function ConvertStringToSqlNoFirstProcent($VarFieldName = '', $VarFieldValue = '', $VarFieldUnion = 'AND'){
    if ('' != $VarFieldName && '' != $VarFieldValue){
      $VarFieldName = 'UPPER('. $VarFieldName .')';
      $VarReturn = strtoupper($VarFieldValue);
      $VarReturn = SiteLibs::toUpper($VarFieldValue);
      $VarReturn = preg_replace('/\s+/', ' ', $VarReturn);
      $VarReturn = preg_replace('/ &&+ /', '&&', $VarReturn);
      $VarReturn = preg_replace('/ \|\|+ /', '||', $VarReturn);
      $VarReturn = preg_replace('/ /', '&&', $VarReturn);
      $VarReturn = preg_replace('/&&/', "%') AND ". $VarFieldName ." LIKE ('", $VarReturn);
      $VarReturn = preg_replace('/\|\|/', "%') OR ". $VarFieldName ." LIKE ('", $VarReturn);
      $VarReturn = " ". $VarFieldUnion ." (". $VarFieldName ." LIKE ('" . $VarReturn . "%'))";
      return $VarReturn;
    }
    else {
      return false;
    }
  }

  function ParceDateElement($VarDateElement = array('d' => 0, 'M' => 0, 'Y' => '0')){
    if (0 != $VarDateElement['Y']){
      if ('0' == $VarDateElement['d']){
        $VarDateElement['d'] = '01';
      }
      if (1 == strlen($VarDateElement['d'])){
        $VarDateElement['d'] = '0'. $VarDateElement['d'];
      }
      if ('0' == $VarDateElement['M']){
        $VarDateElement['M'] = '01';
      }
      if (1 == strlen($VarDateElement['M'])){
        $VarDateElement['M'] = '0'. $VarDateElement['M'];
      }
      return $VarDateElement;
    }
    else {
      return '';
    }
  }

  function ParceTextDateElement($VarDateElement = '', $VarLang = 'ru'){
    if ('' != $VarDateElement){
      switch ($VarLang) {
        case 'ru':
          $ArrDateElementTemp = explode(".", $VarDateElement);
          $ArrDateElement['d'] = $ArrDateElementTemp[0];
          $ArrDateElement['M'] = $ArrDateElementTemp[1];
          $ArrDateElement['Y'] = $ArrDateElementTemp[2];
          break;
        case 'en':
          $ArrDateElementTemp = explode(".", $VarDateElement);
          $ArrDateElement['d'] = $ArrDateElementTemp[0];
          $ArrDateElement['M'] = $ArrDateElementTemp[1];
          $ArrDateElement['Y'] = $ArrDateElementTemp[2];
          break;
      }
      if (true === is_numeric($ArrDateElement['d']) && true === is_numeric($ArrDateElement['M']) && true === is_numeric($ArrDateElement['Y'])){
        return $ArrDateElement;
      }
      else{
        return false;
      }
    }
    else {
      return '';
    }
  }

  function ConvertTextDateToSql($VarFieldName = '', $VarFieldValueB = '', $VarFieldValueE = '', $VarFieldUnion = 'AND'){
    $VarReturn = '';
    $VarFieldValueB = SiteLibs::ParceTextDateElement($VarFieldValueB);
    $VarFieldValueE = SiteLibs::ParceTextDateElement($VarFieldValueE);
    if ('' != $VarFieldName){
      if (true === is_array($VarFieldValueB)){
        $VarReturn .= " ". $VarFieldUnion ." ". $VarFieldName ." >= '". $VarFieldValueB['Y'] ."-". $VarFieldValueB['M'] ."-". $VarFieldValueB['d'] ."'";
      }
      if (true === is_array($VarFieldValueE)){
        $VarReturn .= " ". $VarFieldUnion ." ". $VarFieldName ." <= '". $VarFieldValueE['Y'] ."-". $VarFieldValueE['M'] ."-". $VarFieldValueE['d'] ."'";
      }
      return $VarReturn;
    }
    else {
      return $VarReturn;
    }
  }
  
  function ConvertSqlDateToDb($VarSqlDateValue = ''){
    $VarReturn = '';
    if ('' != $VarSqlDateValue){
      $VarReturn = date("Ymd", strtotime($VarSqlDateValue));
    }
    else{
      $VarReturn = $VarSqlDateValue;
    }
    return $VarReturn;
  }
  
  function ConvertSqlDateInsert($VarSqlDateValue = ''){
    if ('' != $VarSqlDateValue){
      //echo "VarSqlDateValue: ". $VarSqlDateValue ."<br />";
      $VarSqlDateValue = date("Y-m-d", strtotime($VarSqlDateValue));
    }
//    else{
//      $VarSqlDateValue = '';
//    }
    return $VarSqlDateValue;
  }
  
  function ConvertSqlDatetimeInsert($VarSqlDateValue = ''){
    if ('' != $VarSqlDateValue){
      //echo "VarSqlDateValue: ". $VarSqlDateValue ."<br />";
      $VarSqlDateValue = date("Y-m-d H:i:s", strtotime($VarSqlDateValue));
    }
//    else{
//      $VarSqlDateValue = '';
//    }
    return $VarSqlDateValue;
  }

  function ConvertSqlDateToText($VarSqlDateValue = ''){
    $VarReturn = '';
    if ('' != $VarSqlDateValue){
      $VarReturn = date("d.m.Y", strtotime($VarSqlDateValue));
    }
    else{
      $VarReturn = $VarSqlDateValue;
    }
    return $VarReturn;
  }
  
  function ConvertSqlDatetimeToText($VarSqlDateValue = ''){
    $VarReturn = '';
    if ('' != $VarSqlDateValue){
      $VarReturn = date("d.m.Y H:i:s", strtotime($VarSqlDateValue));
    }
    else{
      $VarReturn = $VarSqlDateValue;
    }
    return $VarReturn;
  }

  function ConvertDateToSql($VarFieldName = '', $VarFieldValueB = '', $VarFieldValueE = '', $VarFieldUnion = 'AND'){
    $VarReturn = '';
    if ('' != $VarFieldName && (0 != $VarFieldValueB['Y'] || 0 != $VarFieldValueE['Y'])){
      $VarFieldValueB = SiteLibs::ParceDateElement($VarFieldValueB);
      $VarFieldValueE = SiteLibs::ParceDateElement($VarFieldValueE);
      if ('' != $VarFieldValueB){
        $VarReturn .= " ". $VarFieldUnion ." ". $VarFieldName ." >= '". $VarFieldValueB['Y'] ."-". $VarFieldValueB['M'] ."-". $VarFieldValueB['d'] ."'";
      }
      if ('' != $VarFieldValueE){
        $VarReturn .= " ". $VarFieldUnion ." ". $VarFieldName ." <= '". $VarFieldValueE['Y'] ."-". $VarFieldValueE['M'] ."-". $VarFieldValueE['d'] ."'";
      }
      //echo "VarReturn: ". $VarReturn ."<br />";
      return $VarReturn;
    }
    else {
      return $VarReturn;
    }
  }

  function ConvertCheckboxToSql($VarFieldName = '', $VarFieldValue = '', $VarFieldUnion = 'AND'){
    if ('' != $VarFieldName && true === is_array($VarFieldValue)){
      $VarReturn = '';
      foreach ($VarFieldValue AS $k => $v){
        if (0 < $v){
          if ('' == $VarReturn){
            $VarReturn .= $k;
          }
          else {
            $VarReturn .= ', '. $k;
          }
        }
      }
      if ('' != $VarReturn){
        $VarReturn = " ". $VarFieldUnion ." (". $VarFieldName ." IN (". $VarReturn ."))";
        return $VarReturn;
      }
      else {
        return false;
      }
    }
    else {
      return false;
    }
  }
  
  function ConvertSqlIntegerInsert($VarInt = ''){
    if(true === is_numeric($VarInt)){
      return $VarInt;
    }
  }

  function StripAndOrFirst($VarSqlAdd = ''){
    if ('' != $VarSqlAdd){
      $VarSqlAdd = preg_replace('/^ AND /', '', $VarSqlAdd);
      $VarSqlAdd = preg_replace('/^ OR /', '', $VarSqlAdd);
      return $VarSqlAdd;
    }
    else {
      return '';
    }
  }

  function StripBadSymbol($VarValue = ''){
    if ('' != $VarValue){
      $VarValue = trim($VarValue);
      $VarOrder = array("\r\n", "\n", "\r");
      $VarValue = str_replace($VarOrder, '<br />', $VarValue);
      return $VarValue;
    }
    else {
      return '';
    }
  }

//  function ConvertBBCode($VarText = '', $VarCommand = ''){
//    require_once('PEAR.php');
//    require_once('HTML/BBCodeParser.php');
//
//    /* get options from the ini file */
//    $config = parse_ini_file($_SERVER['DOCUMENT_ROOT'] .'/../script/BBCodeParser.ini', true);
//    //SiteLibs::GetVarDump($config);
//    $options = &PEAR::getStaticProperty('HTML_BBCodeParser', '_options');
//    $options = $config['HTML_BBCodeParser'];
//    unset($options);
//
//    /* do yer stuff! */
//    $parser = new HTML_BBCodeParser();
//    $parser->setText(@$VarText);
//    $parser->parse();
//    $VarReturn = $parser->getParsed();
//    if ('' != $VarCommand){
//      $VarReturn = $VarCommand($VarReturn);
//    }
//    return $VarReturn;
//  }

  function addcslashes($VarString = ''){
    if('' != $VarString){
      return addcslashes($VarString, "\\\"\n\r");
    }
    else{
      return '';
    }
  }

  function ConvertArrayIconv(&$item1, $key, $VarCharset = 'windows-1251'){
    if ('utf-8' != strtolower($VarCharset)){
      if (true === is_array($item1)){
        array_walk($item1, 'SiteLibs::ConvertArrayIconv', $VarCharset);
      }
      else{
        $item1 = iconv("utf-8", $VarCharset, $item1);
        return $item1;
      }
    }
    else{
      return $item1;
    }
  }
  
  function ConvertArrayIconvBack(&$item1, $key, $VarCharset = 'windows-1251'){
    if ('utf-8' != strtolower($VarCharset)){
      if (true === is_array($item1)){
        array_walk($item1, 'SiteLibs::ConvertArrayIconvBack', $VarCharset);
      }
      else{
        $item1 = iconv($VarCharset, "utf-8", $item1);
        return $item1;
      }
    }
    else{
      return $item1;
    }
  }

  function ConvertTextToSql($VarString){
    if('' != $VarString){
      $VarString = str_replace('\\"', '"', $VarString);
      $VarString = str_replace("\\'", "'", $VarString);
      $VarString = str_replace("'", '&#039;', $VarString);
      //$VarString = htmlspecialchars($VarString);
      return $VarString;
    }
    else{
      return '';
    }
  }
  
  function array2tree($source_arr, $parent_id, $key_children='child_nodes', $key_id='menu_id', $key_parent_id='menu_parent_id'){
  	$tree=array();
  	if (empty($source_arr)){
  		return $tree;
  	}
  	SiteLibs::_array2treer($source_arr, $tree, $parent_id, $parent_id, $key_children, $key_id, $key_parent_id);
  	return $tree;
	}

	function _array2treer($source_arr, &$_this, $parent_id, $_this_id, $key_children, $key_id, $key_parent_id){
		foreach ($source_arr as $value)
  		if ($value[$key_parent_id] == $_this_id){
    		$_this[$key_children][$value[$key_id]]=$value;
    	}
    	if (isset($_this[$key_children])){
				foreach ($_this[$key_children] as $value)
      		SiteLibs::_array2treer($source_arr, $_this[$key_children][$value[$key_id]], $parent_id, $value[$key_id], $key_children, $key_id, $key_parent_id);
				if ($_this_id == $parent_id)
      		$_this=$_this[$key_children];
    	}
	}
  
  function GetLinks($VarStr = ''){
    if('' != $VarStr){
      $ArrFromStr = explode('-----', $VarStr);
      $VarReturn = '';
      if (true === is_array($ArrFromStr) && 0 < count($ArrFromStr)){
        foreach ($ArrFromStr AS $k => $v){
          if ('' != $v){
            if('' != $VarReturn){
              $VarReturn .= '<br />';
            }
            $VarText = $k+1;
            $ArrLinkRow = explode('_____', $v);
            $VarReturn .= '<a target="_blank" class="ui-state-default" href="./TnpaDetail.php?UrlId='. $ArrLinkRow[1] .'">'. iconv("windows-1251", "UTF-8", $ArrLinkRow[0]) .'</a>&nbsp;';
          }
        }
      }
      return $VarReturn;
    }
    else{
      return '';
    }
  }
  function scheme_url(){
    if(true === isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on"){
      return 'https://';
    }
    else{
      return 'http://';
    }
  }
}
?>