<?PHP
if( ! defined( 'DATALIFEENGINE' ) ) {die( "Hacking attempt!" );}

require_once SYSTEM_DIR . '/classes/cache.class.php';
$cache = new cache($dir = ROOT_DIR . '/cache');

function mksize($bytes) {
    if ($bytes < 1000)
        return $bytes. " b";
    if ($bytes < 1000 * 1024)
        return number_format($bytes / 1024, 2) . " Kb";
    if ($bytes < 1000 * 1048576)
        return number_format($bytes / 1048576, 2) . " Mb";
    if ($bytes < 1000 * 1073741824)
        return number_format($bytes / 1073741824, 2) . " Gb";
    if ($bytes < 1000 * 1099511627776)
        return number_format($bytes / 1099511627776, 2) . " Tb";
    if ($bytes < 1000 * 1125899906842620)
        return number_format($bytes / 1125899906842620, 2) . " Pb";
    if ($bytes < 1000 * 1152921504606850000)
        return number_format($bytes / 1152921504606850000, 2) . " Eb";
}

class microTimer {
	function start() {
		global $starttime;
		$mtime = microtime();
		$mtime = explode( ' ', $mtime );
		$mtime = $mtime[1] + $mtime[0];
		$starttime = $mtime;
	}
	function stop() {
		global $starttime;
		$mtime = microtime();
		$mtime = explode( ' ', $mtime );
		$mtime = $mtime[1] + $mtime[0];
		$endtime = $mtime;
		$totaltime = round( ($endtime - $starttime), 5 );
		return $totaltime;
	}
}

function totranslit( $var, $lower = true, $punkt = true ) {
    global $langtranslit;

   	if ( is_array($var) ) return "";
    if (!is_array ( $langtranslit ) OR !count( $langtranslit ) ) {
   	$langtranslit = array('а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'e', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch', 'ь' => '', 'ы' => 'y', 'ъ' => '', 'э' => 'e', 'ю' => 'yu', 'я' => 'ya', "ї" => "yi", "є" => "ye",
                          'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ё' => 'E', 'Ж' => 'Zh', 'З' => 'Z', 'И' => 'I', 'Й' => 'Y', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O', 'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C', 'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sch', 'Ь' => '', 'Ы' => 'Y', 'Ъ' => '', 'Э' => 'E', 'Ю' => 'Yu', 'Я' => 'Ya', "Ї" => "yi", "Є" => "ye",);
    }

   	$var = trim( strip_tags( $var ) );
   	$var = preg_replace( "/\s+/ms", "-", $var );
   	$var = str_replace( "/", "-", $var );

   	$var = strtr($var, $langtranslit);

    if( $punkt ) {$var = preg_replace( "/[^a-z0-9\_\-.]+/mi", "", $var );}else{$var = preg_replace( "/[^a-z0-9\_\-]+/mi", "", $var );}

	$var = preg_replace( '#[\-]+#i', '-', $var );

	if( $lower ) {$var = strtolower( $var );}

    $var = str_ireplace( ".php", "", $var );
   	$var = str_ireplace( ".php", ".ppp", $var );

    if( strlen( $var ) > 50 ) {
   		$var = substr( $var, 0, 50 );
   		if( ($temp_max = strrpos( $var, '-' )) ) $var = substr( $var, 0, $temp_max );
   	}
	return $var;
}

function langdate($format, $stamp) {
	global $langdate;
	return strtr( @date( $format, $stamp ), $langdate );
}

function mcdate($format, $stamp) {
    global $langdate, $config;
    $today = strtotime(date("Y-m-d.", time()+ ($config['date_adjust']*60)));
    if ($stamp > $today) return "" . date ("H:i:s", $stamp);
    elseif ($stamp > ($today - 86400)) return "". date ("H:i:s", $stamp);
    else return strtr(date($format, $stamp), $langdate);
}

function msgbox($title, $text) {
	global $tpl;
	$tpl_2 = new dle_template( );
	$tpl_2->dir = TEMPLATE_DIR;
	$tpl_2->load_template( 'info.tpl' );
	$tpl_2->set( '{error}', $text );
	$tpl_2->set( '{title}', $title );
	$tpl_2->compile( 'info' );
	$tpl_2->clear();
	$tpl->result['info'] .= $tpl_2->result['info'];
}

function ShortRating($id, $rating, $allow = true) {
 global $config, $lang;

 if ($rating) $rating = round($rating, 0); else $rating = 0;
if ($rating > 0) $rating = "<font color=\"green\">".$rating."</font>"; elseif ($rating == 0) $rating="".$rating."</font>"; else $rating = "<font color=\"red\">".$rating."</font>";

 if (!$allow) {
  $rated = <<<HTML
 <div id="ratig-layer">
   <img src="/templates/default/images/down_off.png" alt="Не нравится(-)" border="0"  style="cursor:hand; border:0; vertical-align:middle;" />
        <a href="#" class="vote_link" onclick="voted_list({$id}); return false;">{$rating}</a>
   <img src="/templates/default/images/up_off.png" alt="Нравится(+)" border="0"  style="cursor:hand; border:0; vertical-align:middle;" />
</div>
HTML;
 return $rated;
}

$rated = "<span id=\"ratig-layer-" . $id . "\">";
$rated .= <<<HTML
 <div id="ratig-layer">
<a href="#" title="Нравится(+)" alt="Не нравится(-)" class="r2-unit" onclick="Rate('-1', '{$id}', '1'); return false;">
   <img src="{THEME}/images/down.png" alt="Не нравится(-)" border="0" style="cursor:hand; border:0; vertical-align:middle;"/>
</a>
    <a href="#" class="vote_link" onclick="voted_list({$id}); return false;">{$rating}</a>
<a href="#" title="Нравится(+)" alt="Нравится(+)" class="r2-unit" onclick="Rate('1', '{$id}', '1'); return false;">
   <img src="{THEME}/images/up.png" alt="Нравится(+)" border="0" style="cursor:hand; border:0; vertical-align:middle;"/>
</a>
 </div>
HTML;

$rated  .= "</span>";
 return $rated;
}

function CommRating ($id, $commrating, $allow = true){
global $is_logged, $member_id, $config, $lang, $db;

if ($commrating) $commrating = round($commrating, 0); else $commrating = 0;

switch($commrating) {
case ($commrating >= 0):
$commrating = '<span style="color: #009900;">+'.$commrating.'</span>';
break;
case ($commrating <= 0):
$commrating = '<span style="color: #FF0000;">'.$commrating.'</span>';
break;
case($commrating == 0):
$commrating = '<span style="color: #000000;">'.$commrating.'</span>';
break;
}
if (!$allow) {

$commrated = <<<HTML
<span id="cratig-layer-{$id}">
<img title="Поддерживаю" src="/templates/default/images/comm_up_off.gif" border="0" align="middle" style="padding-bottom:5px; padding-right:5px;">
{$commrating}
<img title="Не поддерживаю" src="/templates/default/images/comm_down_off.gif" border="0" align="middle" style="padding-bottom:5px; padding-left:5px; padding-right:5px;">
</span>
HTML;

return $commrated;
}

$commrated .= <<<HTML
<span id="cratig-layer-{$id}">
<a href="#" title="+" class="r2-unit" onclick="Rate('+1', '{$id}', '2'); return false;"><img title="Поддерживаю" src="{THEME}/images/comm_up.gif" border="0" align="middle" style="padding-bottom:5px; padding-right:5px;"></a>
{$commrating}
<a href="#" title="-" class="r1-unit" onclick="Rate('-1', '{$id}', '2'); return false;"><img title="Не поддерживаю" src="{THEME}/images/comm_down.gif" border="0" align="middle" style="padding-bottom:5px; padding-left:5px; padding-right:5px;"></a>
</span>
HTML;

return $commrated;
}

function CategoryNewsSelection($categoryid = 0, $parentid = 0, $nocat = TRUE, $sublevelmarker = '', $returnstring = '') {
	global $cat_info, $user_group, $member_id;
	
	$allow_list = explode( ',', $user_group[$member_id['user_group']]['allow_cats'] );
	$spec_list = explode( ',', $user_group[$member_id['user_group']]['cat_add'] );

	$root_category = array ();
	
	if( $parentid == 0 ) {if( $nocat ) $returnstring .= '<option value="0"></option>';
	} else {$sublevelmarker .= '&nbsp;&nbsp;&nbsp;';}
	
	if( count( $cat_info ) ) {

		foreach ( $cat_info as $cats ) {if( $cats['parentid'] == $parentid ) $root_category[] = $cats['id'];}
		
		if( count( $root_category ) ) {
			foreach ( $root_category as $id ) {
				
				if( $allow_list[0] == "all" or in_array( $id, $allow_list ) ) {
					
					if( $spec_list[0] == "all" or in_array( $id, $spec_list ) ) $color = "black"; else $color = "red";
					
					$returnstring .= "<option style=\"color: {$color}\" value=\"" . $id . '" ';
					
					if( is_array( $categoryid ) ) {
						foreach ( $categoryid as $element ) {if( $element == $id ) $returnstring .= 'SELECTED';
						}} elseif( $categoryid == $id ) $returnstring .= 'SELECTED';
					$returnstring .= '>' . $sublevelmarker . $cat_info[$id]['name'] . '</option>';
				}$returnstring = CategoryNewsSelection( $categoryid, $id, $nocat, $sublevelmarker, $returnstring );
	}}}
	return $returnstring;
}

// Ajax категорий
function CategoryNewsSelectioh(){
	global $cat_info;
	foreach ($cat_info as $ccccc){
		$aaaaa = $ccccc['parentid'];
		if ($aaaaa == '0'){
			$returnstring .= "<option value=\"" . $ccccc['id'] . '" ';
			$returnstring .= '>' . $cat_info[$ccccc['id']]['name'] . '</option>';
	}}
	return $returnstring;
	}

function CategoryNewsSelectiod($idd){
	global $cat_info;
	$retng = "<select name=\"catlist[]\">";
	foreach ($cat_info as $ccccd){
		$aaaab = $ccccd['parentid'];
		if ($aaaab == $idd){$retng .= '<option value="' . $ccccd['id'] . '">' . $cat_info[$ccccd['id']]['name'] . '</option>';}
	}$retng .= "</select>";
	return $retng;
	}
// Ajax категорий

function get_ID($cat_info, $category) {
	foreach ( $cat_info as $cats ) {if( $cats['alt_name'] == $category ) return $cats['id'];}
	return false;
}

function filesize_url($url) {
	return ($data = @file_get_contents( $url )) ? strlen( $data ) : false;
}

function ChangeSkin($dir, $skin) {
	$templates_list = array ();
	$handle = opendir( $dir );
	while ( false !== ($file = readdir( $handle )) ) {
		if( @is_dir( "./templates/$file" ) and ($file != "." AND $file != ".." AND $file != "smartphone") ) {
			$templates_list[] = $file;
	}}
	closedir( $handle );
	sort($templates_list);
	$skin_list = "<form method=\"post\" action=\"\"><select onchange=\"submit()\" name=\"skin_name\">";
	foreach ( $templates_list as $single_template ) {
		if( $single_template == $skin ) $selected = " selected=\"selected\""; else $selected = "";
		$skin_list .= "<option value=\"$single_template\"" . $selected . ">$single_template</option>";
	}
	$skin_list .= '</select><input type="hidden" name="action_skin_change" value="yes" /></form>';
	return $skin_list;
}

function check_ip($ips) {
	$_IP = $_SERVER['REMOTE_ADDR'];
	$blockip = FALSE;
	if( is_array( $ips ) ) {
		foreach ( $ips as $ip_line ) {
			$ip_arr = rtrim( $ip_line['ip'] );
			$ip_check_matches = 0;
			$db_ip_split = explode( ".", $ip_arr );
			$this_ip_split = explode( ".", $_IP );
			
			for($i_i = 0; $i_i < 4; $i_i ++) {
				if( $this_ip_split[$i_i] == $db_ip_split[$i_i] or $db_ip_split[$i_i] == '*' ) {$ip_check_matches += 1;
			}}
			
			if( $ip_check_matches == 4 ) {
				$blockip = $ip_line['ip'];
				break;
		}}}
	return $blockip;
}

function check_netz($ip1, $ip2) {
	$ip1 = explode( ".", $ip1 );
	$ip2 = explode( ".", $ip2 );
	if( $ip1[0] != $ip2[0] ) return false;
	if( $ip1[1] != $ip2[1] ) return false;
	return true;
}

function show_file ($story, $id, $static = false){
	global $db, $config, $lang, $user_group, $member_id;
	
	if ($static){
		if (is_array ($id) and count ($id)) $where = "static_id IN (" . implode (",", $id) . ")";
		else $where = "static_id = '".intval($id)."'";
		
		$db->query ("SELECT id, name, onserver, dcount FROM " . PREFIX . "_static_files WHERE $where");
		$area = "&amp;area=static";
	}else{
		if (is_array ($id) and count ($id)) $where = "news_id IN (" . implode (",", $id) . ")";
		else $where = "news_id = '".intval($id)."'";
		
		$db->query ("SELECT id, name, onserver, dcount FROM " . PREFIX . "_files WHERE $where");
		$area = "";
	}
	
	while ($row = $db->get_row ()){
		$size = mksize (@filesize (ROOT_DIR . '/uploads/files/' . $row['onserver']));
		$row['name'] = explode ("/", $row['name']);
		$row['name'] = end ($row['name']);

        $find_1[] = '[file=' . $row['id'] . ']';
      	$find_2[] = "#\[file={$row['id']}:(.+?)\]#i";
		
		if (!$user_group[$member_id['user_group']]['allow_files']){
            $replace_1[] = "<span class=\"attachment\">{$lang['att_denied']}</span>";
         	$replace_2[] = "<span class=\"attachment\">{$lang['att_denied']}</span>";
        }else{
            $replace_1[] = "<span class=\"attachment\"><a href=\"{$config['http_home_url']}system/file.php?id={$row['id']}{$area}\" >{$row['name']}</a> [{$size}] ({$lang['att_dcount']} {$row['dcount']})</span>";
         	$replace_2[] = "<span class=\"attachment\"><a href=\"{$config['http_home_url']}system/file.php?id={$row['id']}{$area}\" >\\1</a> [{$size}] ({$lang['att_dcount']} {$row['dcount']})</span>";
        }
	}
    $db->free();
   	$story = str_replace ( $find_1, $replace_1, $story );
   	$story = preg_replace( $find_2, $replace_2, $story );
   	return $story;
}

function show_torrent ($story, $id){
	global $db, $config, $user_group, $member_id, $tpl;

	if (is_array($id) AND count($id))$where = "news_id IN (".implode(",", $id).")";
	else $where = "news_id = '".intval($id)."'";

	$db->query("SELECT * FROM " . PREFIX . "_torrents WHERE $where");

	while($row = $db->get_row()){

		$tpl->load_template('torrent.tpl');

		$file_size =	mksize(@filesize ( ROOT_DIR . '/uploads/torrents/' . $row['onserver'] ));
		$size = mksize($row['size']);
		$hash = bin2hex($row['info_hash']);
		if ($row['seeders']=='0') $seeders = 'Сиды будут получены при закачке'; else $seeders = $row['seeders'];
		if (!$user_group[$member_id['user_group']]['allow_files']) $link=""; else $link = "{$config['http_home_url']}download.php?id={$row['id']}'";

		$tpl->set('{rowid}', $row['id']);
		$tpl->set('{name}', $row['name']);
		$tpl->set('{downs}', $row['dcount']);
		$tpl->set('{complited}', $row['completed']);
		$tpl->set('{seeders}', $seeders);
		$tpl->set('{leechers}', $row['leechers']);
		$tpl->set('{hash}', $hash);
		$tpl->set('{size}', $size);
		$tpl->set('{file_size}', $file_size);
		$tpl->set('{link}', $link);
		//$tpl->set('{torrent_files}', $spisokfile );


		$tpl->compile('torrent');
		$show = $tpl->result['torrent'] ;
		$tpl->clear();

		$story = str_replace( '[torrent='. $row['id'] .']', $show, $story );
	}
	$db->free();
	return $story;
}

function create_keywords($story) {
	global $metatags;
	
	$keyword_count = 20;
	$newarr = array ();
	
	$quotes = array ("\x22", "\x60", "\t", "\n", "\r", ",", ".", "/", "¬", "#", ";", ":", "@", "~", "[", "]", "{", "}", "=", "-", "+", ")", "(", "*", "^", "%", "$", "<", ">", "?", "!", '"' );
	$fastquotes = array ("\x22", "\x60", "\t", "\n", "\r", '"', "\\", '\r', '\n', "/", "{", "}", "[", "]" );
	
	$story = preg_replace( "'\[hide\](.*?)\[/hide\]'si", "", $story );
	$story = preg_replace( "'\[file=(.*?)\]'si", "", $story );
	$story = preg_replace( "'\[torrent=(.*?)\]'si", "", $story );
	$story = str_replace( "&nbsp;", " ", $story );
	
	$story = str_replace( $fastquotes, '', trim( strip_tags( str_replace( '<br />', ' ', stripslashes( $story ) ) ) ) );
	$metatags['description'] = substr( $story, 0, 190 );
	$story = str_replace( $quotes, '', $story );
	$arr = explode( " ", $story );
	foreach ( $arr as $word ) {if( strlen( $word ) > 4 ) $newarr[] = $word;}
	
	$arr = array_count_values( $newarr );
	arsort( $arr );
	
	$arr = array_keys( $arr );
	$total = count( $arr );
	$offset = 0;
	$arr = array_slice( $arr, $offset, $keyword_count );
	$metatags['keywords'] = implode( ", ", $arr );
}

function allowed_ip($ip_array) {
	$ip_array = trim( $ip_array );
	if( $ip_array == "" ) {return true;}
	$ip_array = explode( "|", $ip_array );
	$db_ip_split = explode( ".", $_SERVER['REMOTE_ADDR'] );
	
	foreach ( $ip_array as $ip ) {
		$ip_check_matches = 0;
		$this_ip_split = explode( ".", trim( $ip ) );
		for($i_i = 0; $i_i < 4; $i_i ++) {
			if( $this_ip_split[$i_i] == $db_ip_split[$i_i] or $this_ip_split[$i_i] == '*' ) {
				$ip_check_matches += 1;
		}}if( $ip_check_matches == 4 ) return true;
	}return FALSE;
}

function news_permission($id) {
	if( $id == "" ) return;
	$data = array ();
	$groups = explode( "|", $id );
	foreach ( $groups as $group ) {
		list ( $groupid, $groupvalue ) = explode( ":", $group );
		$data[$groupid] = $groupvalue;
	}return $data;
}

function get_sub_cats($id, $subcategory = '') {
	global $cat_info;
	$subfound = array ();
	if( $subcategory == '' ) $subcategory = $id;
	foreach ( $cat_info as $cats ) {if( $cats['parentid'] == $id ) {$subfound[] = $cats['id'];}}
	foreach ( $subfound as $parentid ) {
		$subcategory .= "|" . $parentid;
		$subcategory = get_sub_cats( $parentid, $subcategory );
	}return $subcategory;
}

function check_xss() {
	
	$url = html_entity_decode( urldecode( $_SERVER['QUERY_STRING'] ) );
    $url = str_replace( "\\", "/", $url );
	
	if( $url ) {
		if( (strpos( $url, '<' ) !== false) || (strpos( $url, '>' ) !== false) || (strpos( $url, '"' ) !== false) || (strpos( $url, './' ) !== false) || (strpos( $url, '../' ) !== false) || (strpos( $url, '\'' ) !== false) || (strpos( $url, '.php' ) !== false) ) {
		if( $_GET['do'] != "search" or $_GET['subaction'] != "search" ) die( "Hacking attempt!" );
	}}
	
	$url = html_entity_decode( urldecode( $_SERVER['REQUEST_URI'] ) );
    $url = str_replace( "\\", "/", $url );
	
	if( $url ) {
		if( (strpos( $url, '<' ) !== false) || (strpos( $url, '>' ) !== false) || (strpos( $url, '"' ) !== false) || (strpos( $url, '\'' ) !== false) ) {
		if( $_GET['do'] != "search" or $_GET['subaction'] != "search" ) die( "Hacking attempt!" );
	}}
}

function check_category($cats, $block, $category, $action = true) {
    $cats = str_replace(" ", "", $cats );
   	$cats = explode( ',', $cats );
   	$category = explode( ',', $category );
   	$found = false;
	
	foreach ( $category as $element ) {
		if( $action ) {
			if( in_array( $element, $cats ) ) {$block = str_replace( '\"', '"', $block ); return $block;}
        } else {
      		if( in_array( $element, $cats ) ) {$found = true;}
      	}}
    if ( !$action AND !$found ) {$block = str_replace( '\"', '"', $block  ); return $block;}
   	return "";
}

function clean_url($url) {
	if( $url == '' ) return;
	
    $url = str_replace( "http://", "", strtolower( $url ) );
   	$url = str_replace( "https://", "", $url );
	if( substr( $url, 0, 4 ) == 'www.' ) $url = substr( $url, 4 );
	$url = explode( '/', $url );
	$url = reset( $url );
	$url = explode( ':', $url );
	$url = reset( $url );
	
	return $url;
}

function get_url($id) {
	global $cat_info;
	if( ! $id ) return;
	
	$parent_id = $cat_info[$id]['parentid'];
	$url = $cat_info[$id]['alt_name'];
	
	while ( $parent_id ) {
		$url = $cat_info[$parent_id]['alt_name'] . "/" . $url;
		$parent_id = $cat_info[$parent_id]['parentid'];
		if( $cat_info[$parent_id]['parentid'] == $cat_info[$parent_id]['id'] ) break;
	}
	return $url;
}

function get_categories($id) {
	global $cat_info, $config, $PHP_SELF;
	if( ! $id ) return;
	
	$parent_id = $cat_info[$id]['parentid'];
	$list = "<a href=\"" . $config['http_home_url'] . get_url( $id ) . "/\">{$cat_info[$id]['name']}</a>";
	
	while ( $parent_id ) {
		$list = "<a href=\"" . $config['http_home_url'] . get_url( $parent_id ) . "/\">{$cat_info[$parent_id]['name']}</a>" . " &raquo; " . $list;
		$parent_id = $cat_info[$parent_id]['parentid'];
		if( $cat_info[$parent_id]['parentid'] == $cat_info[$parent_id]['id'] ) break;
	}
	return $list;
}

$domain_cookie = explode (".", clean_url( $_SERVER['HTTP_HOST'] ));
$domain_cookie_count = count($domain_cookie);
$domain_allow_count = -2;

if ( $domain_cookie_count > 2 ) {
	if ( in_array($domain_cookie[$domain_cookie_count-2], array('com', 'net', 'org') )) $domain_allow_count = -3;
	if ( $domain_cookie[$domain_cookie_count-1] == 'ua' ) $domain_allow_count = -3;
	$domain_cookie = array_slice($domain_cookie, $domain_allow_count);
}

$domain_cookie = "." . implode (".", $domain_cookie);

if( ip2long($_SERVER['HTTP_HOST']) != -1 AND ip2long($_SERVER['HTTP_HOST']) !== FALSE ) define( 'DOMAIN', null );
else define( 'DOMAIN', $domain_cookie );

function set_cookie($name, $value, $expires) {
	if( $expires ) {$expires = time() + ($expires * 86400);
	} else {$expires = FALSE;}
	
	if( PHP_VERSION < 5.2 ) {setcookie( $name, $value, $expires, "/", DOMAIN . "; HttpOnly" );
	} else {setcookie( $name, $value, $expires, "/", DOMAIN, NULL, TRUE );}
}

function news_sort($do) {
	global $config, $lang;
	if( ! $do ) $do = "main";
	
	$find_sort = "dle_sort_" . $do;
	$direction_sort = "dle_direction_" . $do;
	
	$find_sort = str_replace( ".", "", $find_sort );
	$direction_sort = str_replace( ".", "", $direction_sort );
	
	$sort = array ();
	$allowed_sort = array ('date', 'rating', 'news_read', 'comm_num', 'title' );
	
	$soft_by_array = array (
	    'date' => array ('name' => $lang['sort_by_date'], 'value' => "date", 'direction' => "desc", 'image' => "" ),
	    'rating' => array ('name' => $lang['sort_by_rating'], 'value' => "rating", 'direction' => "desc", 'image' => "" ),
	    'news_read' => array ('name' => $lang['sort_by_read'], 'value' => "news_read", 'direction' => "desc", 'image' => "" ),
	    'comm_num' => array ('name' => $lang['sort_by_comm'], 'value' => "comm_num", 'direction' => "desc", 'image' => "" ),
	    'title' => array ('name' => $lang['sort_by_title'], 'value' => "title", 'direction' => "desc", 'image' => "" )
	 );

	if( $_SESSION[$direction_sort] == "desc" or $_SESSION[$direction_sort] == "asc" ) $direction = $_SESSION[$direction_sort];  else $direction = $config['news_msort'];
	if( $_SESSION[$find_sort] and in_array( $_SESSION[$find_sort], $allowed_sort ) ) $soft_by = $_SESSION[$find_sort];  else $soft_by = $config['news_sort'];
	
	if( strtolower( $direction ) == "asc" ) {
		$soft_by_array[$soft_by]['image'] = "<img src=\"{THEME}/images/asc.gif\" alt=\"\" />";
		$soft_by_array[$soft_by]['direction'] = "desc";
	} else {
		$soft_by_array[$soft_by]['image'] = "<img src=\"{THEME}/images/desc.gif\" alt=\"\" />";
		$soft_by_array[$soft_by]['direction'] = "asc";
	}
	
	foreach ( $soft_by_array as $value ) {$sort[] = $value['image'] . "<a href=\"#\" onclick=\"news_change_sort('{$value['value']}','{$value['direction']}'); return false;\">" . $value['name'] . "</a>";}
	$sort = "<form name=\"news_set_sort\" id=\"news_set_sort\" method=\"post\" action=\"\" >" . implode( " | ", $sort );
	
$sort .= <<<HTML
    <input type="hidden" name="dlenewssortby" id="dlenewssortby" value="{$config['news_sort']}" />
    <input type="hidden" name="dledirection" id="dledirection" value="{$config['news_msort']}" />
    <input type="hidden" name="set_new_sort" id="set_new_sort" value="{$find_sort}" />
    <input type="hidden" name="set_direction_sort" id="set_direction_sort" value="{$direction_sort}" />
HTML;
	return $sort;
}

function comm_sort(){
	global $config;
	if (isset($_SESSION['dle_comm_sort']) and ($_SESSION['dle_comm_sort'] == "DESC" or $_SESSION['dle_comm_sort'] == "ASC")){
	    $conf_comm_msort = $_SESSION['dle_comm_sort'];
	}else{$conf_comm_msort = $config['comm_msort'];}
	if ($conf_comm_msort == "ASC"){
		$value_image = '<img src="{THEME}/images/asc.gif" />';
		$value_sorts = "DESC";
		}else{
		$value_image = '<img src="{THEME}/images/desc.gif" />';
		$value_sorts = "ASC";
		}

	$sort = <<<HTML
<form name="comm_set_sort" id="comm_set_sort" method="post" action="">
{$value_image}<a href="#" onClick="comm_change_sort('{$value_sorts}'); return false;">дата</a>
<input type="hidden" name="dle_comm_sort" id="dle_comm_sort" value="{$value_sorts}" />
</form>
HTML;
	return $sort;
}

function compare_tags($a, $b) {
	if( $a['tag'] == $b['tag'] ) return 0;
	return strcasecmp( $a['tag'], $b['tag'] );
}

function convert_unicode($t, $to = 'windows-1251') {
	$to = strtolower( $to );

	if( $to == 'utf-8' ) {
        return $t;
	} else {
		if( function_exists( 'mb_convert_encoding' ) ) {
			$t = mb_convert_encoding( $t, $to, "UTF-8" );
		}elseif( function_exists( 'iconv' ) ){
			$t = iconv( "UTF-8", $to . "//IGNORE", $t );
		}
		else $t = "The library iconv is not supported by your server";
	}
	return $t;
}

function check_smartphone() {
    if ( $_SESSION['mobile_enable'] ) return true;
    $phone_array = array('iphone', 'android', 'pocket', 'palm', 'windows ce', 'windowsce', 'mobile windows', 'cellphone', 'opera mobi', 'operamobi', 'ipod', 'small', 'sharp', 'sonyericsson', 'symbian', 'symbos', 'opera mini', 'nokia', 'htc_', 'samsung', 'motorola', 'smartphone', 'blackberry', 'playstation portable', 'tablet browser', 'android');
	$agent = strtolower( $_SERVER['HTTP_USER_AGENT'] );

	foreach ($phone_array as $value) {if ( strpos($agent, $value) !== false ) return true;}
	return false;
}

function comm_hide ($hide,$comm){
    global $member_id,$is_logged;
    if (!$is_logged)
        return "<div class=\"quote\">Внимание! У вас нет прав для просмотра скрытого текста.</div>";
        else if (intval($member_id["comm_num"])>=intval($hide)) return "<div class=\"quote\">".$comm."</div>";
        else return "<div class=\"quote\">Для просмотра скрытого текста необходимо набрать <b>" . $hide . "</b> комментариев.<br />У вас <b>".$member_id["comm_num"]."</b> (осталось <b>".(intval($hide)-intval($member_id["comm_num"]))."</b>)</div>";
}

function group_hide($group, $text){
    global $member_id, $is_logged, $user_group;
    if (!$is_logged)
        return "<div class=\"quote\">Внимание! У вас нет прав для просмотра скрытого текста.</div>";
        else if (intval($member_id['user_group']) >= intval($group)) return "<div class=\"quote\">".$text."</div>";
        else return "<div class=\"quote\">Просмотр скрытого текста возможен только пользователям группы <b>" . $user_group[$group]['group_name'] . "</b></div>";
}

function CreateNavigation( $url, $page, $total, $tpl = "navigation.tpl", $result = "content" ){
    if(!$Navigation){
        require SYSTEM_DIR . '/classes/navigation.class.php';
        $Navigation = new Navigation;
    }
	$Navigation->URL = $url;
	$Navigation->Page = $page;
	$Navigation->Total = $total;
	$Navigation->Tpl = $tpl;
	$Navigation->Compile = $result;

	$Navigation->BuildNavigation();
}

function stag () {
$with_us = round( ( time() - $GLOBALS['row']['reg_date']) / 86400);
if ($with_us > 0){
    $count_days=1;
    $y1="год";$y2="года";$y3="лет";$m1="месяц";$m2="месяцa";$m3="месяцев";$d1="день";$d2="дня";$d3="дней";
    $with_us_year = floor($with_us / 365);

if ($with_us_year >= 1){
if ($with_us_year == 1) $after_y = $y1;
if ($with_us_year > 1 && $with_us_year < 5) $after_y = $y2;
if ($with_us_year > 4) $after_y = $y3;
$years = $with_us_year." ".$after_y;
$with_us = $with_us - ($years * 365);
$count_days=0;
}
$with_us_month = floor($with_us / 31);
if ($with_us_month >= 1){
    if ($with_us_month == 1) $after_m = $m1;
    if ($with_us_month > 1 && $with_us_month < 5) $after_m = $m2;
    if ($with_us_month > 4) $after_m = $m3;
    $monthes = $with_us_month." ".$after_m;
    $with_us = $with_us - ($monthes * 31);
    if ($with_us_month > 6) $count_days=0;
    if ($with_us_month == 12) {$years = ($with_us_year+1)." ".$y1;$with_us_month=$monthes=''; }
}
if ($count_days == 1){
if ($with_us > 0){
    if ($with_us == 1 || $with_us == 21 || $with_us == 31) $after_d = $d1;
    if ($with_us > 1 && $with_us < 5) $after_d = $d2;
    if ($with_us > 4 && $with_us < 21) $after_d = $d3;
    if ($with_us > 21 && $with_us < 25) $after_d = $d2;
    if ($with_us > 24 && $with_us < 31) $after_d = $d3;
    $days = $with_us." ".$after_d;
}}
$stag = $years." ".$monthes." ".$days;
unset($years); unset($monthes); unset($days);
return $stag;
}
$stag = 0;
return $stag;
}

function json_decode_from_class( $content, $ass = FALSE ) {
  require_once SYSTEM_DIR.'/classes/JSON.php';
  if ($ass) {$json = new Services_JSON( SERVICES_JSON_LOOSE_TYPE );
  } else {$json = new Services_JSON;}
  return $json->decode($content);
}
?>