<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
set_magic_quotes_runtime(0);
$mtime = explode(' ', microtime());
$mm_starttime = $mtime[1] + $mtime[0];
define('l_path', substr(dirname(__FILE__), 0, -3));
define('l_ok',true);
if(PHP_VERSION < '4.1.0') {
	$_GET = &$HTTP_GET_VARS;
	$_POST = &$HTTP_POST_VARS;
	$_COOKIE = &$HTTP_COOKIE_VARS;
	$_SERVER = &$HTTP_SERVER_VARS;
	$_ENV = &$HTTP_ENV_VARS;
	$_FILES = &$HTTP_POST_FILES;
}
function mexit($msg=''){
	exit($msg);
}
function filter($string, $force = 0) {
	if(!$GLOBALS['magic_quotes_gpc'] || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = filter($val, $force);
			}
		} else {
			$string = addslashes($string);
		}
	}
	return $string;
}
function textcut($string, $length, $dot = '') {
	global $charset;
	if(strlen($string) <= $length) {
		return $string;
	}
	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
	$strcut = '';
	if(strtolower($charset) == 'utf-8') {
		$n = $tn = $noc = 0;
		while($n < strlen($string)) {
			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t < 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}
			if($noc >= $length) {
				break;
			}
		}
		if($noc > $length) {
			$n -= $tn;
		}
		$strcut = substr($string, 0, $n);
	} else {
		for($i = 0; $i < $length; $i++) {
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}
	$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
	return $strcut.$dot;
}

function ispage($number) {
	return !empty($number) && preg_match ("/^([0-9]+)$/", $number);
}

function paging($count,$perlogs,$page,$url)
{
$pnums = @ceil($count / $perlogs);
$pagesss=ceil($page-1);
if (!$pagesss) $re = "上一页";
if ($pagesss) $re = "<a href=\"$url$pagesss.html\">上一页</a>";
$pagexxx=ceil($page+1);
if ($pagexxx<=$pnums) $re .= " <a href=\"$url$pagexxx.html\">下一页</a>";
return $re;
}

function paginga($count,$perlogs,$page,$url)
{
$pnums = @ceil($count / $perlogs);
$re = '共有'.$pnums.'页';
for ($i = $page-5;$i <= $page+5 && $i <= $pnums; $i++)
{
if ($i > 0)
{
if ($i == $page)
{
$re .= " <span class=\"lan3\">$i</span> ";
} else 
{
$re .= " <a href=\"$url$i\" class=\"lan3\"><span class=\"fycss\">$i</span></a> ";
}
}
}
$ss=1;
if ($page > 6) $re = "<a href=\"$url$ss\" title=\"首页\" class=\"lan3\">首页</a> ...$re";
if ($page + 5 < $pnums) $re .= "... <a href=\"$url$pnums\" title=\"尾页\" class=\"lan3\">尾页</a>";
if ($pnums <= 1) $re = '';
return $re;
}
function GetKeywords($keyword){
global $tablepre,$db;
$time=date("Y-m-d");
	   $keyword = cn_substr($keyword,50);
//	   $row = $db -> queryarray("SELECT tags FROM {$tablepre}key where keyword='".addslashes($keyword)."'; ");
	   if(!is_array($row)){
		   if(strlen($keyword) > 8){
		      $sp = new SplitWord();
	        $keywords = $sp->SplitRMM($keyword);
	        $sp->Clear();
	        $keywords = ereg_replace("[ ]{1,}"," ",trim($keywords));
	     }else{
	        $keywords = $keyword;
	     }
	     $inquery = "INSERT INTO `{$tablepre}key`(`keyword`,`tags`,`weekct`,`weekup`,`monthct`,`monthup`,`count`,`result`,`sotime`)
          VALUES ('".addslashes($keyword)."', '".addslashes($keywords)."', '1', '".$time."', '1', '".$time."', '1', '0', '".$time."');
       ";
	     $db -> query($inquery);
	  }else{
		   $db -> query("Update {$tablepre}key set count=count+1,sotime='".$time."' where keyword='".addslashes($keyword)."'; ");
		   $keywords = $row['tags'];
	  }
	  return $keywords;
}

function GetLikeWords(){
global $tablepre,$db,$keywords,$keyword,$siteurl;
	  $keyword = cn_substr($keyword,50);
 		$ks = explode(" ",$keywords);
 		$lsql = "";
 		foreach($ks as $k){
 			$k = trim($k);
 	    if(strlen($k)<2) continue;
 			if(ord($k[0])>0x80 && strlen($k)<3) continue;
 			$k = addslashes($k);
 			if($lsql=="") $lsql = $lsql." CONCAT(tags,' ') like '%$k %' ";
 			else $lsql = $lsql." Or CONCAT(tags,' ') like '%$k %' ";
 		}
 		if($lsql=="") return "";
 		else{
 		$i=0;
 			$lsql = "(".$lsql.") And Not(keyword like '".addslashes($keyword)."') ";
 			$query = $db -> query("Select keyword,count From {$tablepre}key where $lsql and result='1'order by sotime desc limit 0,8; ");
 			while($row = $db -> fetch_array($query)){
 			$i=$i+1;
 			if($i==1){
 			$likeword = "&#x76f8;&#x5173;&#x641c;&#x7d22;:";
 			}
 				 if($row['count']>1000) $fstyle=" style='font-size:11pt;color:red'";
 				 else if($row['count']>300) $fstyle=" style='font-size:10pt;color:green'";
 				 else $style = "";
 				 $likeword .= '<a href="'.$siteurl.'/index.php/tags/'.urlencode($row['keyword']).'"'.$style."><u>".$row['keyword']."</u></a>　";
 			}
 			return $likeword;
 		}
}

function newupct($upct){
global $tablepre,$db;
if($upct==1){
$db -> query("Update {$tablepre}link set dayctbak=dayct,dayct=0; ");
$db -> query("DELETE FROM {$tablepre}linkip");
}
if($upct==2){
$db -> query("Update {$tablepre}link set weekctbak=weekct,weekct=0; ");
}
if($upct==3){
$db -> query("Update {$tablepre}link set monthctbak=monthct,monthct=0; ");
}
}

function Gettags(){
global $tablepre,$db,$keywords;
$time=date("Y-m-d");
 		$ks = explode(",",$keywords);
 		$rstr = "";
 		$kwsql = "";
 		$words = array();
 		foreach($ks as $k){
 			$k = trim($k);
 			if($k=="") continue;
 			if(ord($k[0])>0x80 || strlen($k)<3) continue;
 			$row = $db -> queryarray("SELECT * FROM {$tablepre}key where tags='".$k."' and result='1'; ");
 			if(!is_array($row)){
	     $inquery = "INSERT INTO `{$tablepre}key`(`tags`,`weekct`,`weekup`,`monthct`,`monthup`,`count`,`result`,`sotime`)
          VALUES ('".$k."', '1', '".$time."', '1', '".$time."', '1', '1', '".$time."');
       ";
	     $db -> query($inquery);
	  }else{
		   $db -> query("Update {$tablepre}key set weekct=weekct+1,monthct=monthct+1,count=count+1,sotime='".$time."' where id='".$row['id']."'; ");
			  if($time-$row['weekup']>7){
        $db -> query("Update {$tablepre}key set weekct=0,weekup='".$time."' where id='".$row['id']."'; ");
			  }
			  if($time-$row['monthup']>30){
        $db -> query("Update {$tablepre}key set monthct=0,monthup='".$time."' where id='".$row['id']."'; ");
			  }
	  }
 		}
 		return ;
}

function GetRedKeyWord($fstr){
global $keywords;
 		$ks = explode(" ",$keywords);
 		$rstr = "";
 		$kwsql = "";
 		$words = array();
 		foreach($ks as $k){
 			$k = trim($k);
 			if($k=="") continue;
 			if(ord($k[0])>0x80 && strlen($k)<3) continue;
 			$rstr.= str_replace($k,"<font color='red'>$k</font>",$fstr);
 		}
 		return $rstr;
}

function Gettoptags($n=0){
global $tablepre,$db;
$Gettoptags="";
$cjurls = file(l_path."./keys.txt");
$a = array_unique($cjurls);//取出重复
$sum = 0;//初始化累加变量urlencode
foreach($a as $cjurls[$sum])
{           
$sum  = $sum+1;
}
$rand_keys=array_rand($cjurls,10);
for($i=0;$i<=9;$i++) {
 				 $Gettoptags .= '<a href="/tags/'.urlencode(trim($cjurls[$rand_keys[$i]])).'/"'.$style."><u>".trim($cjurls[$rand_keys[$i]])."</u></a>　";
}
$n=$n-9;
 			$query = $db -> query("Select tags,count From {$tablepre}key where result='1' order by count desc limit 0,$n; ");
 			while($row = $db -> fetch_array($query)){
 				 if($row['count']>1000) $fstyle=" style='font-size:11pt;color:red'";
 				 else if($row['count']>300) $fstyle=" style='font-size:10pt;color:green'";
 				 else $style = "";
 				 $Gettoptags .= '<a href="/tags/'.urlencode($row['tags']).'/"'.$style."><u>".$row['tags']."</u></a>　";
 			}
 			return $Gettoptags;
}

function Getnewtags($n=0){
global $tablepre,$db,$siteurl;
$Gettoptags="";
$cjurls = file(l_path."./keys.txt");
$a = array_unique($cjurls);//取出重复
$sum = 0;//初始化累加变量
foreach($a as $cjurls[$sum])
{           
$sum  = $sum+1;
}
$rand_keys=array_rand($cjurls,3);
for($i=0;$i<=9;$i++) {
$Gettoptags .= '<a href="/tags/'.urlencode(trim($cjurls[$rand_keys[$i]])).'/"'.$style."><u>".trim($cjurls[$rand_keys[$i]])."</u></a>　";
}
$n=$n-9;
$style="";
 			$query = $db -> query("Select tags,count From {$tablepre}key where result='1' order by id desc limit 0,$n; ");
 			while($row = $db -> fetch_array($query)){
 				 $Getnewtags .= '<a href="/tags/'.urlencode($row['tags']).'/"'.$style."><u>".$row['tags']."</u></a>　";
 			}
 			return $Getnewtags;
}

function sortselect($sorts = array(),$checkid=0,$id=0,$now=0){
	$lists='';
	if(count($sorts[$id])) {
		foreach($sorts[$id] as $key => $sort){
			$selected = $sort['id'] == $checkid ? ' selected' : '';
			$lists.= '<option value="'.$sort['id'].'"'.$selected.'>'.str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;',$now).$sort['sortname']."</option>";
			if(count($sorts[$sort['id']])) {
				$lists.=sortselect($sorts,$checkid,$sort['id'],$now+1);
						
			}
		}
	}
	return $lists;	
}


function random($length, $numeric = 0) {
	mt_srand((double)microtime() * 1000000);
	if($numeric) {
		$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	} else {
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	return $hash;
}

function writetofile($file_name,$data,$method='w') {
	if($filenum=@fopen($file_name,$method)){
		flock($filenum,LOCK_EX);
		$file_data=fwrite($filenum,$data);
		fclose($filenum);
		return $file_data;
	}else{
		exit('Can not fopen please check the file or PHP.INI');
	}
}
function readfromfile($file){
	if(!@$fp = fopen($file, 'r')) {
		return false;
	} else {
		$str = @fread($fp, filesize($file));
		fclose($fp);
		return $str;
	}
}

$magic_quotes_gpc = get_magic_quotes_gpc();
$register_globals = @ini_get('register_globals');

if(!$register_globals || !$magic_quotes_gpc) {
	@extract(filter($_POST));
	@extract(filter($_GET));
	if(!$magic_quotes_gpc) {
		$_FILES = filter($_FILES);
	}
}


require_once l_path.'./config.inc.php';
require_once l_path.'./inc/db_mysql.class.php';
$time = time();
$db = new db_class();
$db -> mysql_con($dbhost ,$dbuser, $dbpassword,$dbname,$connectmode);
unset($dbhost ,$dbuser, $dbpassword,$dbname,$connectmode);
$PHP_SELF = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
$SCRIPT_FILENAME = str_replace('\\\\', '/', ($_SERVER['PATH_TRANSLATED'] ? $_SERVER['PATH_TRANSLATED'] : $_SERVER['SCRIPT_FILENAME']));
$homeurl = 'http://'.$_SERVER['HTTP_HOST'].preg_replace("/\/+(api|archiver|wap)?\/*$/i", '', substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'))).'/';

function getlocalhtml($filename,$evryhour){
	if(file_exists($filename)){
		if($evryhour==0){
    require_once($filename);	
		exit();
        die();
		}else
    if((time()-filemtime($filename))<($evryhour*60)){
		require_once($filename);
        exit();
        die();
			}else{
			  	return ;
			}		
	}else
		return;

}
function gethchtml($filename,$evryhour){
	if(file_exists($filename)){
		if($evryhour==0){
    return "ok";
		}elseif((time()-filemtime($filename))<($evryhour*60)){
    return "ok";
		}
  }
}

function idarray($idarray, $quote = '\'', $bound = ','){
	if(!is_array($idarray)){
		return false;
	}
	$ids = $common = '';
	foreach($idarray AS $key => $id){
		$ids .=$common. $quote . $id .$quote;
		$common = $bound;
	}
	return $ids;
}

function setLocalHtml($filename,$content){
$content=str_replace("</body>","<!--\nU2 PHP自动链 v2.20110303\n链接你我他！\n-->\n</body>",$content);
	$fp=fopen("$filename","w");
	if(!$fp){		
 		echo "&#x670d;&#x52a1;&#x5668;&#x5904;&#x7406;&#x51fa;&#x9519;&#xff0c;&#x8bf7;&#x548c;&#x7ba1;&#x7406;&#x5458;&#x8054;&#x7cfb;&#x3002;&#x51;&#x51;&#x34;&#x32;&#x36;&#x34;&#x32;&#x30;&#xff01;&#x9519;&#x8bef;&#x49;&#x44;&#xff1a;&#x31;&#x30;&#x30;&#x30;&#x31;";
 		exit();
	}else{
 		 fwrite($fp, $content)?require_once($filename): print("&#x670d;&#x52a1;&#x5668;&#x5904;&#x7406;&#x51fa;&#x9519;&#xff0c;&#x8bf7;&#x548c;&#x7ba1;&#x7406;&#x5458;&#x8054;&#x7cfb;&#x3002;&#x51;&#x51;&#x34;&#x32;&#x36;&#x34;&#x32;&#x30;&#xff01;&#x9519;&#x8bef;&#x49;&#x44;&#xff1a;&#x31;&#x30;&#x30;&#x30;&#x32;"); 
	}
}

function mkpaths($paths){
	if($paths) {
		$listpath = explode('/',$paths);
		$mkpath='';
		for($i=1;$i<=count($listpath);$i++) {
			$mkpath = $mkpath.'/'.$listpath[$i];
			if(!is_dir(l_path.'.'.$mkpath)){
				if(!@mkdir(l_path.'.'.$mkpath,0777)) {
						exit('&#x6307;&#x5b9a;&#x76ee;&#x5f55;&#x4e0d;&#x5b58;&#x5728;&#x6216;&#x4e0d;&#x5141;&#x8bb8;&#x64cd;&#x4f5c;&#x2c;&#x8bf7;&#x68c0;&#x67e5;&#x76ee;&#x5f55;&#x6743;&#x9650;&#x662f;&#x5426;&#x4e3a;&#x20; 0777');
				}
			}
		}
	}
}

$newhours = gmdate("H",time()+3600*8);
$newwday = gmdate("D",time()+3600*8);
$newmon= gmdate("d",time()+3600*8);
$neweday= gmdate("d",time()+3600*32);
if($newmon==$upday){
if($newhours=="0"){
newupct('1');
if($newwday=="Mon"){
newupct('2');
}
if($newmon=="1"){
newupct('3');
}
$configs = readfromfile(l_path.'./config.inc.php');
$configs = preg_replace("/[$]upday\s*\=\s*[\"'].*?[\"'];/is", "\$upday = '$neweday';", $configs);
writetofile(l_path.'./config.inc.php',$configs);
}
}

function get_url_content($url) {
global $charset;
if(function_exists('file_get_contents')) {
$file_contents = @file_get_contents($url);
} else {
$ch = curl_init();
$timeout = 5; 
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
}
$file_contents=get_encoding($file_contents,$charset);
return $file_contents;
}
//自动检测内容是编码进行转换 get_encoding($data,"GB2312");
function get_encoding($data,$to)
{
$encode_arr = array('UTF-8','ASCII','GBK','GB2312','BIG5','JIS','eucjp-win','sjis-win','EUC-JP');
$encoded = mb_detect_encoding($data, $encode_arr);
$data = mb_convert_encoding($data,$to,$encoded);
return $data;
}
function okip() {
  if (isset($_SERVER)) {
          $realip = $_SERVER[HTTP_X_FORWARDED_FOR];
  } else {
    $realip = getenv("HTTP_X_FORWARDED_FOR");
  }
  if ($realip!=''){
      mexit("不可以使用代理访问");
  }
}

function cut($string,$start,$end)
{
	$message = explode($start,$string);
	$message = explode($end,$message[1]); 
	return trim($message[0]);
}
/*过滤不健康的字*/
function replace_word($string){
global $delkey;
    $delkeys = explode("|",$delkey);  //使用数组保存需要过滤的词语
    foreach ($delkeys as $del_word) 
    {    
        if (stristr(trim($string),$del_word))
        {
            $length = strlen($del_word);
//            for ($i = 1; $i <= $length; $i++)
//            {
//            $stars .= "*";
//            }
        $stars = "*";
        $string = eregi_replace($del_word,$stars,trim($string));
//        $stars = '';
        }
    }
    return $string;
}

function d($str){
$str=str_replace("http://","",$str);
$uurlt=split('/',$str);
$uuurlt=$uurlt[0];
return $uuurlt;
}
function t($str,$s='50'){
return textcut($str,$s);
}
function s($str){
$ss="font-size:12px;";
if($str=='2'){
$ss="color:#FF0099;font-size:13px;";
} 
if($str=='3'){
$ss="color:red;font-size:12px;";
} 
return $ss;
}
function k($str,$s='50'){
$keywords=textcut($str,100);
$keys = "";
$b = explode(",",$keywords); 
foreach ($b as $v) {
$keys.="" .$v. "&nbsp;";
}
return $keys;
}


require_once l_path."./inc/links.inc.php";
require_once l_path."./inc/splitword.func.php";
require_once l_path."./inc/uri.inc.php";
require_once l_path."./inc/links.class.php";
define('l_dbt',$tablepre);

function Getsclass($uid='0'){
global $tablepre,$db;
$sclass = $db -> queryarray("SELECT sortname FROM {$tablepre}sclass WHERE id='$uid'");
if(!$sclass['sortname']){
return "未分类";
}
return $sclass['sortname'];
}
?>