Просмотр файла inc/func.php

Размер файла: 30.85Kb
<?
#-----------------------------------------------------#
#          ********* TerrinCMS *********              #
#              Made by  :  Terrin                     #
#               E-mail  :  [email protected]           #
#             WAP-Site  :  http://lorinz.ru           #
#                  ICQ  :  344-20-52                  #
#  Вы не имеете право вносить изменения в код скрипта #
#        для его дальнейшего распространения          #
#-----------------------------------------------------#
# ----------------------------------- Функция показа заголовка ----------------------------------- #
function show_title($title){
echo'<title>'.$title.'</title>';
}
# ----------------------------------- Функция подсчета онлайна ----------------------------------- #
function online_user(){
$online_user = mysql_query("SELECT count(*) FROM `session_user`;");
$raw = mysql_fetch_row($online_user);
$totel = $raw[0];
return $totel;
}
function online_ghost(){
$online_ip = mysql_query("SELECT count(*) FROM `session`;");
$row = mysql_fetch_row($online_ip);
$total = $row[0];
# ----------------------------------- Функция правельного окончания для гостей ----------------------------------- #
function user($value)
{
 $x = $value % 10;
 if (($x == 1) && ($value != 11)) $s = 'гость';
 elseif ((($x > 1) && ($x < 5)) && (floor($value / 10) != 1)) $s = 'гостя'; else $s = 'гостей';
 return $s;
}
return $total.' '.user($total); 
}
# ----------------------------------- Функция правельного окончания для денег  ----------------------------------- #
function money($value)
{
 $x = $value % 10;
 if (($x == 1) && ($value != 11)) $s = 'рубль';
 elseif ((($x > 1) && ($x < 5)) && (floor($value / 10) != 1)) $s = 'рубля'; else $s = 'рублей';
 return $s;
}
//--------------- Функция рейтинга пользователей -------------------//
function rating($login){
$rez = mysql_query("select * from `users` where login = '".$login."'");
$rez = mysql_fetch_assoc($rez);
//-------   Расчет рейтинга   --------//
$level = $rez['level'];
$exp = $rez['exp'];
$rating = $exp;
//-------- LEVEL UP -------------//
if($rating > 100){$rating = 100; } else { $rating = $rating; }
if($rating == 100){mysql_query("UPDATE `users` SET `level`=`level` + 1,`exp`='0' WHERE login = '".$login."'");}
$r =  '<img src="/core/rating.php?img=' . $rating . '" alt="Рейтинг ' . $rating . '" />';
return $r;
}
function rating_plus($login,$exp){
$rez = mysql_query("select * from `users` where login = '".$login."'");
$rez = mysql_fetch_assoc($rez);
//-------   Расчет рейтинга   --------//
$level = $rez['level'];
if($level == 0){ $rating = $exp;  } 
if($level == 1){ $rating = $exp / 5;  } 
if($level == 2){ $rating = $exp / 10;  } 
if($level == 3){ $rating = $exp / 15;  } 
if($level == 4){ $rating = $exp / 20;  } 
if($level == 5){ $rating = $exp / 25;  } 
if($level == 6){ $rating = $exp / 30;  } 
if($level == 7){ $rating = $exp / 35;  } 
if($level == 8){ $rating = $exp / 40;  } 
if($level == 9){ $rating = $exp / 50;  } 
if($level == 10){ $rating = $exp / 60;  } 
if($level > 10 && $level < 50 ){ $rating = $exp / 65;  } 
if($level > 50 && $level < 100 ){ $rating = $exp / 75;  } 
if($level > 100 && $level < 150 ){ $rating = $exp / 85;  } 
if($level > 150 && $level < 200 ){ $rating = $exp / 90;  } 
if($level > 200){ $rating = $exp / 100;  } 
mysql_query("UPDATE `users` SET `exp`=`exp` + $rating WHERE login = '".$login."'");
}
# ----------------------------------- Функция генерации пароля ----------------------------------- #
function gen_code($number){  
session_start();
$arr = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','r','s','t','u','v','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','R','S','T','U','V','X','Y','Z','1','2','3','4','5','6','7','8','9','0');  
// Генерируем пароль  
$pass = "";  
for($i = 0; $i < $number; $i++){  
// Вычисляем случайный индекс массива  
$index = rand(0, count($arr) - 1);  
$pass .= $arr[$index];  
}  
$_SESSION['gener'] = $pass;
} 
//----------- Транслит -------------//
function translite($text) {
return str_replace( 
array('YO','Yo','ZH','Zh','CH','Ch','SHC','SHc','Shc','SH', 
'Sh','YE','Ye','YU','Yu','YA','Ya','ch','sh','shc','ye','yu', 
'ya','yo ','zh','A','B','V','G','D','E','Z','I','Y','K','L', 
'M','N','O','P','R' ,'S','T','U','F','H','C','X','a','b','v', 
'g','d','e','z','i','y','k',' l','m','n','o','p','r','s','t', 
'u','f','h','c','x','""','"',"''","'"), 
array('Ё','Ё','Ж','Ж','Ч','Ч','Щ','Щ','Щ','Ш','Ш','Э','Э','Ю', 
'Ю','Я', 'Я','ч','ш','щ','э','ю','я','ё','ж','A','Б','В','Г', 
'Д','E','З','И','Й ','К','Л','М','Н','О','П','Р','С','Т','У', 
'Ф','Х','Ц','Ы','а','б','в', 'г','д','е','з','и','й','к','л', 
'м','н','о','п','р','с','т','у','ф','х ','ц','ы','Ъ','ъ','Ь', 
'ь'),$text); 
}
//-------- АНТИМАТ ---------//
function antimat($string) { 
$query = mysql_query("SELECT * FROM `antimat`"); 
while($row = mysql_fetch_assoc($query)) 
$string = str_replace($row['mat_string'], '***', $string); 
     
return $string; 
}
//--------------- Функция прибавления актива -------------------//
function activ($login){
$rez = mysql_query("select * from `users` where login = '".$login."';");
$rez = mysql_fetch_assoc($rez);
$activ = $rez['activ'];
mysql_query("UPDATE `users` SET `activ`=`activ` + 1,`hero`=`hero` + 1 WHERE login = '".$login."';");
}
function smesh($activ,$money,$login){
$rez = mysql_query("select * from `users` where login = '".$login."';");
$rez = mysql_fetch_assoc($rez);
$m = $rez['money'] + $money;
$a = $rez['activ'] + $activ;
mysql_query("UPDATE `users` SET `money`='$m',`activ`='$a' WHERE login = '".$login."'");
}
# ----------------------------------- Функция времени ----------------------------------- #
function formattime($file_time){
if($file_time >= 86400){
$file_time = round((($file_time / 60) / 60) / 24).' д.';
}elseif(
$file_time >= 3600){
$file_time = round(($file_time / 60) / 60, 1).' ч.';
}elseif(
$file_time >= 60){
$file_time = round($file_time / 60).' мин.';
}else{
$file_time = ''.round($file_time).' сек.';}
return $file_time;
}
# ----------------------------------- Функция фильтации данных ----------------------------------- #
function check($msg) {
	if (is_array($msg)) {
		foreach($msg as $key => $val) {
			$msg[$key] = check($val);
		} 
	} else {
		$msg = htmlspecialchars($msg);
		$search = array('|', '\'', '$', '\\', '^', '%', '`', "\0", "\x00", "\x1A", chr(226) . chr(128) . chr(174));
		$replace = array('&#124;', '&#39;', '&#36;', '&#92;', '&#94;', '&#37;', '&#96;', '', '', '', '');

		$msg = str_replace($search, $replace, $msg);
		$msg = stripslashes(trim($msg));
	} 

	return $msg;
} 
# ----------------------------------- Функция подсчета символов ----------------------------------- #
function utf_strlen($str) {
	if (function_exists('mb_strlen')) return mb_strlen($str, 'utf-8');
	if (function_exists('iconv_strlen')) return iconv_strlen($str, 'utf-8');
	if (function_exists('utf8_decode')) return strlen(utf8_decode($str));
	return strlen(utf_to_win($str));
} 
# ----------------------------------- Функция смайлов ----------------------------------- #
function smiles($string) { 
    $query = mysql_query("SELECT * FROM `smiles` WHERE `smiles_cats`='1'"); 
     
    while($row = mysql_fetch_assoc($query)) 
        $string = str_replace($row['smiles_code'], '<img src="/images/smiles/' . $row['smiles_name'] . '" alt="' . $row['smiles_code'] . '" />', $string); 
     
$login = $_COOKIE['login'];	 
if($login == !NULL){
$li =mysql_query("SELECT * FROM users WHERE `login`='$login';");
$li = mysql_fetch_assoc($li);	 
$status = $li['status'];
if($status == 101 || $status == 102 || $status == 103 || $status == 104){	 
    $query = mysql_query("SELECT * FROM `smiles` WHERE `smiles_cats`='2'"); 
     
    while($row = mysql_fetch_assoc($query)) 
        $string = str_replace($row['smiles_code'], '<img src="/images/smiles2/' . $row['smiles_name'] . '" alt="' . $row['smiles_code'] . '" />', $string); 

}	 }
    return mysql_real_escape_string($string); 
}
# ----------------------------------- Функция без пробелов ----------------------------------- #
function no_br($msg) {
	$msg = nl2br($msg);
	$msg = preg_replace('|[\r\n]+|si', '', $msg);
	return $msg;
} 
# ----------------------------------- Функция вывода рекламы ----------------------------------- #
function reclama_index() {
$link = $_SERVER['REQUEST_URI'];
if($link == '/?mode=index'){
$rec = mysql_query("select * from `reclama` WHERE gde = 'index';");
#########
$uu= mysql_query("SELECT count(*) FROM `reclama` WHERE gde = 'index'");
$mm = mysql_fetch_row($uu);
$renn = $mm[0];
#########
if($renn >= 1){ $it = '<div class="menu">
<div style="overflow: hidden"><div style="float: left"></div><div align="right"><img src="/images/adv.png"></div></div>'; $tm = '</div>'; } else {$it = NULL; $tm = NULL; }
echo $it;
while($r = mysql_fetch_assoc($rec)){
if($r['color'] == NULL){ $a = NULL; $b = NULL;  }else{ $a = '<font color="'.$r['color'].'">'; $b = '</font>';   }
if($r['g'] == 0){ $c = NULL; $v = NULL; } else { $c = '<strong>'; $v = '</strong>';  }
if($r['real_count'] < $r['max_count']){
echo'» <a href="/users/go.php?url='.$r['name'].'">'.$a.''.$c.''.$r['opi'].''.$v.''.$b.'</a><br />';
}//
}//
echo $tm;
}///
}////
function open($url) {  
$curl = curl_init(); 
curl_setopt($curl, CURLOPT_URL, $url); 
curl_setopt($curl, CURLOPT_USERAGENT, 'NokiaN73-1' ); 
curl_setopt($curl, CURLOPT_AUTOREFERER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl); 
curl_close($curl); 
if(!$result){ 
exit('Ошибка.<br />' );  
} 
    return $result;  
} 
function reclama_all() {
$rec = mysql_query("select * from `reclama` WHERE gde = 'all';");
#########
$uu= mysql_query("SELECT count(*) FROM `reclama` WHERE gde = 'all'");
$mm = mysql_fetch_row($uu);
$renn = $mm[0];
#########
if($renn >= 1){ $it = '<div class="menu"><div style="overflow: hidden"><div style="float: left"></div><div align="right"><img src="/images/adv.png"></div></div>'; $tm = '</div>'; } else {$it = NULL; $tm = NULL; }
echo $it;
while($r = mysql_fetch_assoc($rec)){
if($r['color'] == NULL){ $a = NULL; $b = NULL;  }else{ $a = '<font color="'.$r['color'].'">'; $b = '</font>';   }
if($r['g'] == 0){ $c = NULL; $v = NULL; } else { $c = '<strong>'; $v = '</strong>';  }
if($r['real_count'] < $r['max_count']){
echo'» <a href="/users/go.php?url='.$r['name'].'">'.$a.''.$c.''.$r['opi'].''.$v.''.$b.'</a><br />';
}//
}//
echo $tm;
}////
# ----------------------------------- Функция убирания смайлов ----------------------------------- #
function nosmiles($string) {
	$string = preg_replace('|<img src="/images/smiles/(.*?)\.gif" alt="(.*?)" /> |', ':$1', $string);
    $string = preg_replace('|<img src="/images/smiles/(.*?)\.gif" alt="(.*?)" />|', ':$1', $string);
	$string = preg_replace('|<img src="/images/smiles2/(.*?)\.gif" alt="(.*?)" /> |', ':$1', $string);
	return $string;
} 
# ----------------------------------- Функция полного удаления юзера ----------------------------------- #
function del_user($login) {
mysql_query('DELETE FROM `friend` WHERE `kto` = "'.$login.'"');
mysql_query('DELETE FROM `history_ban` WHERE `login` = "'.$login.'"');
mysql_query('DELETE FROM `ignor` WHERE `kto` = "'.$login.'"');
mysql_query('DELETE FROM `note` WHERE `login` = "'.$login.'"');
mysql_query('DELETE FROM `reclama` WHERE `name` = "'.$login.'"');
mysql_query('DELETE FROM `users` WHERE `login` = "'.$login.'"');
mysql_query('DELETE FROM `vote_golos` WHERE `login` = "'.$login.'"');
mysql_query('DELETE FROM `wall` WHERE `my_login` = "'.$login.'"');
mysql_query('DELETE FROM `news_kom` WHERE `login` = "'.$login.'"');
mysql_query('DELETE FROM `book` WHERE `nik` = "'.$login.'"');
mysql_query('DELETE FROM `chat_msg` WHERE `login` = "'.$login.'"');
mysql_query('DELETE FROM `drug` WHERE `my_login` = "'.$login.'"');
mysql_query('DELETE FROM `drug` WHERE `send_login` = "'.$login.'"');
mysql_query('DELETE FROM `forum_topic` WHERE `login` = "'.$login.'"');
mysql_query('DELETE FROM `news_kom` WHERE `login` = "'.$login.'"');
mysql_query('DELETE FROM `rating` WHERE `my_login` = "'.$login.'"');
mysql_query('DELETE FROM `rating` WHERE `send_login` = "'.$login.'"');
mysql_query('DELETE FROM `dating` WHERE `login` = "'.$login.'"');
mysql_query('DELETE FROM `diary_cat` WHERE `login` = "'.$login.'"');
mysql_query('DELETE FROM `diary_note` WHERE `login` = "'.$login.'"');
mysql_query('DELETE FROM `diary_com` WHERE `login` = "'.$login.'"');
} 
# ----------------------------------- Функция бб тегов ----------------------------------- #
function bb($msg) {
	$msg = str_replace('[nextpage]', '<br>', $msg);
	$msg = preg_replace('#\[code\](.*?)\[/code\]#ie', 'highlight_code("\1")', $msg);
	$msg = preg_replace('#\[hide\](.*?)\[/hide\]#ie', 'hidden_text("\1")', $msg);
//	$msg = preg_replace_callback('~\[url=((https?|ftp)://.+?)\](.+?)\[/url\]|((https?|ftp)://[0-9a-zа-яё/.;?=\(\)\_\-&%#]+)~ui', 'url_replace', $msg);  
	$msg = preg_replace('#\[big\](.*?)\[/big\]#si', '<big>\1</big>', $msg);
	$msg = preg_replace('#\[b\](.*?)\[/b\]#si', '<b>\1</b>', $msg);
	$msg = preg_replace('#\[i\](.*?)\[/i\]#si', '<i>\1</i>', $msg);
	$msg = preg_replace('#\[u\](.*?)\[/u\]#si', '<u>\1</u>', $msg);
	$msg = preg_replace('#\[small\](.*?)\[/small\]#si', '<small>\1</small>', $msg);
	$msg = preg_replace('#\[red\](.*?)\[/red\]#si', '<span style="color:#ff0000">\1</span>', $msg);
	$msg = preg_replace('#\[green\](.*?)\[/green\]#si', '<span style="color:#00cc00">\1</span>', $msg);
	$msg = preg_replace('#\[blue\](.*?)\[/blue\]#si', '<span style="color:#0000ff">\1</span>', $msg);
	$msg = preg_replace('#\[q\](.*?)\[/q\]#si', '<div class="q">\1</div>', $msg);
	$msg = preg_replace('#\[del\](.*?)\[/del\]#si', '<del>\1</del>', $msg);
    $msg = preg_replace('#\[url=(.*?)\](.*?)\[/url\]#si', '<a href="/pages/go_url.php?url=\1">\2</a>', $msg);

	return $msg;
}
function url_replace($m) {
	global $config;

	if (!isset($m[4])) {
		$target = (strpos($m[1], $config['home']) === false) ? ' target="_blank"' : '';
		return '<a href="'.$m[1].'"'.$target.'>'.check(rawurldecode(html_entity_decode($m[3], ENT_QUOTES, 'utf-8'))).'</a>';
	} else {
		$target = (strpos($m[4], $config['home']) === false) ? ' target="_blank"' : '';
		return '<a href="'.$m[4].'"'.$target.'>'.check(rawurldecode(html_entity_decode($m[4], ENT_QUOTES, 'utf-8'))).'</a>';
	} 
} 
# ----------------------------------- Функция подсчета строк в бд ----------------------------------- #
function index($start) {
$inj = mysql_query("SELECT count(*) FROM $start");
$utf = mysql_fetch_row($inj);
$result = $utf[0];
return $result;
}
function last_news() {
$news=mysql_query("SELECT * FROM `news` ORDER BY `id` DESC LIMIT 1");  
$news = mysql_fetch_assoc($news);
return $news['data'];
}
function index_to($start,$where,$login) {
$oq= mysql_query("SELECT count(*) FROM $start WHERE $where ='".$login."'");
$rq = mysql_fetch_row($oq);
$result = $rq[0];
return $result;
}
# ----------------------------------- Функция вывода героя дня ----------------------------------- #
function hero_day($num) {
echo'<div class="menu">
Анкета дня<hr>';
$g=mysql_query("SELECT * FROM `users` ORDER BY `hero` DESC LIMIT $num");  
while($u=mysql_fetch_array($g)){ 
if($u['hero'] > 0){
if($u['avatar_mini'] == NULL){ $avatar ='/images/noavatar.gif'; } else {$avatar = ''.$u['avatar_mini'].'';}
if($u['pol'] == 1){$img = '<img src="'.IMG.'user.m.png">'; } else { $img = '<img src="'.IMG.'user.w.png">';}
$p = mysql_query('SELECT * FROM session_user WHERE user = "'.$u['login'].'"');
if(mysql_num_rows($p) != 0){ $on ='[<font color="green">On</font>]'; } else { $on ='[<font color="red">Off</font>]'; }
echo'<div style="overflow: hidden"><div style="float: left"><img src="'.$avatar.'"></div> <a href="/users/profile.php?user='.$u['login'].'">'.$u['login'].'</a> '.$img.' <img src="/images/medal/hero/hero_day.png" title="Анкета дня"><br />
Актив за сегодня: '.$u['hero'].' '.$on.'</div>';
} else { echo'Лидер еще не нашелся :('; }
}
echo'</div>';

}
//Функция для вывода инфы о проценте сжатия и др.
function info_compress()
{
   global $method, $step;
   
   $contents = ob_get_contents();
   // Сколько весит исходная страница
   $in = strlen($contents);
   
   switch($method)
   {
      default:
      echo'Сжатие не поддерживается';//<br>
      break;
      
      case 'deflate':
      $out = strlen(gzdeflate($contents, $step));
      
      echo 'Сжатие: '.round(100-(100/($in/$out)),1).' %';
      break;
      
      case 'gzip':
      $out = strlen(gzencode($contents, $step));
      
      echo 'Сжатие: '.round(100-(100/($in/$out)),1).' %';
      break;
      
      case 'x-gzip':
      $out = strlen(gzcompress($contents, $step));
      
      echo 'Сжатие: '.round(100-(100/($in/$out)),1).' %';
      break;
   }
   
   return;
}
# ----------------------------------- Функция вывода тем на главную ----------------------------------- #
function forum_index($num){
if($num > 0){
 $g=mysql_query("SELECT * FROM `forum_topic`  GROUP BY `topic` ORDER BY `id` DESC LIMIT $num");  
while($u=mysql_fetch_array($g)){ 
$z = mysql_query("select * from `forum_themes` where `id` = '".$u['topic']."' GROUP BY `themes`");
$z = mysql_fetch_assoc($z);
$q=mysql_result(mysql_query("SELECT COUNT(*) FROM `forum_topic` WHERE topic = '".$u['topic']."'"),0);  
$total = intval(($q - 1) / 10) + 1;  
if($z['krep'] == 1){ $img = '<img src="/images/forum/lock.gif" alt="">';} else {if($z['status'] == 'on'){$img = '<img src="/images/forum/topics.gif" alt=""> ';} else {$img = '<img src="/images/forum/closed.gif" alt="">';} }
echo''.$img.' <a href="/forum/?mode=topic&themes='.$u['themes'].'&id='.$z['id'].'&page='.$total.'">'.$z['themes'].'</a> ['.index_to('forum_topic','topic',$u['topic']).']<br />';
}
}
}
# ----------------------------------- Функция показа меделей ----------------------------------- #
function medal($login){
$img = '/images/medal/';
$hero = 'hero/';
$post = 'post/';
$level = 'level/';
$s =mysql_query("SELECT * FROM users WHERE `login`='".$login."'");
$s = mysql_fetch_assoc($s);
echo'<a href="/pages/medal.php">Медали:</a> ';
//--------------------- Анкета Дня --------------------//
$g=mysql_query("SELECT * FROM `users` ORDER BY `hero` DESC LIMIT 1");  
$g = mysql_fetch_assoc($g);
if($g['login'] == $login && $g['hero'] > 0){ echo'<img src="'.$img.''.$hero.'hero_day.png" title="Анкета дня"> ';}
//--------------------- За посты --------------------//
if($s['activ'] >= 250){ echo' <img src="'.$img.''.$post.'1.png" title="Набрал(а) 250 постов!"> '; }
if($s['activ'] >= 500){ echo' <img src="'.$img.''.$post.'2.png" title="Набрал(а) 500 постов!"> ';}
if($s['activ'] >= 1000){ echo' <img src="'.$img.''.$post.'3.png" title="Набрал(а) 1000 постов!"> ';}
if($s['activ'] >= 2000){ echo' <img src="'.$img.''.$post.'4.png" title="Набрал(а) 2000 постов!"> ';}
if($s['activ'] >= 4000) {echo' <img src="'.$img.''.$post.'5.png" title="Набрал(а) 4000 постов!"> ';}
if($s['activ'] >= 6000){echo' <img src="'.$img.''.$post.'6.png" title="Набрал(а) 6000 постов!"> ';}
if($s['activ'] >= 8000){echo' <img src="'.$img.''.$post.'7.png" title="Набрал(а) 8000 постов!"> ';}
if($s['activ'] >= 10000){echo' <img src="'.$img.''.$post.'8.png" title="Набрал(а) 10000 постов!"> ';}
if($s['activ'] >= 15000){echo' <img src="'.$img.''.$post.'9.png" title="Набрал(а) 15000 постов!"> ';}
//--------------------- За уровни --------------------//
if($s['level'] >= 1){ echo' <img src="'.$img.''.$level.'1.png" title="За достижение 1 уровня"> '; }
if($s['level'] >= 5){ echo' <img src="'.$img.''.$level.'2.png" title="За достижение 5 уровня"> ';}
if($s['level'] >= 10){echo' <img src="'.$img.''.$level.'3.png" title="За достижение 10 уровня"> ';}
if($s['level'] >= 50){echo' <img src="'.$img.''.$level.'4.png" title="За достижение 50 уровня"> ';}
if($s['level'] >= 100){echo' <img src="'.$img.''.$level.'5.png" title="За достижение 100 уровня"> ';}
if($s['level'] >= 150){echo' <img src="'.$img.''.$level.'6.png" title="За достижение 150 уровня"> ';}
if($s['level'] >= 200){echo' <img src="'.$img.''.$level.'7.png" title="За достижение 200 уровня"> ';}




}
/**  Функция перевода размера  **/
function formatsize($file_size) {
	if ($file_size >= 1048576000) {
		$file_size = round(($file_size / 1073741824), 2)." Gb";
	} elseif ($file_size >= 1024000) {
		$file_size = round(($file_size / 1048576), 2)." Mb";
	} elseif ($file_size >= 1000) {
		$file_size = round(($file_size / 1024), 2)." Kb";
	} else {
		$file_size = round($file_size)." byte";
	} 
	return $file_size;
} 
/**  Функция чтения папки и вывод веса в байтах   **/
function read_dir($dir) {
	if (empty($allsize)) {
		$allsize = 0;
	} 

	if ($path = opendir($dir)) {
		while ($file_name = readdir($path)) {
			if (($file_name !== '.') && ($file_name !== '..')) {
				if (is_dir($dir."/".$file_name)) {
					$allsize += read_dir($dir."/".$file_name);
				} else {
					$allsize += filesize($dir."/".$file_name);
				} 
			} 
		} 
		closedir ($path);
	} 
	return $allsize;
} 
# ----------------------------------- Функция  подсчета файлов для обменека----------------------------------- #
function catalog($it) {
if($it == 'apli'){
$q=mysql_result(mysql_query("SELECT COUNT(*) FROM `files` WHERE type='jar' OR type='jad' OR type='sis' OR type='sisx' OR  type='apk' OR type='exe'"),0);  
return $q;
}
if($it == 'java'){
$w=mysql_result(mysql_query("SELECT COUNT(*) FROM `files` WHERE type='jar' OR type='jad'"),0);  
return $w;
}
if($it == 'symbian'){
$e=mysql_result(mysql_query("SELECT COUNT(*) FROM `files` WHERE  type='sis' OR type='sisx'"),0); 
return $e; 
}
if($it == 'android'){
$r=mysql_result(mysql_query("SELECT COUNT(*) FROM `files` WHERE type='apk'"),0);  
return $r;
}
if($it == 'windows'){
$t=mysql_result(mysql_query("SELECT COUNT(*) FROM `files` WHERE type='exe'"),0);  
return $t;
}
if($it == 'music'){
$y=mysql_result(mysql_query("SELECT COUNT(*) FROM `files` WHERE  type='mp3' OR type='wma' OR type='flac' OR type='aac' OR type='mmf' OR type='amr' OR type='m4a' OR type='m4r' OR type='ogg' OR type='mp2' OR type='wav'"),0); 
return $y; 
}
if($it == 'video'){
$f=mysql_result(mysql_query("SELECT COUNT(*) FROM `files` WHERE type='mp4' OR type='avi' OR type='3gp' OR type='rmvb' OR type='wmv' OR type='mkv' OR type='mpg' OR type='mov' OR type='vob' OR type='flv'"),0);
return $f;  
}
if($it == 'images'){
$i=mysql_result(mysql_query("SELECT COUNT(*) FROM `files` WHERE type='jpg' OR type='jpeg' OR type='swf' OR type='png' OR type='ico' OR type='bmp' OR type='gif' OR type='tif' OR type='pcx' OR type='tga'"),0);  
return $i;
}
if($it == 'doc'){
$o=mysql_result(mysql_query("SELECT COUNT(*) FROM `files` WHERE type='txt' OR type='doc' OR type='docx' OR type='pdf'"),0);  
return $o;
}
if($it == 'arhiv'){
$p=mysql_result(mysql_query("SELECT COUNT(*) FROM `files` WHERE  type='zip' OR type='7z' OR type='rar'"),0);
return $p;  
}
}
function other() {
$file = explode(",", file_get_contents('../moduls/obmen/other.txt'));
$where = ''; // это будущее условие
$all = count($file)-1; // всего форматов
$i = 0; // счетчик
foreach($file as $value){ // разбираем масси
     $value = trim($value);
     if($value != ''){ // да бы не попалась пустота
         $where .= "`type` = '{$value}' "; // Дополняем переменную
         if($i != $all) $where .= 'OR '; // если это не последняя запись добавляем OR
     }
     $i++;
}
	 
	 $a=mysql_result(mysql_query("SELECT COUNT(*) FROM `files` WHERE $where"),0);  
return $a;
}
# ----------------------------------- Функция смены регистра ----------------------------------- #
function regist($str){ 
$strold=array("Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M"); # что заменять 
$strnew=array("q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m"); # на что заменять 
$str=str_replace($strold, $strnew, $str);
return $str;
}
# ----------------------------------- Функция удаления дневника ----------------------------------- #
function diary($id) {
mysql_query('DELETE FROM `diary_cat` WHERE `id` = "'.$login.'"');
mysql_query('DELETE FROM `diary_note` WHERE `id_diary_cat` = "'.$login.'"');
mysql_query('DELETE FROM `diary_com` WHERE `id_diaru` = "'.$id.'"');
} 
# ----------------------------------- Функция отправки письма ----------------------------------- #
function addmail($mail, $subject, $messages, $sendermail="", $sendername="") {

	if (empty($sendermail)) {
		$sendermail = '[email protected]';
		$sendername = 'Admin TerrinCMS';
	} 

/* 	
	$subject = utf_to_win($subject);
	$messages = utf_to_win($messages);
	$sendername = utf_to_win($sendername);

	$subject = convert_cyr_string($subject, 'w', 'k');
	$messages = convert_cyr_string($messages, 'w', 'k');
	$sendername = convert_cyr_string($sendername, 'w', 'k'); 

	$subject = '=?KOI8-R?B?'.base64_encode($subject).'?=';
*/

	$subject = '=?UTF-8?B?'.base64_encode($subject).'?=';

	$adds = "From: =?UTF-8?B?".base64_encode($sendername)."?= <".$sendermail.">\n";
	$adds .= "X-sender: =?UTF-8?B?".base64_encode($sendername)."?= <".$sendermail.">\n";
	$adds .= "Content-Type: text/plain; charset=utf-8\n";
	$adds .= "MIME-Version: 1.0\n";
	$adds .= "Content-Transfer-Encoding: 8bit\n";
	$adds .= "X-Mailer: PHP v.".phpversion()."\n";
	$adds .= "Date: ".date("r")."\n";

	return mail($mail, $subject, $messages, $adds);
} 
# ----------------------------------- Функция проверки юзера ----------------------------------- #
function is_user(){
$login = check($_COOKIE['login']);
$pass = check($_COOKIE['pass']);
$pri = NULL;
$login_in = mysql_query('SELECT * FROM users WHERE login = "'.$_COOKIE['login'].'"');
$login_in = mysql_fetch_assoc($login_in);
if(!empty($login_in['login']) && !empty($login_in['pass'])){
if($pass == $login_in['pass'] && $login = $login_in['login']){
$pri = $login;
}
}
return $pri;
}
# ----------------------------------- Функция проверки администатора ----------------------------------- #
function is_admin($access = array()) {
	if (empty($access)) {
		$access = array(101, 102, 103, 104);
	} 

	if (is_user()) {
$login_in = mysql_query('SELECT * FROM users WHERE login = "'.$_COOKIE['login'].'"');
$login_in = mysql_fetch_assoc($login_in);
		if (in_array($login_in['status'], $access)) {
			return true;
		} 
	} 

	return false;
}
function site_verification(){

echo'<div class="menu">';
$file = file_get_contents('http://cms.lorinz.ru/site/'.$_SERVER['HTTP_HOST'].'.php');
include('../inc/vet.php');
if($file == NULL){
$view = open('http://cms.lorinz.ru/site/free_ver.php' );
echo'<span style="color:#ff0000">Бесплатная версия ('.$my_ver.'.0)</span><br />';
if($view > $my_ver){echo'<a href="http://cms.lorinz.ru/cms.php"><span style="color:#ff0000">Доступна новая версия '.$view.'</span></a>'; }
} else {
$view = open('http://cms.lorinz.ru/site/ver.php' );
echo'<span style="color:#00cc00">Лицензионная версия ('.$my_ver.'.0)</span><br />';
if($view > $my_ver){echo'<a href="http://cms.lorinz.ru/cms.php"><span style="color:#ff0000">Доступна новая версия '.$view.'</span></a>'; }
}
echo'</div>';

}
function site_cron(){
$d = date("d"); $m = date("m"); 
$cron = file_get_contents('inc/last_cron.txt');//получаем данные
$exp = explode('||',$cron);
if($cron == NULL || $d > $exp[0] && $m == $exp[1]){
if($d == $exp[0]){} else {
#   Очиска анкеты дня     #
$g=mysql_query("SELECT * FROM `users`");  
while($u=mysql_fetch_array($g)){ 
mysql_query("UPDATE `users` SET `hero`=0 WHERE id = '".$u['id']."'");
}
#  Обновление Хитов / хостов     #
$rec = mysql_query("select * from `statistic` WHERE `id`= '1'");
$rec = mysql_fetch_assoc($rec);
$hit = $rec['hits']; $host = $rec['host'];
mysql_query("UPDATE `statistic` SET `hits_today`='$hit',`host_today`='$host' WHERE 1");
#  Обновление Рекламы     #
$tem = mysql_query("SELECT count(*) FROM `reclama`;"); $zcv = mysql_fetch_row($tem); $tems = $zcv[0];
if($tems >= 1){
$list = mysql_query("select * from `reclama`");
while($shop = mysql_fetch_array($list)) {
$real = $shop['real_count'];  $max = $shop['max_count'];
if($real >= $max){
mysql_query("DELETE FROM `reclama` WHERE id = '".$shop['id']."'");
}
}
}
##################################
/** ----------------  Запись даты крона ----------------------- **/
  $file = fopen ("inc/last_cron.txt","w+");
  $str = "$d||$m";
  if ( !$file ){ echo("Ошибка открытия файла");} else {
  fputs ( $file, $str); }
  fclose ($file);
}
}
############################
#  Удаление Юзеров не потверд. емаил     #
$del_user = mysql_query("select * from `users`");
while($ing = mysql_fetch_array($del_user)) {
if($ing['act_mail'] == 'on'){} else {
if($ing['act_mail_time'] <= time()){
mysql_query("DELETE FROM `users` WHERE id = '".$ing['id']."'");
}
}
}
#  Удаление обьявлений #
$del_cab = mysql_query("select * from `cab_msg`");
while($igen = mysql_fetch_array($del_cab)) {
if($igen['time'] <= time()){
mysql_query("DELETE FROM `cab_msg` WHERE id = '".$igen['id']."'");
}
}
if($d == $exp[0]){} else {
  $file = fopen ("inc/last_cron.txt","w+");
  $str = "$d||$m";
  if ( !$file ){ echo("Ошибка открытия файла");} else {
  fputs ( $file, $str); }
  fclose ($file);

}
############################
}
?>