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

Размер файла: 31.91Kb
<?php
#############################################
# 0JXRgdC70Lgg0YLRiyDRh9C40YLQsNC10YjRjCDRj #
# dGC0L4g0YHQvtC+0LHRidC10L3QuNC1LCDQt9C90L #
# DRh9C40YIg0YLRiyDQvdC10LzQvdC+0LPQviDQt9C #
#          90LDQtdGI0YwgUEhQIQ==            #
#__---------------------------------------__#
#__        0JrQu9C40Log0JrQu9GD0LE=       __#
#  ---------------------------------------  #
# 0JDQstGC0L7RgCA6IE1vcmdhbg==              #
# SUNRIDog0L3QtSDRgdC60LDQttGDIHhE          #
#                                           #
#############################################

//-------------------------- Универсальная функция обрабтки данных --------------------------\\
  function obr($text,$type,$do = NULL)
{
if($type=='string')
  {
$text = mysql_real_escape_string(htmlspecialchars(trim($text),ENT_QUOTES));
  }
elseif($type=='integer')
  {
   $text = abs(intval($text));
  }
if($do) { $text = utf_substr($text,0,$do); }
  return $text;
}
//-------------------------- Функция проверки, в бане ли юзер --------------------------\\
  function is_ban($user_id)
{
global $db;
if(mysql_result(query("SELECT COUNT(*) FROM `$db[prefix]ban` WHERE `who`='$user_id' "),0)>0)
  { return true; }
  else{ return false; }
}
//-------------------------- Функция проверки, в бане ли IP -------------------------\\
  function is_banip($ip)
{
global $db;
if(mysql_result(query("SELECT COUNT(*) FROM `$db[prefix]banip` WHERE `ip`='$ip'"),0)>0)
 { return true; }
 else{ return false; }
}
//-------------------------- Функция красивого вывода даты --------------------------\\
  function formatdate($timestamp = NULL, $format='d M в G:i',$format_month=true,$is_today=true,$echo_week=false)
{
global $sitetime,$config;
if(empty($timestamp))
{
$timestamp = $sitetime;
}

if($config['timestamp']!=0)$timestamp += $config['timestamp']*3600;

if($echo_week==true)
{
$week = array(0=>'Воскресенье',1=>'Понедельник',2=>'Вторник',3=>'Среда',4=>'Четверг',5=>'Пятница',6=>'Суббота');
$format = str_replace('WEEK',$week[date('w')],$format);
}

$date = date($format,$timestamp);
if($is_today==true)
{
$date = str_replace(date('d M',$sitetime),'Сегодня',$date);
$date = str_replace(date('d M',$sitetime-86400),'Вчера',$date);
#echo date('d M',$timestamp);
}


if($format_month==true)
{
$months_eng = array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
$months_rus = array('Января','Февраля','Марта','Апреля','Мая','Июня','Июля','Августа','Сентября','Октября','Ноября','Декабря');
$date = str_replace($months_eng,$months_rus,$date);
}
 return $date;
}
//-------------------------- Функция красивого вывода времени --------------------------\\
  function formattime($time)
{
if($time >= 86400)
{
$time = 'суток: '.round((($time / 60) / 60) / 24, 1);
}elseif(
$time >= 3600)
{
$time = 'часов:  '.round(($time / 60) / 60, 1);
}elseif(
$time >= 60)
{
$time =  'минут: '.round($time / 60);
}else{
$time = 'секунд:  '.round($time);}
  return $time;
}
//-------------------------- Функция красивого вывода размера --------------------------\\
  function formatsize($size)
{
$result = $size;  $size_last = ' б';
if($size >= 1024)
{ $size = round($size/1024,2); $size_last = ' Кб'; }
if($size >= 1024)
{ $size = round($size/1024,2); $size_last = ' Мб';; }
if($size >= 1024)
{ $size = round($size/1024,2); $size_last = ' Гб'; }
if($size >= 1024)
{ $size = round($size/1024,2); $size_last = ' Тб'; }
 return $size.$size_last;
}
//-------------------------- Функция получения логина пользователя по ID --------------------------\\
  function userlogin($user_id,$boid=0,$is_link=0,$type_link=NULL,$view_status=0,$view_online=0)
{
global $config,$db;
$res = query("SELECT login,admin,active FROM `$db[prefix]users` WHERE `id` = '$user_id'");
if(mysql_num_rows($res)==0)return '*без имени*';

$_user = mysql_fetch_array($res);
$login = $_user['login'];


if($view_status == 1 && $_user['active']!=0)
{
if($_user['admin'] == 1)
{ $login = '<font color="'.$config['show_status_color_1'].'">'.$login.'</font>'; }
elseif($_user['admin'] == 2)
{ $login = '<font color="'.$config['show_status_color_2'].'">'.$login.'</font>'; }
elseif($_user['admin'] == 3)
{ $login = '<font color="'.$config['show_status_color_3'].'">'.$login.'</font>'; }
}

if($boid == 1){ $login = '<b>'.$login.'</b>'; }


if($is_link==1)
{
if($type_link == 'admin') { $login = '<a href="/admin/user.php?mode=user&amp;id='.$user_id.'">'.$login.'</a>'; }
elseif($type_link == 'user'  && $_user['active']==1) { $login = '<a href="/menu/private.php?mode=write&amp;to='.$user_id.'">'.$login.'</a>'; }
}

if($type_link != 'private')
{
	if($_user['active']==0)
	{
		$login = '<font color="#000000">'.$login.'</font>';
    }

    if(is_ban($user_id))
    {
    	$login .= '[<font color="#f00000">BAN</font>]';
    }
}








if($view_online == 1)
 {
 global $array_online;
 if(empty($array_online))
  {
  $resonl = query("SELECT id_user FROM `$db[prefix]online` WHERE `id_user`<>'0' ");
  while($reconl = mysql_fetch_array($resonl))$array_online[] = $reconl['id_user'];
  }

 if(count($array_online)>0 && in_array($user_id,$array_online)) $login .= '[<font color="#00f000">On</font>]';
 else $login .= '[<font color="#f00000">Off</font>]';

 }
return $login;
}

//-------------------------- Функция отображения смайлов вместо текста --------------------------\\
  function smiles($text)
{
global $user_prof;
#$cho = array(':)','=)',':-D','%-(',':(',':-(',';)',';-)',':X',':O',':P',':D',':devil:',':ok:',':devil2:',':lol:',':o_O:',':google:',':hack:',':lamer:');
#$na_cho = array(' <img src="/pic/smiles/1.gif"/> ',' <img src="/pic/smiles/2.gif"/> ',' <img src="/pic/smiles/3.gif"/> ',' <img src="/pic/smiles/4.gif"/> ',' <img src="/pic/smiles/5.gif"/> ',' <img src="/pic/smiles/6.gif"/> ',' <img src="/pic/smiles/7.gif"/> ',' <img src="/pic/smiles/8.gif"/> ',' <img src="/pic/smiles/9.gif"/> ',' <img src="/pic/smiles/10.gif"/> ',' <img src="/pic/smiles/11.gif"/> ',' <img src="/pic/smiles/12.gif"/> ',' <img src="/pic/smiles/13.gif"/> ',' <img src="/pic/smiles/14.gif"/> ',' <img src="/pic/smiles/15.gif"/> ','  <img src="/pic/smiles/16.gif"/>  ','  <img src="/pic/smiles/17.gif"/>  ');

$smiles = array();

$dir = opendir(D.'pic/smiles/1/');
 while($sm = readdir($dir))
{
if(strpos($sm,'.gif')!==false)
 {
 $smiles[] = str_replace('.gif','',$sm);
 }
}

#foreach($smiles as $smv)
#{
#$text = str_replace(':'.$smv,'<img src="/pic/smiles/1/'.$smv.'.gif" alt="'.$smv.'"/>',$text);
#}

$count = count($smiles);
for($i = 0;$i < $count; $i++)
{
$text = str_replace(':'.$smiles[$i],'<img src="/pic/smiles/1/'.$smiles[$i].'.gif" alt="'.$smiles[$i].'"/>',$text);
}

$smiles2 = array();

$dir2 = opendir(D.'pic/smiles/2/');
 while($sm2 = readdir($dir2))
{
if(strpos($sm2,'.gif')!==false)
 {
 $smiles2[] = str_replace('.gif','',$sm2);
 }
}

$count2 = count($smiles2);
for($i = 0;$i < $count2; $i++)
{
$text = str_replace(':'.$smiles2[$i],'<img src="/pic/smiles/2/'.$smiles2[$i].'.gif" alt="'.$smiles2[$i].'"/>',$text);
}

#foreach($smiles2 as $smv2)
#{
#$text = str_replace(':'.$smv2,'<img src="/pic/smiles/2/'.$smv2.'.gif" alt="'.$smv2.'"/>',$text);
#}


#$col = count($cho);
# for($i=0;$i<20;$i++)
#{
#$text = str_replace($cho[$i],'<img src="/pic/smiles/1/'.($i+1).'.gif" alt="'.$cho[$i].'"/>',$text);
#}
return $text;
}
//---------------------------------- Функция BB кодов ----------------------------------//
  function bb_code_link($string)
{
# array_dump($string);
if(!empty($string[2]))
 {
 return '<a href="/go.php?go='.base64_encode($string[1]).'&base64=1" title="Страница откроется в новом окне ['.$string[1].']" target="_blank">'.$string[2].'</a>';
 }else
 {
 return '<a href="/go.php?go='.base64_encode($string[3]).'&base64=1" target="_blank">'.$string[3].'</a>';
 }
}

  function bb_code ($string)
{

$string = preg_replace('|\[b](.+)\[\/b]|uUs','<b>$1</b>',$string);
$string = preg_replace('|\[i](.+)\[\/i]|uUs','<i>$1</i>',$string);
$string = preg_replace('|\[u](.+)\[\/u]|uUs','<u>$1</u>',$string);
$string = preg_replace('|\[big](.+)\[\/big]|uUs','<big>$1</big>',$string);
$string = preg_replace('|\[small](.+)\[\/small]|uUs','<small>$1</small>',$string);

$string = preg_replace('|\[red](.+)\[\/red]|uUs','<font color="#f00000">$1</font>',$string);
$string = preg_replace('|\[green](.+)\[\/green]|uUs','<font color="#00f000">$1</font>',$string);
$string = preg_replace('|\[blue](.+)\[\/blue]|uUs','<font color="#0000f0">$1</font>',$string);
$string = preg_replace('|\[yellow](.+)\[\/yellow]|uUs','<font color="#f0f000">$1</font>',$string);


#$string = preg_replace('|\[url=http\:\/\/(.+)](.+)\[/url]|i','<a href="/go.php?go=http://$1" title="Страница откроется в новом окне [$1]" target="_blank">$2</a>',$string);
$string = preg_replace_callback('~\[url=(.+?)\\](.+?)\[/url\]|(http://(www.)?[0-9A-Za-z\.-]+\.[0-9A-Za-z]{2,6}[0-9a-zA-Z/\?\.\~&amp;_=/%-:#]*)~','bb_code_link',$string);


$string = str_replace(array('[b]','[/b]','[i]','[/i]','[u]','[/u]','[big]','[/big]','[small]','[/small]','[red]','[green]','[blue]','[yellow]','[/red]','[/green]','[/blue]','[/yellow]','[url]','[/url]'),'',$string);
 return $string;
}
//-------------------------- Функция `обрезания` --------------------------\\
 function find_cut($string,$arg1,$what)
{
$pos = strpos($string,$arg1);
if($pos !==false)
{
if($what == 'up')
 {return utf_substr($string,0,$pos);}
elseif($what == 'after')
 {return utf_substr($string,$pos+utf_strlen($arg1));}
}else { return $string; }
}
//---------------------------------- Функция оключения графики ----------------------------------//
  function disable_img($image)
{
#$image = preg_replace('|\<img src="\/pic\/smiles\/[1/2]/(.*?)\.gif"\/\>|i',':$1', $image);
#$image = preg_replace('|<img src="/pic/smiles/2/(.*?).gif"/>|',':$1', $image);
#$image = preg_replace('|\<img(.*)(alt="(.*)(_top){0}")?\/\>|uUsi','&#8226;', $image);
  return $image;
}
//---------------------------------- Функция 'моего' md5 хэширования----------------------------------//
 function my_md5($string)
{
global $config;
return md5(str_replace(array('A','Q','R','T','Y','1','2','4','5','a','g'),array('!','@','#','$','%','^','&',')','_','+','|'),md5(md5($string).md5($config['salt']))));
}
//---------------------------------- Функции генерации уникального ID ----------------------------------//
  function gen_id()
{
$r1 = rand(0000000001,9999999999);
#$r2 = rand(0000000001,9999999999);
#$r3 = rand(0000000001,9999999999);
#$r = substr(($r1+$r2+$r3),0,15);
 return $r1;
}
//---------------------------------- Функция перекодировки из UTF в WIN ----------------------------------//
function utf_to_win($str) {

if (function_exists('mb_convert_encoding')) return mb_convert_encoding($str, 'windows-1251', 'utf-8');
if (function_exists('iconv')) return iconv('utf-8', 'windows-1251', $str);

$utf8win1251 = array(
"А"=>"\xC0","Б"=>"\xC1","В"=>"\xC2","Г"=>"\xC3","Д"=>"\xC4","Е"=>"\xC5","Ё"=>"\xA8","Ж"=>"\xC6","З"=>"\xC7","И"=>"\xC8","Й"=>"\xC9","К"=>"\xCA","Л"=>"\xCB","М"=>"\xCC",
"Н"=>"\xCD","О"=>"\xCE","П"=>"\xCF","Р"=>"\xD0","С"=>"\xD1","Т"=>"\xD2","У"=>"\xD3","Ф"=>"\xD4","Х"=>"\xD5","Ц"=>"\xD6","Ч"=>"\xD7","Ш"=>"\xD8","Щ"=>"\xD9","Ъ"=>"\xDA",
"Ы"=>"\xDB","Ь"=>"\xDC","Э"=>"\xDD","Ю"=>"\xDE","Я"=>"\xDF","а"=>"\xE0","б"=>"\xE1","в"=>"\xE2","г"=>"\xE3","д"=>"\xE4","е"=>"\xE5","ё"=>"\xB8","ж"=>"\xE6","з"=>"\xE7",
"и"=>"\xE8","й"=>"\xE9","к"=>"\xEA","л"=>"\xEB","м"=>"\xEC","н"=>"\xED","о"=>"\xEE","п"=>"\xEF","р"=>"\xF0","с"=>"\xF1","т"=>"\xF2","у"=>"\xF3","ф"=>"\xF4","х"=>"\xF5",
"ц"=>"\xF6","ч"=>"\xF7","ш"=>"\xF8","щ"=>"\xF9","ъ"=>"\xFA","ы"=>"\xFB","ь"=>"\xFC","э"=>"\xFD","ю"=>"\xFE","я"=>"\xFF");

return strtr($str, $utf8win1251);
}


//----------------------------------Функция перекодировки из WIN в UTF ----------------------------------//
function win_to_utf($str) {

if (function_exists('mb_convert_encoding')) return mb_convert_encoding($str, 'utf-8', 'windows-1251');
if (function_exists('iconv')) return iconv('windows-1251', 'utf-8', $str);

$win1251utf8 = array(
"\xC0"=>"А","\xC1"=>"Б","\xC2"=>"В","\xC3"=>"Г","\xC4"=>"Д","\xC5"=>"Е","\xA8"=>"Ё","\xC6"=>"Ж","\xC7"=>"З","\xC8"=>"И","\xC9"=>"Й","\xCA"=>"К","\xCB"=>"Л","\xCC"=>"М",
"\xCD"=>"Н","\xCE"=>"О","\xCF"=>"П","\xD0"=>"Р","\xD1"=>"С","\xD2"=>"Т","\xD3"=>"У","\xD4"=>"Ф","\xD5"=>"Х","\xD6"=>"Ц","\xD7"=>"Ч","\xD8"=>"Ш","\xD9"=>"Щ","\xDA"=>"Ъ",
"\xDB"=>"Ы","\xDC"=>"Ь","\xDD"=>"Э","\xDE"=>"Ю","\xDF"=>"Я","\xE0"=>"а","\xE1"=>"б","\xE2"=>"в","\xE3"=>"г","\xE4"=>"д","\xE5"=>"е","\xB8"=>"ё","\xE6"=>"ж","\xE7"=>"з",
"\xE8"=>"и","\xE9"=>"й","\xEA"=>"к","\xEB"=>"л","\xEC"=>"м","\xED"=>"н","\xEE"=>"о","\xEF"=>"п","\xF0"=>"р","\xF1"=>"с","\xF2"=>"т","\xF3"=>"у","\xF4"=>"ф","\xF5"=>"х",
"\xF6"=>"ц","\xF7"=>"ч","\xF8"=>"ш","\xF9"=>"щ","\xFA"=>"ъ","\xFB"=>"ы","\xFC"=>"ь","\xFD"=>"э","\xFE"=>"ю","\xFF"=>"я");

return strtr($str, $win1251utf8);
}
//---------------------------------- Функция подсчета символов для UTF , аналог функции strlen() ----------------------------------//
  function utf_strlen($string)
{
if (function_exists('mb_strlen')) return mb_strlen($string, 'utf-8');
if (function_exists('iconv_strlen')) return iconv_strlen($string, 'utf-8');
return strlen(utf8_decode($string));
}
//---------------------------------- Функция 'обрезания' для UTF , аналог фукнции substr() ----------------------------------//
  function utf_substr($string,$start,$length)
{
if (function_exists('mb_substr')) return mb_substr($string, $start, $length, 'utf-8');
if (function_exists('iconv_substr')) return iconv_substr($string, $start, $length, 'utf-8');

$string=utf_to_win($string);
$string=substr($string,$start,$length);
return win_to_utf($string);

}
//---------------------------------- Функция вывода фильтра ----------------------------------//
  function format_filtr($type)
{
if($type==0) return 'Все';
elseif($type==1) return 'Только мобилы';
elseif($type==2) return 'Только комп';
elseif($type==3) return 'Запрет для мобил';
elseif($type==4) return 'Запрет для компов';


#elseif($type==2) return 'Только Opera Mini';

#elseif($type==5) return 'Запрет для Opera Mini';

else return null;
}
//---------------------------------- Функция вывода типа клика ----------------------------------//
  function formattype_link($type)
{
if($type=='usual') return 'Обычный';
elseif($type=='confirmed') return  'С подтвержденем';
}
//---------------------------------- Функция вывода, проверена ли ссылка ----------------------------------//
  function format_status($status)
{
if($status==0)return '<font color="#000000">Недопущена</font>';
elseif($status==1)return '<font color="#0000f0">На модерации</font>';
elseif($status==2)return '<font color="#f00000">Отключена</font>';
elseif($status==3)return '<font color="#00f000">Активна</font>';
}
//---------------------------------- Функиця для читаемого вывода содржимого массива ----------------------------------//
  function dump($var)
{
echo '<pre>';

if(is_array($var))print_r($var);
else var_dump($var);
echo '</pre>';
}
//---------------------------------- Функция кэширования ----------------------------------//
  function get_cache_return($namefield)
{
global $db;
$result = 0;
mysql_result(query("SELECT COUNT(*) FROM `$db[prefix]cache` WHERE `name`='$namefield' "),0)>0 ? $return = mysql_result(query("SELECT value FROM `$db[prefix]cache` WHERE `name`='$namefield' "),0) :  query("INSERT INTO `$db[prefix]cache` SET `name`='$namefield'");
 return $result;
}

  function get_cache($namefield,$query=NULL,$time_limit=NULL)
{
global $sitetime,$db;

/////////////////////
// Если нам нужно кличество доступных ссылок
/////////////////////
if($namefield=='coldost_links')
{

$res_cache_coldost_links = query("SELECT date,value,name FROM `$db[prefix]cache` WHERE `name`='coldost_links'");
$result = 0;
if(mysql_num_rows($res_cache_coldost_links)>0)
 {
 $_cache = mysql_fetch_array($res_cache_coldost_links);
 if(($_cache['date']+$time_limit)<$sitetime)
  {


//--- Получаем 'хороших'  пользователей
 $good_users = array();
 $res2 = query("SELECT id FROM `$db[prefix]users` WHERE `credits`>'0' AND `active`='1' ");
  while($_user = mysql_fetch_array($res2)) {$good_users[] = $_user['id'];}

# $_cache['value'] = 0;
 $_res_links = query("SELECT user FROM `$db[prefix]sites` WHERE `status` = '3' ");
  while($res_l = mysql_fetch_array($_res_links))
   {
   if(in_array($res_l['user'],$good_users))
    {  $result++;  }
   }
 query("UPDATE `$db[prefix]cache` SET `value`='$result',`date`='$sitetime' WHERE `name`='coldost_links'");

  }else{return $_cache['value'];}
 }else
 {

 //--- Получаем 'хороших'  пользователей
 $good_users = array();
 $res2 = query("SELECT id FROM `$db[prefix]users` WHERE `credits`>'0' AND `active`='1' ");
  while($_user = mysql_fetch_array($res2)) {$good_users[] = $_user['id'];}

# $_cache['value'] = 0;
 $_res_links = query("SELECT user FROM `$db[prefix]sites` WHERE `status` = '3' ");
  while($res_l = mysql_fetch_array($_res_links))
   {
   if(in_array($res_l['id_user'],$good_users))
    {  $result++;  }
   }
 query("INSERT INTO `$db[prefix]cache` SET `name`='coldost_links',`value`='$result',`date`='$sitetime'");
 }

/////////////////////
// А если нет
/////////////////////
}else
{
$res = query("SELECT name,value,date FROM `$db[prefix]cache` WHERE `name`='$namefield'");
if(mysql_num_rows($res)>0)
 {
 $_cached = mysql_fetch_array($res);
 if(($_cached['date']+$time_limit)<$sitetime)
  {
  $result = mysql_result(query($query),0);
  query("UPDATE `$db[prefix]cache` SET `date`='$sitetime',`value`='$result' WHERE `name`='$namefield' ");
  }else{return $_cached['value'];}
 }else
 {
 $result = mysql_result(query($query),0);
 query("INSERT INTO `$db[prefix]cache` SET `name`='$namefield',`date`='$sitetime',`value`='$result' ");
 }
}

  return $result;
}
//---------------------------------- Функция постраничной навигации ----------------------------------//
  function navigator($str,$page,$filename='',$query_string='',$echo_page=true,$get_form=true)
{

if($str<=1)return ;
$query = ($query_string!='') ? $query_string.'&' : '';

echo '<center>
';

if($echo_page==true)echo 'Страница '.$page.' из '.$str.'<br />
';

//-- Начало
if($page>1) { echo '&laquo;<a href="'.$filename.'?'.$query.'page='.($page - 1).'">Назад</a> | '; } else { echo '&laquo;Назад | '; }
if($page<$str ) { echo '<a href="'.$filename.'?'.$query.'page='.($page + 1).'">Далее</a>&raquo; '; } else { echo 'Далее&raquo;'; }
echo '<br />';
//--- Отображение ссылок на страницы
echo 'Страницы : ';
if($page>1) echo '<a href="'.$filename.'?'.$query.'page=1'.'">1</a> ';
if($page>2) echo '<a href="'.$filename.'?'.$query.'page=2'.'">2</a> ';
if($page>3) echo '<a href="'.$filename.'?'.$query.'page=3'.'">3</a> ';

if(($page-3)>3) echo ' ... ';

if(($page-2)>3) echo '<a href="'.$filename.'?'.$query.'page='.($page-2).'">'.($page-2).'</a> ';
if(($page-1)>3) echo '<a href="'.$filename.'?'.$query.'page='.($page-1).'">'.($page-1).'</a> ';

echo '<b>('.$page.')</b>';

if( ($str-($page+1))>1) echo '<a href="'.$filename.'?'.$query.'page='.($page+1).'">'.($page+1).'</a> ';
if( ($str-($page+2))>2) echo '<a href="'.$filename.'?'.$query.'page='.($page+2).'">'.($page+2).'</a> ';

if(($str - ($page+2))>1) echo ' ... ';

if((($str-2)-$page)>2) echo '<a href="'.$filename.'?'.$query.'page='.($str-2).'">'.($str-2).'</a> ';
if((($str-1)-$page)>0) echo '<a href="'.$filename.'?'.$query.'page='.($str-1).'">'.($str-1).'</a> ';
if(($str-$page)>0)  echo '<a href="'.$filename.'?'.$query.'page='.$str.'">'.$str.'</a> ';

if($str>=3 && $get_form==true)
{
echo'<br />
<form action="'.$filename.'?" method="GET">
';

if($query_string!='')
 {
 $array_quers = explode('&',$query_string);
 $count_qurs = count($array_quers);
  for($i=0;$i<$count_qurs;$i++)
 {
 list($name,$value) = explode('=',$array_quers[$i]);
 echo '<input name="'.$name.'" type="hidden" value="'.$value.'">';
 }
}
$strlen_page = utf_strlen($str);
echo '<input name="page" type="text" value="'.$page.'" size="'.$strlen_page.'" maxlength="'.$strlen_page.'"><input type="submit" value="Перейти&gt;&gt;&gt;">
</form>';
}
//-- Конец
echo '</center>
';

}
//---------------------------------- Функция для 'отсеивания' не зареганных юзеров ----------------------------------//
  function only_reg($to='/aut.php?',$refresh=false)
{
global $user_in_site,$user_prof,$_request_uri;
if($user_in_site!=1 || !isset($user_prof))
{
if($refresh==true){$_SESSION['url_refresh']=$_request_uri;}
header('Location:'.$to);
exit;
}

}
//---------------------------------- Функция для правильного окончания слов ----------------------------------//
  function postfix($count,$word1='кредитов',$word2='кредита',$word3='кредит')
{

$count = (int) $count;
if(strlen($count)>2)$count = substr($count,-2);
else { $count = $count;  }
$inp = $word1;
if($count==2||$count==3||$count==4||$count==22||$count==23||$count==24||$count==32||$count==33||$count==34||$count==42||$count==43||$count==44||$count==52||$count==53||$count==54||$count==62||$count==63||$count==64||$count==72||$count==73||$count==74||$count==82||$count==83||$count==84||$count==92||$count==93||$count==94)
{$inp = $word2;}
if($count==1||$count==21||$count==31||$count==41||$count==51||$count==61||$count==71||$count==81||$count==91)
{$inp = $word3;}
  return ' '.$inp;

}
//-------------------------- Функция правилього окончания для кредитов  --------------------------\\
  function credits($credits)
{
$credits = (int) $credits;
if(utf_strlen($credits)>2)$p = substr($credits,-2);
else { $p = $credits;  }
$inp = ' кредитов';
if($p==2||$p==3||$p==4||$p==22||$p==23||$p==24||$p==32||$p==33||$p==34||$p==42||$p==43||$p==44||$p==52||$p==53||$p==54||$p==62||$p==63||$p==64||$p==72||$p==73||$p==74||$p==82||$p==83||$p==84||$p==92||$p==93||$p==94)
{$inp = ' кредита';}
if($p==1||$p==21||$p==31||$p==41||$p==51||$p==61||$p==71||$p==81||$p==91)
{$inp = ' кредит';}
  return $credits.$inp;
}
//---------------------------------- Функция подстветки PHP кода ----------------------------------//
  function highlight($code)
{

$time=time()+rand(111111,999999);
$php_info=ini_get_all();
$inis=array('highlight.html','highlight.default','highlight.keyword','highlight.string','highlight.comment');
$colors=array();
$count_inis = count($inis);
	for($i=0; $i<$count_inis; $i++){
	$colors[]=substr($php_info[$inis[$i]]['global_value'],1);
	}
$colors_replace=array('FFFFCC','0066FF','009900','FF0044','FFCC33','EAFFFF','909090');
$garbage=array('>&lt;?php'.$time,'?&gt;</span>'.$time,'?&gt;'.$time,$time);
$garbage_replace=array('>','</span>','','');
$code=highlight_string('<?php'.$time.$code.'?>'.$time,true);
$code=str_replace($garbage,$garbage_replace,$code);
$code=preg_replace('|<code>(.*?)<\/code>|si','\\1',$code);
$count_colors = count($colors);
	for($i=0; $i<$count_colors; $i++){
	$code=str_replace('<span style="color: #'.$colors[$i],'<font color="#'.$colors_replace[$i],$code);
	}
$code=str_replace('</span>','</font>',$code);
$output='<p style="background-color: #'.$colors_replace[5].'; border:1px dashed #'.$colors_replace[6].'; font-size:13px;padding: 3px;">'.$code.'</p>';
// style="border:1px dashed #909090; font-size:13px;"

	return $output;

}


//---------------------------------- Функция генерирования паролей ----------------------------------//
  function genpass($length=6)
{
$stock = 'abcdefghijklmnopqrstuvwxvzABCDEFGHIJKLMNOPQRSTUVWXVZ0123456789';

$result = '';
 for($i=0;$i<$length;$i++)
{
$result .= $stock[rand(0,61)];
}

return $result;

}
//---------------------------------- Функция отправки почты ----------------------------------//
  function sendmail($tomail, $subject, $msg)
{
global $config;
$subject = utf_to_win($subject);
$msg = utf_to_win($msg);

$subject = convert_cyr_string($subject, 'w','k');
$msg = convert_cyr_string($msg, 'w','k');

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

$adds = "From: ".$config['link_name']." <".$config['email'].">\n";
$adds .= "X-sender: ".$config['link_name']." <".$config['email'].">\n";
$adds .= "Content-Type: text/plain; charset=koi8-r\n";
$adds .= "MIME-Version: 1.0\n";
$adds .= "Content-Transfer-Encoding: 8bit\n";
$adds .= "X-Mailer: PHP v.".phpversion();

return mail($tomail,$subject,$msg,$adds);
}
//---------------------------------- Функция переброса пользовалея на нужную страницу ----------------------------------//
  function location($to,$prefix=true)
{
global $config;
header('Location: '.($prefix==true ? $config['link_url'].'/' : '').$to);
exit;
}
/*
//---------------------------------- Функция получения содержимого страницы ----------------------------------//
  function get_page($link,$ua='Unknow',$obr = true,$clear_scripts = true)
{

if(stripos('http://',$link) === false)$link = 'http://'.$link;

$pu = parse_url($link);

 $context = stream_context_create(array(
        'http' => array(
            'method' => 'GET',
            'header' => 'User-Agent: '.$ua.' (CLCLBMRGN)'."\r\n".
                        'Accept: text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, *\/*;q=0.1'."\r\n".
                        'Connection: Close'."\r\n".
                         'Host: '.$pu['host']
        ),
    ));



$file = file_get_contents($link,false,$context)or false;
# /*
if($clear_scripts)
 {
 	function clear_scripts($text)
   {
   #print_r($text);
   return '<b>JavaScript</b> : &lt;script&gt;'.$text[2].'&lt;/script&gt;';
   }

 $file = preg_replace_callback('#\<script(.*)?\>(.*?)\<\/script\>#Ui','clear_scripts',$file);
 }
#
#if($obr)$file = preg_replace('#\b(?:href|src)=["\'](?=(?!http://)[^"\'])#sUui','$0http://'.$link.'/',$file);

$file = preg_replace('#\b(?:href|src)=["\'](?=(?!http://)[^"\'])#i','$0http://'.$link.'/',$file);

return $file;
}
*/

 function clear_scripts($text)
{
return '<b>JavaScript</b> : &lt;script&gt;'.htmlspecialchars($text[2]).'&lt;/script&gt;';
}

  function get_page($link,$ua='Unknow',$obr = true,$clear_scripts = true)
{
 $context = stream_context_create(array(
        'http' => array(
            'method' => 'GET',
            'header' => "User-Agent: $ua (CLCLBMRGN)\r\n".
                        "Accept: text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1\r\n".
                        "Connection: Close"
        ),
    ));



$file = file_get_contents('http://'.$link,false,$context)or false;

if($clear_scripts)
 {
 $file = preg_replace_callback('#\<script(.*)?\>(.*?)\<\/script\>#Ui','clear_scripts',$file);
 }

if($obr)$file = preg_replace('#\b(?:href|src)=["\'](?=(?!http://)[^"\'])#i','$0http://'.$link.'/',$file);

return $file;
}

//---------------------------------- Функция автоматизации вывода ссылок на сортировку и проверку GET данных ----------------------------------//
  function sorting($elements,$default,$uri)
{
global $sort;
if(!is_array($elements) || count($elements)==0)return null;
if(empty($sort))$sort = $default;

if(!empty($_GET['sort']))
 {
 $tmp_sort = obr($_GET['sort'],'string');
 if(!empty($elements[$tmp_sort]))$sort = $tmp_sort;
 }

#$uri = str_replace('{$sort}',);

// Показ ссылок
echo 'Сортировать по : ';
$i = 0;
  foreach($elements as $key=>$value)
 {
 ++ $i;
 if($i!=1)echo ' | ';
 if($key==$sort)echo '[<b>'.$value.'</b>]';
 else echo '<a href="'.str_replace('{$sort}',$key,$uri).'">'.$value.'</a>';
 }

echo '<br />';
}
//---------------------------------- Поверхностаня проверка вылидности ----------------------------------//
  function is_validate_url($url,$content_url = null)
{

if(substr($url,0,7) != 'http://')$url = 'http://'.$url;

//-- получаем ответ от сервера
$headers = get_headers($url,true);

if($headers === false)return false;

//-- если содержимое страницы пусто, либо равно FALSE
if(empty($content_url) || $content_url === false)
 {
 $content_url = get_page(str_replace('http://','',$url),'Validate from WapClick.Org ('.rand(2,9).')');
 }

//-- сопственно проверка
if((stripos($headers['Content-Type'],'text/html') !== false && stripos($content_url,'<body') !== false && stripos($content_url,'</body>') !== false) || (stripos($headers['Content-Type'],'text/vnd.wap.wml') !== false && stripos($content_url,'<card') !== false && stripos($content_url,'</card>') !== false))
 {
 return true;
 }

return false;

}
//---------------------------------- Проверка на активность юзера ----------------------------------//
  function is_active_user($uid,$mode = 1)
{
global $config,$db;

$uprof = mysql_fetch_array(query("SELECT credits,trans_from FROM `$db[prefix]users` WHERE `id` = '$uid'"));

$values = array(
0=>array('error'=>false,'ok'=>true),
1=>array('error'=>'<font color="#f00000">Неактивен</font>','ok'=>'<font color="#00f000">Активен</font>')
);

//-- проверяем количество кредитов
if($uprof['credits'] < 1)return $values[$mode]['error'].($mode == 1 ? '(недостаточно кредитов)' : null);

//-- проверяем количество площадок
$count_user_sites = mysql_result(query("SELECT COUNT(*) FROM `$db[prefix]sites` WHERE `user` = '$uid' AND `status` = '3'"),0);
if($count_user_sites < $config['dolj_act_sites'])
{
return $values[$mode]['error'].($mode == 1 ? '(недостаточно активных сайтов)' : null);
}

if($uprof['trans_from'] < $config['dolj_act_trans'])
{
return $values[$mode]['error'].($mode == 1 ? '(недостаточно переходов)' : null);
}

return $values[$mode]['ok'];


#if(mysql_result(query("SELECT COUNT(*) FROM `$db[prefix]sites` WHERE `user` = '$user_prof[id]' "),0)<1)
#{
#echo '<font color="#f00000">Неактивен</font>(добавьте площадки)';
#}
#else
#{
#if($user_prof['credits']>=1) {echo '<font color="#00f000">Активен</font>';}
#else{ echo '<font color="#f00000">Неактивен</font>(недостаточно кредитов)'; }
#}

}
//----------------------------------  ----------------------------------//
//----------------------------------  ----------------------------------//

################################################
# 0KHQutGA0LjQv9GCINC90LUg0L/QsNCx0LvQuNC6IQ== #
#   0KHRgtCw0LLRgNC+0L/QvtC70YwsIDIwMDkg0LMu   #
################################################

?>