<?php
class BrowserUtils
{
	/**
	 * Detect browser names and versions of Chrome, Firefox, Internet Explorer, Opera & Safari.
	 *
	 * Returns array('name' => Browser name (as written here ^),
	 * 				 'version' => array(major version, minor subversion, release, build)).
	 *
	 * 'version' is array of integers.
	 *
	 * In case of no browser detected method returns array(null, array()).
	 *
	 * All non-digital version flags (a, b, beta, pre and so on) are skipped.
	 * If browser version is shorter then 4 parts separated by point (.),
	 * undetected parts will be set in 'version' array as null.
	 *
	 * This code written with great help of http://www.useragentstring.com/ website
	 *
	 * The code is actual on 2009-09-15.
	 *
	 * @author Leontyev Valera (feedbee@gmail.com)
	 * @copyright 2009
	 * @license BSD
	 *
	 * @param string $userAgent
	 * @return array
	 */
	static function detectBrowser($userAgent = null)
	{
		is_null($userAgent) && ($userAgent = $_SERVER['HTTP_USER_AGENT']);
		$name = null;
		$version = array(null, null, null, null);
		if (false !== strpos($userAgent, 'Opera/'))
		{
			//http://www.useragentstring.com/pages/Opera/
			$name = 'Opera';
			if (false !== strpos($userAgent, 'Version/')) // http://dev.opera.com/articles/view/opera-ua-string-changes/
			{
				preg_match('#Version/(\d{1,2})\.(\d{1,2})#i', $userAgent, $versionMatch);
				isset($versionMatch[1]) && $version[0] = (int)$versionMatch[1];
				isset($versionMatch[2]) && $version[1] = (int)$versionMatch[2];
			}
			else
			{
				preg_match('#Opera/(\d{1,2})\.(\d{1,2})#i', $userAgent, $versionMatch);
				isset($versionMatch[1]) && $version[0] = (int)$versionMatch[1];
				isset($versionMatch[2]) && $version[1] = (int)$versionMatch[2];
			}
		}
		else if (false !== strpos($userAgent, 'Opera '))
		{
			//http://www.useragentstring.com/pages/Opera/
			$name = 'Opera';
			preg_match('#Opera (\d{1,2})\.(\d{1,2})#i', $userAgent, $versionMatch);
			isset($versionMatch[1]) && $version[0] = (int)$versionMatch[1];
			isset($versionMatch[2]) && $version[1] = (int)$versionMatch[2];
		}
		else if (false !== strpos($userAgent, 'Firefox/'))
		{
			// http://www.useragentstring.com/pages/Firefox/
			$name = 'Firefox';
			preg_match('#Firefox/(\d{1,2})\.(\d{1,2})(\.(\d{1,2})(\.(\d{1,2}))?)?#i', $userAgent, $versionMatch);
			isset($versionMatch[1]) && $version[0] = (int)$versionMatch[1];
			isset($versionMatch[2]) && $version[1] = (int)$versionMatch[2];
			isset($versionMatch[4]) && $version[2] = (int)$versionMatch[4];
			isset($versionMatch[6]) && $version[3] = (int)$versionMatch[6];
		}
		else if (false !== strpos($userAgent, 'MSIE '))
		{
			//http://www.useragentstring.com/pages/Internet%20Explorer/
			$name = 'Internet Explorer';
			preg_match('#MSIE (\d{1,2})\.(\d{1,2})#i', $userAgent, $versionMatch);
			isset($versionMatch[1]) && $version[0] = (int)$versionMatch[1];
			isset($versionMatch[2]) && $version[1] = (int)$versionMatch[2];
		}
		else if (false !== strpos($userAgent, 'Iceweasel/')) // Firefox in Debian
		{
			// http://www.useragentstring.com/pages/Iceweasel/
			$name = 'Firefox'; //Iceweasel is identical to Firefox! no need to differt them
			preg_match('#Iceweasel/(\d{1,2})\.(\d{1,2})(\.(\d{1,2})(\.(\d{1,2}))?)?#i', $userAgent, $versionMatch);
			isset($versionMatch[1]) && $version[0] = (int)$versionMatch[1];
			isset($versionMatch[2]) && $version[1] = (int)$versionMatch[2];
			isset($versionMatch[4]) && $version[2] = (int)$versionMatch[4];
			isset($versionMatch[6]) && $version[3] = (int)$versionMatch[6];
		}
		else if (false !== strpos($userAgent, 'Chrome/'))
		{
			// http://www.useragentstring.com/pages/Chrome/
			$name = 'Chrome';
			preg_match('#Chrome/(\d{1,2})\.(\d{1,3})\.(\d{1,3}).(\d{1,3})#i', $userAgent, $versionMatch);
			isset($versionMatch[1]) && $version[0] = (int)$versionMatch[1];
			isset($versionMatch[2]) && $version[1] = (int)$versionMatch[2];
			isset($versionMatch[3]) && $version[2] = (int)$versionMatch[3];
			isset($versionMatch[4]) && $version[3] = (int)$versionMatch[4];
		}
		else if (false !== strpos($userAgent, 'Safari/'))
		{
			// http://www.useragentstring.com/pages/Safari/
			$name = 'Safari';
			/* Uncomment this block of code if u want to use Version/ tag
			 * instead of Safari/Build tag. Old Safari browsers haven’t Version/ tag
			 * and their version was marked as build number (ex. 528.16).
			if (false !== strpos($userAgent, 'Version/')) // old versions of Safari doesn't have Version tag in UserAgent
			{
				preg_match('#Version/(\d{1,2})\.(\d{1,2})(\.(\d{1,2}))?#i', $userAgent, $versionMatch);
				isset($versionMatch[1]) && $version[0] = (int)$versionMatch[1];
				isset($versionMatch[2]) && $version[1] = (int)$versionMatch[2];
				isset($versionMatch[4]) && $version[2] = (int)$versionMatch[4];
			}
			else
			{*/
				preg_match('#Safari/(\d{1,3})\.(\d{1,2})(\.(\d{1,2}))?#i', $userAgent, $versionMatch);
				isset($versionMatch[1]) && $version[0] = (int)$versionMatch[1];
				isset($versionMatch[2]) && $version[1] = (int)$versionMatch[2];
				isset($versionMatch[4]) && $version[2] = (int)$versionMatch[4];
			//}
		}

		return array('name' => $name, 'version' => $version);
	}

	/**
	 * Compare browser versions.
	 *
	 * Returns int(0)  if version is aqual to $conditions,
	 *         int(-1) if version is older than $conditions,
	 *         int(1)  if version is newer than $conditions.
	 *
	 * Returns NULL in case of any error.
	 *
	 * @author Leontyev Valera (feedbee@gmail.com)
	 * @copyright 2009
	 * @license BSD
	 *
	 * @param array $browser -- result of self::detectBrowser() method
	 * @param $conditions    -- vetsions to compre array('Opera' => array(9, 4), 'Firefox' => array(3, 1, 1), ...)
	 * @return int
	 */
	static public function checkForBrowserVersion(array $browser, array $conditions)
	{
		if (!isset($browser['name']) || !isset($conditions[$browser['name']])
			|| !isset($browser['version']) || count($browser['version']) < 1)
		{
			return null;
		}

		$cnd = $conditions[$browser['name']]; // 0=>, 1=>, 2=>
		if (!is_array($cnd))
		{
			return null;
		}

		for ($i = 0; $i < count($cnd); $i++)
		{
			if ($browser['version'][$i] < $cnd[$i])
			{
				return -1;
			}
			else if ($browser['version'][$i] > $cnd[$i])
			{
				return 1;
			}
		}

		return 0;
	}
}

//--------------------------------------------------------------------
// Функция проверки принадлежит ли браузер к мобильным устройствам
// Возвращает 0 - браузер стационарный или определить его не удалось
//            1-4 - браузер запущен на мобильном устройстве
//--------------------------------------------------------------------
function is_mobile() {
  $user_agent=strtolower(getenv('HTTP_USER_AGENT'));
  $accept=strtolower(getenv('HTTP_ACCEPT'));

  if ((strpos($accept,'text/vnd.wap.wml')!==false) ||
      (strpos($accept,'application/vnd.wap.xhtml+xml')!==false)) {
    return 1; // Мобильный браузер обнаружен по HTTP-заголовкам
  }

  if (isset($_SERVER['HTTP_X_WAP_PROFILE']) ||
      isset($_SERVER['HTTP_PROFILE'])) {
    return 2; // Мобильный браузер обнаружен по установкам сервера
  }

  if (preg_match('/(mini 9.5|vx1000|lge |m800|e860|u940|ux840|compal|'.
    'wireless| mobi|ahong|lg380|lgku|lgu900|lg210|lg47|lg920|lg840|'.
    'lg370|sam-r|mg50|s55|g83|t66|vx400|mk99|d615|d763|el370|sl900|'.
    'mp500|samu3|samu4|vx10|xda_|samu5|samu6|samu7|samu9|a615|b832|'.
    'm881|s920|n210|s700|c-810|_h797|mob-x|sk16d|848b|mowser|s580|'.
    'r800|471x|v120|rim8|c500foma:|160x|x160|480x|x640|t503|w839|'.
    'i250|sprint|w398samr810|m5252|c7100|mt126|x225|s5330|s820|'.
    'htil-g1|fly v71|s302|-x113|novarra|k610i|-three|8325rc|8352rc|'.
    'sanyo|vx54|c888|nx250|n120|mtk |c5588|s710|t880|c5005|i;458x|'.
    'p404i|s210|c5100|teleca|s940|c500|s590|foma|samsu|vx8|vx9|a1000|'.
    '_mms|myx|a700|gu1100|bc831|e300|ems100|me701|me702m-three|sd588|'.
    's800|8325rc|ac831|mw200|brew |d88|htc\/|htc_touch|355x|m50|km100|'.
    'd736|p-9521|telco|sl74|ktouch|m4u\/|me702|8325rc|kddi|phone|lg |'.
    'sonyericsson|samsung|240x|x320vx10|nokia|sony cmd|motorola|'.
    'up.browser|up.link|mmp|symbian|smartphone|midp|wap|vodafone|o2|'.
    'pocket|kindle|mobile|psp|treo)/', $user_agent)) {
    return 3; // Мобильный браузер обнаружен по сигнатуре User Agent
  }

  if (in_array(substr($user_agent,0,4),
    Array("1207", "3gso", "4thp", "501i", "502i", "503i", "504i", "505i", "506i",
          "6310", "6590", "770s", "802s", "a wa", "abac", "acer", "acoo", "acs-",
          "aiko", "airn", "alav", "alca", "alco", "amoi", "anex", "anny", "anyw",
          "aptu", "arch", "argo", "aste", "asus", "attw", "au-m", "audi", "aur ",
          "aus ", "avan", "beck", "bell", "benq", "bilb", "bird", "blac", "blaz",
          "brew", "brvw", "bumb", "bw-n", "bw-u", "c55/", "capi", "ccwa", "cdm-",
          "cell", "chtm", "cldc", "cmd-", "cond", "craw", "dait", "dall", "dang",
          "dbte", "dc-s", "devi", "dica", "dmob", "doco", "dopo", "ds-d", "ds12",
          "el49", "elai", "eml2", "emul", "eric", "erk0", "esl8", "ez40", "ez60",
          "ez70", "ezos", "ezwa", "ezze", "fake", "fetc", "fly-", "fly_", "g-mo",
          "g1 u", "g560", "gene", "gf-5", "go.w", "good", "grad", "grun", "haie",
          "hcit", "hd-m", "hd-p", "hd-t", "hei-", "hiba", "hipt", "hita", "hp i",
          "hpip", "hs-c", "htc ", "htc-", "htc_", "htca", "htcg", "htcp", "htcs",
          "htct", "http", "huaw", "hutc", "i-20", "i-go", "i-ma", "i230", "iac",
          "iac-", "iac/", "ibro", "idea", "ig01", "ikom", "im1k", "inno", "ipaq",
          "iris", "jata", "java", "jbro", "jemu", "jigs", "kddi", "keji", "kgt",
          "kgt/", "klon", "kpt ", "kwc-", "kyoc", "kyok", "leno", "lexi", "lg g",
          "lg-a", "lg-b", "lg-c", "lg-d", "lg-f", "lg-g", "lg-k", "lg-l", "lg-m",
          "lg-o", "lg-p", "lg-s", "lg-t", "lg-u", "lg-w", "lg/k", "lg/l", "lg/u",
          "lg50", "lg54", "lge-", "lge/", "libw", "lynx", "m-cr", "m1-w", "m3ga",
          "m50/", "mate", "maui", "maxo", "mc01", "mc21", "mcca", "medi", "merc",
          "meri", "midp", "mio8", "mioa", "mits", "mmef", "mo01", "mo02", "mobi",
          "mode", "modo", "mot ", "mot-", "moto", "motv", "mozz", "mt50", "mtp1",
          "mtv ", "mwbp", "mywa", "n100", "n101", "n102", "n202", "n203", "n300",
          "n302", "n500", "n502", "n505", "n700", "n701", "n710", "nec-", "nem-",
          "neon", "netf", "newg", "newt", "nok6", "noki", "nzph", "o2 x", "o2-x",
          "o2im", "opti", "opwv", "oran", "owg1", "p800", "palm", "pana", "pand",
          "pant", "pdxg", "pg-1", "pg-2", "pg-3", "pg-6", "pg-8", "pg-c", "pg13",
          "phil", "pire", "play", "pluc", "pn-2", "pock", "port", "pose", "prox",
          "psio", "pt-g", "qa-a", "qc-2", "qc-3", "qc-5", "qc-7", "qc07", "qc12",
          "qc21", "qc32", "qc60", "qci-", "qtek", "qwap", "r380", "r600", "raks",
          "rim9", "rove", "rozo", "s55/", "sage", "sama", "samm", "sams", "sany",
          "sava", "sc01", "sch-", "scoo", "scp-", "sdk/", "se47", "sec-", "sec0",
          "sec1", "semc", "send", "seri", "sgh-", "shar", "sie-", "siem", "sk-0",
          "sl45", "slid", "smal", "smar", "smb3", "smit", "smt5", "soft", "sony",
          "sp01", "sph-", "spv ", "spv-", "sy01", "symb", "t-mo", "t218", "t250",
          "t600", "t610", "t618", "tagt", "talk", "tcl-", "tdg-", "teli", "telm",
          "tim-", "topl", "tosh", "treo", "ts70", "tsm-", "tsm3", "tsm5", "tx-9",
          "up.b", "upg1", "upsi", "utst", "v400", "v750", "veri", "virg", "vite",
          "vk-v", "vk40", "vk50", "vk52", "vk53", "vm40", "voda", "vulc", "vx52",
          "vx53", "vx60", "vx61", "vx70", "vx80", "vx81", "vx83", "vx85", "vx98",
          "w3c ", "w3c-", "wap-", "wapa", "wapi", "wapj", "wapm", "wapp", "wapr",
          "waps", "wapt", "wapu", "wapv", "wapy", "webc", "whit", "wig ", "winc",
          "winw", "wmlb", "wonu", "x700", "xda-", "xda2", "xdag", "yas-", "your",
          "zeto", "zte-"))) {
    return 4; // Мобильный браузер обнаружен по сигнатуре User Agent
  }

  return false; // Мобильный браузер не обнаружен
}

// функция для определение кодировки текста
function check_code()
{
  $tab = array("UTF-8", "ASCII", "Windows-1252", "ISO-8859-15", "ISO-8859-1", "ISO-8859-6", "CP1256");
  $chain = "";
  foreach ($tab as $i)
	    {
	        foreach ($tab as $j)
	        {
	            $chain .= " $i-$j ".iconv($i, $j,$objXML->nodeValue).'<br>';
	        }
	    }

  $res['name']=$objXML->nodeName.':'.$chain;
}

 if(!function_exists('parse_ini_string'))
 { function parse_ini_string($str, $ProcessSections=false)
   {
        $lines  = explode("\n", $str);
        $return = Array();
        $inSect = false;
        foreach($lines as $line){
            $line = trim($line);
            if(!$line || $line[0] == "#" || $line[0] == ";")
                continue;
            if($line[0] == "[" && $endIdx = strpos($line, "]")){
                $inSect = mb_substr($line, 1, $endIdx-1);
                continue;
            }
            if(!strpos($line, '=')) // (We don't use "=== false" because value 0 is not valid as well)
                continue;

            $tmp = explode("=", $line, 2);
            if($ProcessSections && $inSect)
                $return[$inSect][trim($tmp[0])] = ltrim($tmp[1]);
            else
                $return[trim($tmp[0])] = ltrim($tmp[1]);
        }
        return $return;
   }
 }


if (!function_exists('exif_imagetype'))
 { function exif_imagetype($fname)
   { $info=getimagesize($fname) ;
     //print_r($info) ;
     return($info[2]) ;
	 // отключено 4.10.2010 - так как этот способ не позволяет определять изображения, зарузенные в tmp файлы
	 //if (stripos($fname,'.jpg')!==false)  return(2) ;
	 //if (stripos($fname,'.jpeg')!==false) return(2) ;
	 //if (stripos($fname,'.gif')!==false)  return(1) ;
	 //if (stripos($fname,'.png')!==false)  return(3) ;
	 //if (stripos($fname,'.bmp')!==false)  return(15) ;
   }
 }

if(!function_exists('mime_content_type')) {

    function mime_content_type($filename) {

        $mime_types = array(

            'txt' => 'text/plain',
            'htm' => 'text/html',
            'html' => 'text/html',
            'php' => 'text/html',
            'css' => 'text/css',
            'js' => 'application/javascript',
            'json' => 'application/json',
            'xml' => 'application/xml',
            'swf' => 'application/x-shockwave-flash',
            'flv' => 'video/x-flv',

            // images
            'png' => 'image/png',
            'jpe' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'gif' => 'image/gif',
            'bmp' => 'image/bmp',
            'ico' => 'image/vnd.microsoft.icon',
            'tiff' => 'image/tiff',
            'tif' => 'image/tiff',
            'svg' => 'image/svg+xml',
            'svgz' => 'image/svg+xml',

            // archives
            'zip' => 'application/zip',
            'rar' => 'application/x-rar-compressed',
            'exe' => 'application/x-msdownload',
            'msi' => 'application/x-msdownload',
            'cab' => 'application/vnd.ms-cab-compressed',

            // audio/video
            'mp3' => 'audio/mpeg',
            'qt' => 'video/quicktime',
            'mov' => 'video/quicktime',

            // adobe
            'pdf' => 'application/pdf',
            'psd' => 'image/vnd.adobe.photoshop',
            'ai' => 'application/postscript',
            'eps' => 'application/postscript',
            'ps' => 'application/postscript',

            // ms office
            'doc' => 'application/msword',
            'rtf' => 'application/rtf',
            'xls' => 'application/vnd.ms-excel',
            'ppt' => 'application/vnd.ms-powerpoint',

            // open office
            'odt' => 'application/vnd.oasis.opendocument.text',
            'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
        );

        $arr=explode('.',$filename) ;
        $ext = strtolower(array_pop($arr));
        if (array_key_exists($ext, $mime_types)) {
            return $mime_types[$ext];
        }
        elseif (function_exists('finfo_open')) {
            $finfo = finfo_open(FILEINFO_MIME);
            $mimetype = finfo_file($finfo, $filename);
            finfo_close($finfo);
            return $mimetype;
        }
        else {
            return 'application/octet-stream';
        }
    }
}

 if (!function_exists('htmlspecialchars_decode'))
  {
    function htmlspecialchars_decode($str) { return($str) ; }
  }


// опредение в глобальныз переменных версий браузера
// источник: http://valera.ws/2009.09.16~browser-version-detection/

function defines_vers($HTTP_USER_AGENT,$debug=0)
	{   global $br_vers,$IE ;
		$browser = BrowserUtils::detectBrowser($HTTP_USER_AGENT);
		//if ($debug) damp_array($browser);
		$br_vers=$browser['name'] ;
		if ($browser['name']=='Internet Explorer')
		{ $br_vers=($browser['version'][0]<6)? 'IE 5 или младше':'IE '.$browser['version'][0] ;
		  $IE='IE' ;
		} else $IE='' ;

		return($br_vers) ;
	}

function get_se_query($referer, $se='', $start=0, $filter='')
 {
        $referer = urldecode($referer);
        if (empty($referer) || strpos($referer, "=") === false ) {
            return false;
        }
        //$referer = $this->strtolower_cyr($referer);
		$page 	= '';
		$filter = '';
		$multi 	= 0;
        if (strpos($referer, "yand")) {
            $sw 		= 'text=';
            $referer 	= urldecode($referer);
            //$referer  = convert_cyr_string ($referer, 'k', 'w');
			$page 		= 'p=';
			$multi 		= 10;
            $se 		= 'Yandex';
            //$referer  = iconv('utf-8','windows-1251',$referer) ;

        } else if(stristr($referer, 'google.')) {
            $sw		  = 'q=';
			$filter   = 'cr=';
			$page 	  = 'start=';
            $referer  = urldecode($referer);
            //$referer  = $this->utf_encode($referer, 'decode');
            //$referer  = iconv('utf-8','windows-1251',$referer) ;

			$url_info = parse_url($referer);
			if (!empty($url_info['host'])) {
				$se 	  = str_replace('www.', '', $url_info['host']);
			} else {
				$se 	  = 'Google';
			}
        } else if ((stristr($referer, 'go.mail.ru')) and (stristr($referer, 'words='))) {
            $sw ='words=';
            $se = 'mail.ru';
        } else if (stristr($referer,  'go.mail.ru')) {
            $sw = 'q=';
            $se = 'mail.ru';
        } else if (stristr($referer,  'meta.ua')) {
			$sw = 'q=';
            $se = 'meta.ua';
        } else if (stristr($referer,  'meta.com.ua')) {
			$sw = 'q=';
            $se = 'meta.ua';
        } else if (stristr($referer,  'meta-ukraine.com')) {
			$sw = 'q=';
            $se = 'meta.ua';
        } else if (stristr($referer,  'bigmir.net')) {
			$sw    = 'q=';
			$page  = 'cPage=';
			$multi = 10;
            $se    = 'bigmir.net';
        } else if (stristr($referer,  'rambler')) {
			$page 	= 'start=';
			$sw 	= 'query=';
            $se 	= 'Rambler';
            $referer  = urldecode($referer);
            //$referer  = iconv('utf-8','windows-1251',$referer) ;

        } else if (stristr($referer,  'sm.aport')) {
			$sw='r=';
            $se = 'Aport';
        } else if (stristr($referer,  'search.yahoo')) {
			$sw='p=';
            $se = 'Yahoo';
        } else if (stristr($referer,  'search.msn.com')) {
			$sw = 'q=';
            $se = 'MSN';
            $referer  = urldecode($referer);
            //$referer  = iconv('utf-8','windows-1251',$referer) ;

        } else if (stristr($referer,  'aolsearch')) {
			$sw='query=';
            $se = 'AOL';
        //} else if(stristr($referer,   'q=')) { $sw = 'q=';
        //} else if(stristr($referer,   'query=')) { $sw = 'query=';
        } else {
            return false;
        }
        if (!stristr($referer,  $sw)) {
            return false;
        }
        $referer = strip_tags ($referer.'&');
        $referer = stripslashes ($referer);
        eregi ($sw."([^&]*)", $referer, $query);
        $query = trim($query[1]);
        if (empty($query)) {
            return 0;
        }
        eregi ($page."([^&]*)", $referer, $matches);
		$start = intval(trim($matches[1]));
		if ($multi>0 && $start>0) {
			$start = ($start-1)*$multi;
		}
		if (!empty($filter)) {
			if (eregi ($filter."([^&]*)", $referer, $matches)) {
				$filter = trim($matches[1]);
			} else {
				$filter = '';
			}
		}
        return $query;
    }


// http://php5.com.ua/blog/php-programming/17.html
function translit($text)
{ if (is_object(_CUR_PAGE()) and method_exists(_CUR_PAGE(),'translit')) return(_CUR_PAGE()->translit()) ;
  //$l=setlocale(LC_ALL, 'ru_RU.CP1251');
  //var_export($l); // посмотрим, что локаль включилась. Если нет - скрипт выдаст false
  //if (!preg_match('|русс|i','русский язык')) echo 'русский так и не заработал';
  if(preg_match("/[А-я]/", $text))
  { $trans = array("ий" => "iy","ый" => "yy",'№ '=>'N','№'=>'N',
                   "а" => "a", "б" => "b", "в" => "v", "г" => "g", "д" => "d","е" => "e","ё" => "e","ж" => "zh","з" => "z","и" => "i","й" => "y","к" => "k","л" => "l","м" => "m","н" => "n","о" => "o","п" => "p","р" => "r","с" => "s","т" => "t","у" => "u","ф" => "f","х" => "h","ц" => "ts","ч" => "ch","ш" => "sh","щ" => "sch","ы" => "y","э" => "e","ю" => "yu","я" => "ya",
                   "А" => "A","Б" => "B","В" => "V","Г" => "G","Д" => "D","Е" => "E","Ё" => "E","Ж" => "Zh","З" => "Z","И" => "I","Й" => "Y","К" => "K","Л" => "L","М" => "M","Н" => "N","О" => "O","П" => "P","Р" => "R","С" => "S","Т" => "T","У" => "U","Ф" => "F","Х" => "Kh","Ц" => "Ts","Ч" => "Ch","Ш" => "Sh","Щ" => "Shch","Ы" => "Y","Э" => "E","Ю" => "Yu","Я" => "Ya","ь" => "","Ь" => "","ъ" => "","Ъ" => "");
    return strtr($text, $trans);
  }
  else return $text;
}


 class c_grabber
 {

     static function rawToSimpleXML($data)
     {  $tidy_config = array( 'input-encoding' => 'utf8',
             				//	'input-encoding' => 'win1252',
             					//'input-encoding' => 'us-ascii',
             					'output-encoding' => 'utf8',
             				  //'output-encoding' => 'win1252',
             					'output-xml' => TRUE,
             					'add-xml-decl' => TRUE,
             					'hide-comments' => TRUE
         					);
         //$tidy_encoding = 'win1252';
         //$tidy_encoding = 'utf8';
         /*чистим HTML*/
         //$tidy = tidy_parse_string($data, $tidy_config, $tidy_encoding);
         //$tidy->CleanRepair();
         //$tidy_out = $tidy->html()->value;
         $dom = new DOMDocument('1.0', 'utf-8');
         $dom->strictErrorChecking = FALSE;
         //@$dom->loadHTML($tidy_out);
         @$dom->loadHTML($data);
         //unset($tidy);
         //echo  $dom->saveHTML() ;
         /* �?нициализация SimpleXML */
         $simpexml = simplexml_import_dom($dom);
         //$simpexml = simplexml_load_file('http://teploprofi.com/teploobmennik-et-008/');
         //echo $simpexml->html->body.'<br>' ;
         unset($dom);
         //print_r($simpexml) ;
         return $simpexml;
     }

     /* Вспомогательная функция для очистки XML */
     static function xmlEscape($text)
     {   $text = str_replace("\r", '', $text);
         $text = str_replace("\n", ' ', $text);
         return $text;
     }

     /* Вспомогательная функция для получения данных из SimpleXML */
     static function getFromXPath($xml)
     {   $text = '';
         if($xml && $xml[0])
         {
             //$text = self::xmlEscape( html_entity_decode ($xml[0]->asXML()));
             $text = self::xmlEscape($xml[0]->asXML());
             //$text = self::xmlEscape( $xml[0]->asXML());
             /*?><textarea rows="6" cols="100"><? echo $text ?></textarea><br><?*/
             //$text=iconv('utf-8','windows-1252',$text) ;
             $text=mb_convert_encoding($text,'windows-1252','utf-8') ;
             //damp_string($text) ;
             //$text=iconv('windows-1252','utf-8',$text) ;
             //$text=iconv('utf-8','windows-1252',$text) ;
             /*?><textarea rows="6" cols="100"><? echo $text ?></textarea><br><br><br><?*/

         }
         return $text;
     }

     static function getAttrFromXPath($xml,$attr_name)
     {   $text = '';
         if($xml && $xml[0])
         {   $text=$xml[0][$attr_name] ;
             $text=mb_convert_encoding($text,'windows-1252','utf-8') ;
         }
         return $text;
     }


     // пример парсинга страницы с подразделами сайта
     static public function parse_goods_from_page($url)
     {   global $TM_catalog,$obj_info,$start_page ;
         $tkey=$_SESSION['pkey_by_table'][$TM_catalog] ;

         $input = file_get_contents($url); // Получение данных
         $xml = self::rawToSimpleXML($input); // Подготовка полученных данных к обработке

         // получаем адрес страницы каталога описаний
         if (!strpos($url,'comparison/'))
         {	$ret['href_page'] = self::getAttrFromXPath($xml->xpath('/html/body/div/div[2]/div[4]/div[2]/div[2]/ul/li/a'),'href');
          	if (!$ret['href_page'])  { echo 'Не удалось получить адрес страницы описаний на странице '.$url.'<br>' ; return ; }
          	$url='http://sravni.com'.$ret['href_page'] ;
         }
         $input = file_get_contents($url); // Получение данных
         $xml = self::rawToSimpleXML($input); // Подготовка полученных данных к обработке

         // текущий раздел
         $ret['category_name'] = self::getFromXPath($xml->xpath('/html/body/div/div[2]/div[2]/div[2]/a[2]'));
         echo 'Будут импортированы описания товаров раздела: "<strong>'.$ret['category_name'].'</strong>" со страницы <a href="'.$url.'" target=_blank>'.$url.'</a><br>' ;

     	// определяем число страниц
         $ret['count_page'] = 	self::getFromXPath($xml->xpath('/html/body/div/div[2]/div[5]/table/tr/td/b'));
         if (!$ret['count_page'])  $ret['count_page']=1 ;
         echo 'Число страниц: '.$ret['count_page'].'<br>' ;

         $ret['added_goods']=0 ;
         $ret['ignore_goods']=0 ;

         echo 'Начинаем обработку со страницы: '.$start_page.'<br>' ;

         for ($cur_page=$start_page; $cur_page<=$ret['count_page']; $cur_page++)
         { if ($cur_page>1) { $cur_href=$ret['href_page'].'?pg='.$cur_page ;
						      $input = file_get_contents($url); // Получение данных очередной страницы
						      $xml = self::rawToSimpleXML($input); // Подготовка полученных данных к обработке
						    }
		     ?><h2>Страница <? echo $cur_page ?></h2><?

		     // опеределяем, сколько тавара размещено на странице
	         preg_match_all('/<div class="item_horizontal(.+?)">/is',$input,$matches,PREG_SET_ORDER) ; //print_r($matches) ; echo '<br>' ;
	         $count=_sizeof($matches) ;
             echo 'На странице найдено '.$count.' описаний товаров<br>' ;
             $kk=0 ;
	         // краткие описания товаров

	         for ($i=2; $i<=$count+1; $i++)
	         {
	           $goods=array() ;
	           $goods['parent']=$obj_info['pkey'] ;
	           $goods['clss']=205 ;
	           $goods['obj_name'] = self::getFromXPath($xml->xpath('/html/body/div/div[2]/div[5]/div['.$i.']/div[2]/div/a'));
	           $goods['intro'] = 	self::getFromXPath($xml->xpath('/html/body/div/div[2]/div[5]/div['.$i.']/div[2]/div[2]/p'));
	           $goods['sravni_href'] =  self::getAttrFromXPath($xml->xpath('/html/body/div/div[2]/div[5]/div['.$i.']/div[2]/div/a'),'href');
	           if (strpos($goods['sravni_href'],'javascript')!==false) $goods['sravni_href']='' ;
	           // проверяем, что такого описания нет в базе
	           //$ops=execSQL_van('select pkey from '.$TM_catalog.' where obj_name="'.addslashes($goods['obj_name']).'"') ;
	           if (!$ops['pkey'])
	           { // добавляем в базу описание товара
	             $id=adding_rec_to_table($TM_catalog,$goods) ;
	             //if ($id)  echo '�?мпортирован "<strong>'.$goods['obj_name'].'</strong>"<br>' ;
	           	 // добавляем фото
	           	 $goods['img_src'] =  self::getAttrFromXPath($xml->xpath('/html/body/div/div[2]/div[5]/div['.$i.']/div/div/table/tr/td/a/img'),'src');
	          	 if (strpos($goods['img_src'],'phone.jpg')!==false) $goods['img_src']='' ;
	             else
		         { $goods['img_src'] =  str_replace('small_100x100','site_4/newcat/big',$goods['img_src']) ;
		           $img_name=basename($goods['img_src']) ;
		           $goods['img_src_small'] = str_replace('site_4/','',$goods['img_src']) ;
		           $goods['img_src_small'] = str_replace('big/','',$goods['img_src_small']) ;
		           $goods['img_src_small'] = str_replace($img_name,'midl/'.$img_name,$goods['img_src_small']) ;
		           //$goods['img'] =  '<img src="'.$goods['img_src_small'].'"  border="0">' ;
		           obj_upload_image_by_href($id.'.'.$tkey,$goods['img_src_small'],array('debug'=>2)) ;

				   // загружаем большое фото как обычный файл
				  // upload_file_by_href($goods['img_src'],_DOT(112)->dir_to_file,array('use_dir'=>'source/','debug'=>0)) ;

		           //echo '<br>' ;

		         }
      			$ret['added_goods']++ ;
                $kk++ ;


	           } else { echo '"<strong>'.$goods['obj_name'].'</strong>" уже есть в базе<br>' ;
	           			$ret['ignore_goods']++ ;
	           		  }



	         }
             echo 'На странице импортировано '.$kk.' описаний товаров<br>' ;

         }

         _event_reg('�?мпорт товаров в раздел "'.$ret['category_name'].'": '.$ret['added_goods'].' шт.','') ;

         return $ret;
     }


 }

//***************************************************************************************************************************************************************
// Подсветка синтаксиса в статьях с использованием GeSHi
// 16 мая 2008, 3:40 Автор: Григорий Рубцов [rgbeast]
// http://www.webew.ru/articles/412.webew
//***************************************************************************************************************************************************************

//require_once("geshi/geshi.php");
//вместо добавить $use_script[]='geshi/geshi.php' ; в patch.php

function geshi_syntax_filter($text) {
  $search = '/\[syntax=(.*?)\]\r?\n?(.*?)\r?\n?\[\/syntax\]/is';
  return preg_replace_callback($search, 'geshi_syntax_filter_callback', $text);
}

function geshi_syntax_filter_callback($data)
{
  $linenumbers = false;
  $urls = false;
  $inline = false;
  $indentsize = 4;

  if (isset($data[2])) {
    $syntax = $data[1];
    $code = $data[2];

    if(strstr($syntax, '*')) {
      $inline = true;
      $syntax=str_replace('*','',$syntax);
    }

    if(strstr($syntax, '#')) {
      $linenumbers = true;
      $syntax=str_replace('#','',$syntax);
    }

    if ($syntax=='html') {
      $syntax = 'html4strict';
    }

    if ($syntax=='js') {
      $syntax = 'javascript';
    }

    $geshi = new GeSHi($code, $syntax);
    $geshi->set_header_type(GESHI_HEADER_DIV);

    $geshi->enable_classes(true);
    $geshi->set_overall_style('font-family: monospace;');
    if($linenumbers) {
      $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS, 5);
      $geshi->set_line_style('color:#222;', 'color:#888;');
      $geshi->set_overall_style('font-size: 14px;font-family: monospace;', true);
    }

    if (!$urls) {
      for ($i = 0; $i < 5; $i++) {
    $geshi->set_url_for_keyword_group($i, '');
      }
    }

    if ($indentsize) {
      $geshi->set_tab_width($indentsize);
    }

    $parsed = $geshi->parse_code();
    if($inline) {
      $parsed = preg_replace('/^<div/','<span', $parsed);
      $parsed = preg_replace('/<\/div>$/','</span>', $parsed);
    }
  }
  return $parsed;
}

function check_parse_by_ip()
{ global $aip ;
  if ($aip)
  { //echo 'ip='.$ip.'<br>';
    // получаем информацию, сколько было сделано запросов за послений час
    $t_end=time() ;
   	$now=getdate($t_end) ;
    $t_start=mktime($now['hours']-1,$now['minutes'],$now['seconds'],$now['mon'],$now['mday'],$now['year']); // время начала расчетного периода
    $ip_info=execSQL('select count(pkey) as cnt,max(pkey) as pkey from '.TM_LOG_PAGES.' where ip="'.$aip.'" and c_data>='.$t_start.' and c_data<='.$t_end,2) ;
    $rec=execSQL('select * from '.TM_LOG_PAGES.' where ip="'.$aip.'" limit 10',2) ;
  }
}

// функция возвращаем инфу по IP адресу, в зависимости от имеющих плагинов и возможностей
// возвращется:
// array(   country : страна
//          city:     город
//          region:   область
//          lat:      широта
//          lng:      долгота
function get_IP_city_info($IP)
{ $res=array() ;
  switch(_GEO_IP_METHOD_)
  { case "GeoIP_db" : // http://js-php.ru/web-development/php-development/get-geo-info-by-ip/
                      $_SESSION['GeoIP_db'] = geoip_open(_DIR_TO_ROOT."/AddOns/Geo/GeoIPCity.dat",GEOIP_STANDARD);
                      $record = Geoip_record_by_addr($_SESSION['GeoIP_db'],$IP);
                      if (is_object($record))
                        { $res['country']=$record->country_code3 ;
                          $res['city']=$record->city ;
                          $res['lat']=$record->latitude ;
                          $res['lng']=$record->longitude ;
                        }
                      break ;
    case "GeoIP_mod" ://http://dev.maxmind.com/geoip/geolite#Downloads-5
                      $record = geoip_record_by_name($IP);
                      if (_sizeof($record))
                      { $res['country']=$record['country_code3'] ;
                        $res['city']=$record['city'] ;
                        $res['lat']=$record['latitude'] ;
                        $res['lng']=$record['longitude'] ;
                      }
                      break ;
    case "ipGeoBase": //http://blog.ipgeobase.ru/?p=76
                      $res=ipGeoBase($IP) ;
                      break ;
  }
  return($res) ;

}

function ipGeoBase($IP)
{ if (_sizeof($GLOBALS['ipgeobase_cache'][$IP])) return($GLOBALS['ipgeobase_cache'][$IP]) ;
  $cont=file_get_contents('http://ipgeobase.ru:7020/geo?ip='.$IP) ;
  $rec=array() ;
  $dom = new DomDocument();
   if ($dom->loadXML($cont))
    { $objs_xml=$dom->getElementsByTagName("ip");
      if (_sizeof($objs_xml)) foreach ($objs_xml as $obj_xml) foreach($obj_xml->childNodes as $prop_xml) $rec[$prop_xml->nodeName]=trim($prop_xml->nodeValue) ;
    }
  $GLOBALS['ipgeobase_cache'][$IP]=$rec ;
  return($rec) ;
}


class HZip
{
  /**
   * Add files and sub-directories in a folder to zip file.
   * @param string $folder
   * @param ZipArchive $zipFile
   * @param int $exclusiveLength Number of text to be exclusived from the file path.
   */
  private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
    $handle = opendir($folder);
    while (false !== $f = readdir($handle)) {
      if ($f != '.' && $f != '..')
      { $filePath = "$folder/$f";
        //echo '$filePath='.$filePath.'<br>' ;
        // Remove prefix from file path before add to zip.
        $localPath = substr($filePath, $exclusiveLength);
        //echo $localPath.'<br>' ;
        if (is_file($filePath)) $zipFile->addFile($filePath, $localPath);
        elseif (is_dir($filePath))
        { // Add sub-directory.
          $zipFile->addEmptyDir($localPath);
          self::folderToZip($filePath, $zipFile, $exclusiveLength);
        }
      }
    }
    closedir($handle);
  }

  /**
   * Zip a folder (include itself).
   * Usage:
   *   HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip');
   *
   * @param string $sourcePath Path of directory to be zip.
   * @param string $outZipPath Path of output zip file.
   */
  public static function zipDir($sourcePath, $outZipPath,$options=array())
  { $pathInfo = pathInfo($sourcePath);
    $parentPath = $pathInfo['dirname'];
    $dirName = $pathInfo['basename'];
    $exslude_dir=($options['no_include_root_dir'])? $parentPath.'/'.$dirName:$parentPath.'/' ;

    $z = new ZipArchive();
    $z->open($outZipPath, ZIPARCHIVE::CREATE);
    if (!$options['no_include_root_dir']) $z->addEmptyDir($dirName);
    self::folderToZip($sourcePath, $z, strlen($exslude_dir));
    $z->close();
  }
}


function Zip($source, $destination, $include_dir = false)
{

    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    if (file_exists($destination)) {
        unlink ($destination);
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }
    $source = str_replace('\\', '/', realpath($source));

    if (is_dir($source) === true)
    {

        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        if ($include_dir) {

            $arr = explode("/",$source);
            $maindir = $arr[count($arr)- 1];

            $source = "";
            for ($i=0; $i < count($arr) - 1; $i++) {
                $source .= '/' . $arr[$i];
            }

            $source = substr($source, 1);

            $zip->addEmptyDir($maindir);

        }

        foreach ($files as $file)
        {
            $file = str_replace('\\', '/', $file);

            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                continue;

            $file = realpath($file);

            if (is_dir($file) === true)
            {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            }
            else if (is_file($file) === true)
            {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    }
    else if (is_file($source) === true)
    {
        $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
}

/** * mb_ucfirst - преобразует первый символ в верхний регистр * @param string $str - строка * @param string $encoding - кодировка, по-умолчанию UTF-8 * @return string */
if (!function_exists('mb_ucfirst') && extension_loaded('mbstring')) {  function mb_ucfirst($str, $encoding='UTF-8') { $str = mb_ereg_replace('^[\ ]+', '', $str); $str = mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding). mb_substr($str, 1, mb_strlen($str), $encoding); return $str; } }

//
//	Strangely, PHP doesn't have a mb_str_replace multibyte function
//	As we'll only ever use this function with UTF-8 characters, we can simply "hard-code" the character set
//
if ((!function_exists('mb_str_replace')) &&
	(function_exists('mb_substr')) && (function_exists('mb_strlen')) && (function_exists('mb_strpos'))) {
	function mb_str_replace($search, $replace, $subject) {
		if(is_array($subject)) {
			$ret = array();
			foreach($subject as $key => $val) {
				$ret[$key] = mb_str_replace($search, $replace, $val);
			}
			return $ret;
		}

		foreach((array) $search as $key => $s) {
			if($s == '') {
				continue;
			}
			$r = !is_array($replace) ? $replace : (array_key_exists($key, $replace) ? $replace[$key] : '');
			$pos = mb_strpos($subject, $s, 0, 'UTF-8');
			while($pos !== false) {
				$subject = mb_substr($subject, 0, $pos, 'UTF-8') . $r . mb_substr($subject, $pos + mb_strlen($s, 'UTF-8'), 65535, 'UTF-8');
				$pos = mb_strpos($subject, $s, $pos + mb_strlen($r, 'UTF-8'), 'UTF-8');
			}
		}
		return $subject;
	}
}
