<?php
/*** 数据缓存相关 ***/
/*** 南京牛昆网络科技有限公司 ***/
function get_cache_counts($sql,$ttl=0)
{
	global $db,$T;
	$id = md5($sql);
	$ttl=intval($ttl)?intval($ttl):CACHE_COUNT_TTL;

	if(!isset($T['count'][$id]))
	{
		if($ttl)
		{
			$r=$db->fetch_one("SELECT `count`,`updatetime` FROM `".LA_PRE."counts` WHERE `id`='$id'");
			if(!$r||$r['updatetime']<TIME-$ttl)
			{
				$r=$db->fetch_one($sql);
				$T['count'][$id] = $r['count'];
				$db->query("REPLACE INTO `".LA_PRE."counts`(`id`, `count`, `updatetime`) VALUES('$id', '".$r['count']."', '".TIME."')",true);
			}
		}
		else
		{
			$r=$db->get_one($sql);
		}
		$T['count'][$id]=$r['count'];
	}
	return $T['count'][$id];
}

function cache_read($cachename,$path='')
{
	$cachename=str_replace('/','',$cachename);
	$cachename=str_replace('\\','',$cachename);
	$path=empty($path)?SYSTEM_ROOT.'data/cache/':$path;
	$cachefile=$path.$cachename;
	if(!file_exists($cachefile))return false;
	return @include $cachefile;
}

function cache_write($cachename,$array=array(),$path='')
{
	if(!is_array($array))return false;
	$path=empty($path)?SYSTEM_ROOT.'data/cache/':$path;
	$cachefile=$path.$cachename;
	
	$array="<?php\n//".date('Y-m-d H:i:s',time())."\nreturn ".var_export($array,true).";\n?>";
	$strlen=file_put_contents($cachefile,$array);

	@chmod($cachefile,0777);
	return $strlen;
}

function cache_delete($cachename,$path='')
{
	$path=empty($path)?SYSTEM_ROOT.'data/cache/':$path;
	if($cachename=='*') // 所有缓存文件及文件夹
	{
		rmdirs($path);
	}
	else if($cachename=='*.*') // 所有缓存文件
	{
		 rmfiles($path);
	}
	else // 指定文件
	{
		$cachefile=$path.$cachename;
		return @unlink($cachefile);
	}
}

function set_config($config)
{
	if(!is_array($config)) return false;
	$configfile = SYSTEM_ROOT.'data/config.inc.php';
	if(!is_writable($configfile)) 
	{
		admin_error('Please chmod ./data/config.inc.php to 0777 !');
	}

	$pattern = $replacement = array();
	foreach($config as $k=>$v)
	{
		$pattern[$k] = "/define\(\s*['\"]".strtoupper($k)."['\"]\s*,\s*([']?)[^']*([']?)\s*\)/is";
        $replacement[$k] = "define('".strtoupper($k)."', \${1}".$v."\${2})";
	}
	$str = file_get_contents($configfile);
	$str = preg_replace($pattern, $replacement, $str);

	return file_put_contents($configfile, $str);
}

function get_hash_table($table,$id,$volume=10) 
{
	$hash = sprintf("%u", crc32($id));
	$hash1 = intval(fmod($hash, $volume));
	return $hash1?$table.$hash1:$table;
}

/*** 模板引擎相关 ***/

function forbiddendownload()
{
	!defined('IN_SYS') && exit('<html></html>');
}


function getchildtypeid($typeid=0)
{
	global $db;
	$typeid=intval($typeid);
	$re[]=$typeid;
	$r=$db->fetch_all("SELECT `".LA_PRE."type`.`typeid` FROM `".LA_PRE."type` WHERE `".LA_PRE."type`.`parentid`=$typeid OR `".LA_PRE."type`.`grandparentid`=$typeid");
	if($r)foreach($r as $i => $_r)
	{
		$i++;
		$re[$i]=$_r['typeid'];
	}
	return $re;
}

function isfinaltypeid($typeid=0)
{
	global $db;
	$typeid=intval($typeid);
	return $db->fetch_one("SELECT `".LA_PRE."type`.`typeid` FROM `".LA_PRE."type` WHERE `".LA_PRE."type`.`parentid`=$typeid OR `".LA_PRE."type`.`grandparentid`=$typeid")?false:true;
}

function isfinalcatid($typeid=0)
{
	return isfinaltypeid($typeid);
}

function la_call_user_func($function,$parameter,$extra='')
{
	$para=array();
	$parameter=preg_replace('/\"\s+\"/i','""',$parameter);
	$parameter=explode(" ",$parameter);

	if($parameter)
	{
		foreach($parameter as $val)
		{
			preg_match('/([0-9a-z_]+)\s*=\s*([^\s]+)/i',$val,$matches);
			$para[$matches[1]]=filterpara($matches[2]);
		}
	}

	if($extra)
	{
		preg_match('/([0-9a-z_]+)\s*=\"([^\"]+)\"/i',$extra,$matches);
		$para[$matches[1]]=filterpara($matches[2]);
	}
	return call_user_func($function,$para);
}

function filterpara($para)
{
	return str_replace(array('\'','"'),'',stripslashes($para));
}

function create_html($file)
{
	global $usermodule,$LA,$niubicms;	
	$data=ob_get_contents();
	ob_clean();
	if(!is_dir(dirname($file)))
	{
		makedir(dirname($file));
	}

	$strlen=file_put_contents($file,$data);
	@chmod($file,0777);
	return $strlen;
}

/**
	格式化日期函数
	用法：formattime($time,$format)
	参数：$time, Unix时间戳；$format,日期格式
	更新：2012-06-27 
*/
function formattime($time,$format='Y-m-d H:i:s')
{
	global $baselang;

	if(TIME-$time<60)
	{
		return (TIME-$time).'秒前';
	}
	else if(TIME-$time<3600)
	{
		return intval((TIME-$time)/60).'分钟前';
	}
	else if(TIME-$time<3600*24)
	{
		return intval((TIME-$time)/3600).'小时前';
	}
	else
	{
		return date($format,$time);
	}
}

function template($tplname,$mod='',$isprompt=0)//include template('admin-success','',true);
{
	global $LA;
	$LA['lang']=$LA['lang']?$LA['lang']:'cn';

	if(!$isprompt)
	{
		$mod=trim($mod)?trim($mod).'/':'';
		$project=$LA['template'].'/';
	}
	else
	{
		$mod='';
		$project='prompt/';
	}

	require_once (SYSTEM_ROOT.'include/template.func.php');
	$compliedfile=TPL_CACHEPATH.$LA['lang'].'/'.$project.$mod.$tplname.'.tlp.php';
	
	if(!is_dir(TPL_CACHEPATH))
	{
		@mkdir(TPL_CACHEPATH,0777);
	}

	if(!is_dir(TPL_CACHEPATH.$LA['lang'].'/'))
	{
		@mkdir(TPL_CACHEPATH.$LA['lang'].'/',0777);
	}

	if(!is_dir(TPL_CACHEPATH.$LA['lang'].'/'.$project.'/'))
	{
		@mkdir(TPL_CACHEPATH.$LA['lang'].'/'.$project.'/',0777);
	}

	if(!is_dir(TPL_CACHEPATH.$LA['lang'].'/'.$project.'/'.$mod))
	{
		@mkdir(TPL_CACHEPATH.$LA['lang'].'/'.$project.'/'.$mod,0777);
	}

	if(!file_exists(TPL_ROOT.$LA['lang'].'/'.$project.'/'.$mod.$tplname.'.html'))
	{
		fatal_error('该模板方案下的模板文件'.TPL_ROOT.$LA['lang'].'/'.$project.$mod.$tplname.'.html'.'不完整!','t1001');
	}

	if(!file_exists($compliedfile) || @filemtime(TPL_ROOT.$LA['lang'].'/'.$project.$mod.$tplname.'.html') > @filemtime($compliedfile))
	{
		template_complie($tplname,$mod,$isprompt);
	}
	
	return $compliedfile;
}

function getconpos($typeid=0)
{
	global $LA,$db,$mod;

	$typeid=intval($typeid);
	$mod=empty($mod)?'index':preg_replace('/[^0-9a-z_]/i','',$mod);

	$postion='<a href="'.$LA['siteurl'].'" target="_blank">'.$LA['sitename'].'</a>&gt;';
	$r=$db->fetch_one("SELECT * FROM `".LA_PRE."type` WHERE `".LA_PRE."type`.`typeid`=".intval($typeid));

	if($r['grandparentid'])
	{
		$r2=$db->fetch_one("SELECT * FROM `".LA_PRE."type` WHERE `".LA_PRE."type`.`typeid`=".intval($r['grandparentid']));	
		$postion.='<a href="'.typeurl($r['grandparentid']).'" target="_blank">'.$r2['name'].'</a>&gt;';
	}

	if($r['parentid'])
	{
		$r3=$db->fetch_one("SELECT * FROM `".LA_PRE."type` WHERE `".LA_PRE."type`.`typeid`=".intval($r['parentid']));
		$postion.='<a href="'.typeurl($r['parentid']).'" target="_blank">'.$r3['name'].'</a>&gt;';
	}

	$postion.='<a href="'.typeurl($typeid).'" target="_blank">'.$r['name'].'</a>';

	return $postion;
}

function listpage($catid,$moduleid=0,$listsize=5,$page=0)
{
	global $conobj,$configobj,$siteidobj;
	$catid=intval($catid);
	$moduleid=intval($moduleid);
	$page=intval($page)>0?intval($page):1;

	$data=array();

	if($catid)
	{
		$r=cache_read('type-listsize'.$catid.'.cache.php',SYSTEM_ROOT.'data/tmp/');
		$row=$r && intval($r[$catid])?intval($r[$catid]):20;

		if(SITETYPE && $_SESSION['siteid'])
		{
			$where='siteid IN('.implode(',',$siteidobj->getchildid($_SESSION['siteid'])).') AND status=1 AND isdeleted=0 AND ishidden=0';
		}
		else
		{
			$where='a.status=1';
		}
		
		$where.=' AND typeid IN('.implode(',',array_unique(getchildtypeid($catid))).')';

		$totalcount=get_cache_counts("SELECT COUNT(*) AS count FROM `".LA_PRE."content` WHERE $where"); 

		if(!$totalcount)
		{
			$data['totalcount']=0;
			$data['pageno']=1;
			$data['page']=1;
			$data['index']='';
			$data['pagelist']='';
			$data['next']='';
			$data['end']='';
		}
		else
		{
			$pageno=ceil($totalcount/$row);
			$page=max(1,min($page,$pageno));
			$data['totalcount']=$totalcount;
			$data['pageno']=$pageno;
			$data['page']=$page;
			$data['index']=$page==1?'':'<a href="'.$catinfo['url'].'">'.$baselang['firstpage'].'</a>';

			$pagearray=range(1,$pageno);
			$pagearray=array_slice($pagearray,max(0,($page/$listsize < 1?0:floor($page/$listsize)*$listsize)-1) ,$listsize);
			$querystring=array();
			
			$modsettings=$configobj->getconfig($_SESSION['siteid'],$moduleid);

			if($modsettings['rewrite']==0) //动态
			{
				if($page==1)
				{
					$data['pre']='';
				}
				else
				{
					$data['pre']='<a href="'.$catinfo['url'].'&page='.max(1,$page-1).'">上一页</a>';
				}

				if($page==$pageno)
				{
					$data['next']='';
				}
				else
				{
					$data['next']='<a href="'.$catinfo['url'].'&page='.min($pageno,$page+1).'">下一页</a>';
				}

				if($pageno>1)
				{
					foreach($pagearray as $_page)
					{
						if($page==$_page)
						{
							$querystring[]=$_page;
						}
						else
						{
							$querystring[]='<a href="'.$catinfo['url'].'&page='.max($_page,1).'">'.max($_page,1).'</a>';
						}
					}
				}
				$data['pagelist']=implode(' ',$querystring);
				$data['end']=$page==$pageno?'':'<a href="'.$catinfo['url'].'&page='.$pageno.'">尾页</a>';
			}
			else //伪静态
			{
				if($page==1)
				{
					$data['pre']='';
				}
				else
				{
					$data['pre']='<a href="'.substr($catinfo['url'],0,-strlen('.'.get_fileext($catinfo['url']))).'-'.max(1,$page-1).'.'.get_fileext($catinfo['url']).'">上一页</a>';
				}
				
				if($pageno>1)
				{
					foreach($pagearray as $_page)
					{
						if($page==$_page)
						{
							$querystring[]=$_page;
						}
						else
						{
							$querystring[]='<a href="'.substr($catinfo['url'],0,-strlen('.'.get_fileext($catinfo['url']))).'-'.$_page.'.'.get_fileext($catinfo['url']).'">'.max($_page,1).'</a>';
						}
					}
				}

				$data['pagelist']=implode(' ',$querystring);

				if($page==$pageno)
				{
					$data['next']='';
				}
				else
				{
					$data['next']='<a href="'.substr($catinfo['url'],0,-strlen('.'.get_fileext($catinfo['url']))).'-'.min($pageno,$page+1).'.'.get_fileext($catinfo['url']).'">下一页</a>';
				}

				$data['end']=$page==$pageno?'':'<a href="'.substr($catinfo['url'],0,-strlen('.'.get_fileext($catinfo['url']))).'-'.intval($pageno).'.'.get_fileext($catinfo['url']).'">末页</a>';
			}
		}
	}
	return $data;
}

function formatconurl($contentid)
{
	global $conobj;
	return $conobj->formatconurl($contentid);
}

/// 获取模块地址
function formatmoduleurl($moduleid=0)
{
	global $moduleobj,$configobj,$LA;
	$moduleid=intval($moduleid);
	$r=$moduleobj->get($moduleid);
	if(!$r)
	{
		return $LA['siteurl'];
	}
	$settings=$configobj->getconfig($_SESSION['siteid'],$moduleid);
	return $settings['domain']?$settings['domain']:$LA['siteurl'].$r['folder'].'/';
}

function typename($id)
{
	global $conobj;
	return $conobj->typename($id);
}

function typeurl($id)
{
	global $conobj,$configobj,$urlcacheobj;
	
	$key='key-content-typeid-'.$id;
	$url=$urlcacheobj->get($key);
		
	if(!$url)
	{
		$r=$conobj->typeinfo($id);
		$_mod=$configobj->getconfig($_SESSION['siteid'],$r['moduleid']);
		if(!$_mod['is_rewrite'])
		{
			$url= LA_PATH.$_mod['folder'].'/index.php?mod='.$_mod['folder'].'&action=list&typeid='.intval($id);
		}
		else
		{
			$url= LA_PATH.$_mod['folder'].'/list-'.intval($id).'.html';
		}
		$urlcacheobj->set($key,$url);
	}

	return $url;
}

/****兼容其他产品****/
function catname($id)
{
	return typename($id);
}

function caturl($id)
{
	return typeurl($id);
}

function formaturl($path)
{
	global $LA;
	return substr(strtolower($path),0,7)=='http://'?$path:$LA['siteurl'].(substr($path,0,1)=='/'?substr($path,1):$path);
}

function substrreplace($string,$start=1,$length=8)
{
	$len=strlen($string);
	if($len==1)
	{
		return '*';
	}
	else
	{
		return substr_replace($string,str_repeat('*',$length),$start,$length);
	}
}
/******** 环境变量相关函数 *********/
function getservername()
{
	return $servername=(!empty($_SERVER['HTTP_HOST'])) ? strtolower($_SERVER['HTTP_HOST']) : ((!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : getenv('SERVER_NAME'));
}

function getcururl()
{
	$cur='';
	if(isset($_SERVER['REQUEST_URI']))$cur=$_SERVER['REQUEST_URI'];
	else if(isset($_SERVER['PHP_SELF']) && isset($_SERVER['argv']))$cur=$_SERVER['PHP_SELF'].'?'.$_SERVER['argv'][0];
	else $cur=$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
	return strip_tags($cur);
}

function disablefunc($func)
{
	return in_array($func,array_map('trim',explode(',',ini_get('disable_functions'))));
}
/******** 分页函数 *********/
function getpages($number,$page,$pagesize,$align='right',$catid=0)
{
	global $niubicms,$baselang;
	$rand=mt_rand(100,999);
	$pagenum=max(1,ceil($number/$pagesize));
	$prepage=max(($page-1),1);
	$nextpage=max(1,min(($page+1),$pagenum));
		
	$cururl=preg_replace('/([&\?]?)(page=[0-9]+)([&\?]?)/i','\\1',getcururl());
	$strlen=strlen($cururl)-1;
	$flag=(boolean)(substr(strrchr($cururl,'/'),1));
	if(substr($cururl,-1,1)=='&')
	{
		$cururl=$flag?substr($cururl,0,$strlen).'&page=':substr($cururl,0,$strlen).'?page=';
	}
	elseif(substr($cururl,-1,1)=='?')
	{
		$cururl=substr($cururl,0,$strlen).'?page=';
	}
	else{
		if(strpos($cururl,'?')===false && strpos($cururl,'&')===false)$flag=false;
		$cururl=$flag?$cururl.'&page=':$cururl.'?page=';
	}
	$pselect='<select name="pageto" id="pagetoselect'.$rand.'" onchange="window.location.href=\'http://'.getservername().$cururl.'\'+document.getElementById(\'pagetoselect'.$rand.'\').value">';
	for($i=1;$i<=intval($pagenum);$i++)
	{
		$pselect.='<option value="'.$i.'">第'.$i.'页</option>';
	}
	$pselect.='</select><script language="javascript">{document.getElementById(\'pagetoselect'.$rand.'\').value='.$page.'}</script>';
	return '<div align="'.$align.'">&nbsp;统计：<b>'.$number.'</b> &nbsp;
					<a href="http://'.getservername().$cururl.'1">第一页</a>&nbsp;<a href="http://'.getservername().$cururl.$prepage.'">上一页</a>&nbsp;
					<a href="http://'.getservername().$cururl.$nextpage.'">下一页</a>&nbsp;
					<a href="http://'.getservername().$cururl.$pagenum.'">尾页</a>&nbsp;总页数：<b><font color="#ff0000">'.$page.'</font>/'.$pagenum.'</b> '.$pselect.($_SERVER['HTTP_REFERER']?'&nbsp;&nbsp;<input type="button" onclick="javascript:self.history.back();" value="后退" style="padding:1px 4px" />':'').'</div>';	
}

/*** 跳转提示相关 ***/

function admin_success($msg='',$url='',$timeout=500)
{
	global $niubicms;
	if(!$url)$url='javascript:history.back();';
	include template('admin-success','',true);
	exit('<script>setTimeout("redirect(\''.$url.'\');",'.$timeout.');</script>');
}

function admin_error($msg='',$url='',$timeout=1000)
{
	global $niubicms;
	if(!$url)$url='javascript:history.back();';
	include template('admin-error','',true);
	exit('<script>setTimeout("redirect(\''.$url.'\');",'.$timeout.');</script>');
}

function showmsg($msg='',$url='',$result='success')
{
	global $LA,$niubicms,$_point,$_amount,$_username;
	include template('msg','',true);
	exit();
}

function showjsmsg($msg='',$refer='')
{
	if(!$refer)
	{
		exit('<script>alert("'.$msg.'");history.back();</script>');
	}
	else
	{
		exit('<script>alert("'.$msg.'");location.href="'.$refer.'";</script>');
	}
}

function shownojsmsg($refer='')
{
	if(!$refer)
	{
		exit('<script>history.back();</script>');
	}
	else
	{
		exit('<script>location.href="'.$refer.'";</script>');
	}
}

function showpopjsmsg($msg='')
{
	exit('<script>alert("'.$msg.'");self.parent.location.reload();</script>');
}

function showmsg_noback($msg='',$url='')
{
	global $LA;
	include template('prompt_noback','',true);
	exit();
}

function fatal_error($msg,$errno='')
{
	$msg=DEBUG?strip_tags($msg,'<br><p><a>'):'系统管理员屏蔽了错误信息!';
	global $LA;
	exit($msg);
}

function show404($msg='',$url='',$timeout=10000)
{
	global $LA;
	header('HTTP/1.1 404 Not Found');
	header("status: 404 Not Found");
	if(!$url)
	{
		$url=$LA['site_url'];
	}
	$expire=$timeout/1000;
	include template('prompt_404','',true);
	exit('<script>setTimeout("redirect(\''.$url.'\');",'.$timeout.');</script>');
}

/*** 管路员相关 ***/
function admin_tlp($tlp,$module='')
{
	$tlpfile=empty($module)?SYSTEM_ROOT.'admin/template/'.$tlp.'.tlp.php':SYSTEM_ROOT.$module.'/admin/template/'.$tlp.'.tlp.php';
	!file_exists($tlpfile) && show404('模板文件'.$tlpfile.'不存在!');
	return $tlpfile;
}

/*** IP相关 ***/

function ip2area($ip) 
{

	global $stringcacheobj;

	if(!preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $ip)) 
	{
		return 'Unknown';
	}

	$key='ip-ip2area-'.$ip;

	
	$iparea=$stringcacheobj->get($key);
		
	if(!$iparea)
	{
		
		$fd = @fopen(SYSTEM_ROOT.'statics/dict/ipdata.dat', 'rb');
		
		if(!$fd)
		{
			return 'Unknown';
		}

		$ip = explode('.', $ip);
		$ipNum = $ip[0] * 16777216 + $ip[1] * 65536 + $ip[2] * 256 + $ip[3];

		$DataBegin = fread($fd, 4);
		$DataEnd = fread($fd, 4);
		$ipbegin = implode('', unpack('L', $DataBegin));
		if($ipbegin < 0) $ipbegin += pow(2, 32);
		$ipend = implode('', unpack('L', $DataEnd));
		if($ipend < 0) $ipend += pow(2, 32);
		$ipAllNum = ($ipend - $ipbegin) / 7 + 1;

		$BeginNum = 0;
		$EndNum = $ipAllNum;

		while($ip1num > $ipNum || $ip2num < $ipNum) 
		{
			$Middle= intval(($EndNum + $BeginNum) / 2);

			fseek($fd, $ipbegin + 7 * $Middle);
			$ipData1 = fread($fd, 4);
			if(strlen($ipData1) < 4)
			{
				fclose($fd);
				return 'System Error';
			}
			$ip1num = implode('', unpack('L', $ipData1));
			if($ip1num < 0) $ip1num += pow(2, 32);

			if($ip1num > $ipNum) 
			{
				$EndNum = $Middle;
				continue;
			}

			$DataSeek = fread($fd, 3);
			if(strlen($DataSeek) < 3) 
			{
				fclose($fd);
				return 'System Error';
			}
			$DataSeek = implode('', unpack('L', $DataSeek.chr(0)));
			fseek($fd, $DataSeek);
			$ipData2 = fread($fd, 4);
			if(strlen($ipData2) < 4) 
			{
				fclose($fd);
				return 'System Error';
			}
			$ip2num = implode('', unpack('L', $ipData2));
			if($ip2num < 0) $ip2num += pow(2, 32);

			if($ip2num < $ipNum) 
			{
				if($Middle == $BeginNum) 
				{
					fclose($fd);
					return 'Unknown';
				}
				$BeginNum = $Middle;
			}
		}

		$ipFlag = fread($fd, 1);
		if($ipFlag == chr(1)) 
		{
			$ipSeek = fread($fd, 3);
			if(strlen($ipSeek) < 3) 
			{
				fclose($fd);
				return 'System Error';
			}
			$ipSeek = implode('', unpack('L', $ipSeek.chr(0)));
			fseek($fd, $ipSeek);
			$ipFlag = fread($fd, 1);
		}

		if($ipFlag == chr(2)) 
		{
			$AddrSeek = fread($fd, 3);
			if(strlen($AddrSeek) < 3) 
			{
				fclose($fd);
				return 'System Error';
			}
			$ipFlag = fread($fd, 1);
			if($ipFlag == chr(2)) 
			{
				$AddrSeek2 = fread($fd, 3);
				if(strlen($AddrSeek2) < 3) 
				{
					fclose($fd);
					return 'System Error';
				}
				$AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
				fseek($fd, $AddrSeek2);
			} 
			else 
			{
				fseek($fd, -1, SEEK_CUR);
			}

			while(($char = fread($fd, 1)) != chr(0))
				$ipAddr2 .= $char;

			$AddrSeek = implode('', unpack('L', $AddrSeek.chr(0)));
			fseek($fd, $AddrSeek);

			while(($char = fread($fd, 1)) != chr(0))
				$ipAddr1 .= $char;
		} 
		else 
		{
			fseek($fd, -1, SEEK_CUR);
			while(($char = fread($fd, 1)) != chr(0))
				$ipAddr1 .= $char;

			$ipFlag = fread($fd, 1);
			if($ipFlag == chr(2)) 
			{
				$AddrSeek2 = fread($fd, 3);
				if(strlen($AddrSeek2) < 3) 
				{
						fclose($fd);
						return 'System Error';
				}
				$AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
				fseek($fd, $AddrSeek2);
			} 
			else 
			{
				fseek($fd, -1, SEEK_CUR);
			}
			while(($char = fread($fd, 1)) != chr(0))
				$ipAddr2 .= $char;
		}
		fclose($fd);

		if(preg_match('/http/i', $ipAddr2)) 
		{
			$ipAddr2 = '';
		}
		$ipaddr = "$ipAddr1 $ipAddr2";
		$ipaddr = preg_replace('/CZ88\.NET/is', '', $ipaddr);
		$ipaddr = preg_replace('/^\s*/is', '', $ipaddr);
		$ipaddr = preg_replace('/\s*$/is', '', $ipaddr);
		if(preg_match('/http/i', $ipaddr) || $ipaddr == '') 
		{
			$ipaddr = 'Unknown';
		}

		$ip=iconv('GBK','GBK//IGNORE',$ipaddr);
		$ip=explode(" ",$ip);
		$iparea=$ip[0];
		$stringcacheobj->set($key,$iparea);
	}

	return $iparea;
}

function is_ip($str)
{
	$ip = explode('.',$str);
	for($i=0;$i<count($ip);$i++)
	{  
		if($ip[$i]>255)
		{  
			return false;  
		}  
	}  
	return preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/',$str);  
}

function hideip($ip,$key=4)
{
	if(!is_ip($ip) || $key>4)return 'Unkonwn';
	$ip=explode(".",$ip);
	$ip[$key-1]='*';
	return implode(".",$ip);
}

function getIp($ishide=0)
{
	$ip='Unknown Ip';

	if(!empty($_SERVER['HTTP_CLIENT_IP']))
	{
		$ip=is_ip($_SERVER['HTTP_CLIENT_IP'])?$_SERVER['HTTP_CLIENT_IP']:$ip;
	}
	elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
	{
		$ip=is_ip($_SERVER['HTTP_X_FORWARDED_FOR'])?$_SERVER['HTTP_X_FORWARDED_FOR']:$ip;
	}
	else
	{
		$ip=is_ip($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:$ip;
	}

	return $ishide && is_ip($ip)?hideip($ip,3):$ip;
}

/*** 字符过滤相关 ***/

function sub_string($string, $length, $dot='')
{
	$string=trim($string);
	$strlen = strlen($string);
	if($strlen <= $length) return $string;
	$string = str_replace(array('&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
	$strcut = '';
	$dotlen = strlen($dot);
	$maxi = $length - $dotlen - 1;
	for($i = 0; $i < $maxi; $i++)
	{
		$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
	}
	$strcut = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), $strcut);
	return $strcut.$dot;
}

function la_safehtml($str,$rtype=4)
{
	$str=stripslashes($str);
	switch($rtype)
	{
		case '0': // 用 htmlspecialchars() 函数直接替换
			$str=htmlspecialchars($str);
			break;
		case '1': // 用 htmlspecialchars() 函数替换并除去连续空白字符
			$str=htmlspecialchars($str);
			$str=preg_replace('/[\s\v]{1,}/','',$str);
			break;
		case '2': // 用 htmlspecialchars() 函数替换并除去所有空白字符
			$str=htmlspecialchars($str);
			$str=preg_replace('/[\s\v]/','',$str);
			break;
		case '3': // 用 strip_tags() 函数替换并除去所有空白字符
			$str=strip_tags($str);
			$str=preg_replace('/[\s\v]/','',$str);
			break;
		default: // 去除 iframe,link,meta 等可能XSS的代码
			$str=preg_replace('/[\s\v]/',' ',$str);
			$str=preg_replace('/script/i','ｓｃｒｉｐｔ',$str);
			$str=preg_replace('/<[\/]?(link|ifra|fra|meta)[^>]*>/i','',$str);
			break;
	}
	return addslashes($str);
}

function la_batsafehtml($str,$rtype=4)
{
	if(is_string($str))return la_safehtml($str,$rtype);
	foreach($str as $key => $value)
	{
		$str[$key]=la_batsafehtml($value,$rtype);
	}
	return $str;
}

function la_stripslashes($str)
{
	if(!is_array($str))return stripslashes($str);
	foreach($str as $key => $value)
	{
		$str[$key]=la_stripslashes($value);
	}
	return $str;
}

function la_addslashes($str)
{
	if(!is_array($str))return addslashes($str);
	foreach($str as $key=>$value)
	{
		$str[$key]=la_addslashes($value);
	}
	return $str;
}

function la_htmlspecialchars($str)
{
	if(!is_array($str))return htmlspecialchars($str);
	foreach($str as $key=>$value)
	{
		$str[$key]=la_htmlspecialchars($value);
	}
	return $str;
}

function la_md5($str)
{
	return substr(md5($str),8,16);
}

/*** 文件（夹）操作相关 ***/

function get_basename($filename)
{  
	return preg_replace('/^.+[\\\\\\/]/', '', $filename);  
} 

function rmfiles($path)
{
	if(!file_exists($path))return true;
	$path = get_path($path);
	$list = glob($path.'*.*');
	foreach($list as $v)
	{
		@unlink($v);
	}
	return true;
}

function makedir($dirname) 
{	
	@chdir(SYSTEM_ROOT);
	if(file_exists($dirname) || !$dirname)return true;
	$dirname=strtolower(preg_replace('/[^0-9a-zA-Z_\-\/]/i','',str_replace('\\','/',$dirname)));
	$dirname=explode('/',$dirname);
	$dir_name='./';
	foreach($dirname as $childdir)
	{
		$dir_name.=$childdir.'/';
		if(!file_exists($dir_name) && !empty($childdir))
		{
			@mkdir($dir_name);
			@chmod($dir_name,0777);
		}
	}
	return true;
}

function rmdirs($path)
{
	$path=str_replace('\\','/',$path);
	$path=str_replace('//','/',$path);

	if(!file_exists($path))return true;

	/*
		简单安全检查  如果 文件夹下含有 rm.lock 则不能删除该文件夹 以及文件
	*/

	if(is_dir($path))
	{
		if(file_exists(str_replace('//','/',$path.'/rm.lock')))return false;
	}

	else
	{
		if(file_exists(dirname($path).'/rm.lock'))return false;
	}

	if(is_dir($path))
	{
		$path = get_path($path);
		$list = glob($path.'*');
		foreach($list as $v)
		{
			is_dir($v) ? rmdirs($v) : @unlink($v);
		}
		return rmdir($path);
	}
	else
	{
		return unlink($path);
	}
}

function get_path($path)
{
	$path = str_replace('\\', '/', $path);
	if(substr($path,-1) != '/') $path = $path.'/';
	return $path;
}

/*** 数组操作相关 ***/
function string2array($str)
{
	if($str=='') return array();
	if(is_array($str))return $str;

	$cachefile=SYSTEM_ROOT.'data/tmp/'.md5($str).'.array.php';
	$array="<?php\n//".date('Y-m-d H:i:s',time())."\nreturn ".$str.";\n?>";
	$strlen=file_put_contents($cachefile,$array);
	@chmod($cachefile,0777);

	$array=cache_read(md5($str).'.array.php',SYSTEM_ROOT.'data/tmp/');
	cache_delete(md5($str).'.array.php',SYSTEM_ROOT.'data/tmp/');
	return $array;
}

function searcharray($value,$arr=array())
{
	$result=false;

	foreach($arr as $v)
	{
		if(strpos($v,$value)!==FALSE)
		{
			$result=true;
			break;
		}
	}

	return $result;
}

function formatarray($formatstr)
{
	$re=array();
	$r=explode(',',$formatstr);
	foreach($r as $_r)
	{
		$t=explode(':',$_r);
		$re[$t[0]]=$t[1];
	}

	return $re;
}

function enformatarray($arr)
{
	$str=array();
	foreach($arr as $key =>$val)
	{
		$str[$key]=$key.':'.$val;
	}

	return implode(',',$str);
}

/*** 文件上传相关 ***/
function get_fileext($file)
{
	return strtolower(substr(strrchr($file,'.'),1));
}

function is_image($file)
{
	return in_array(get_fileext($file),array('gif','jpg','jpeg','png','bmp'));
}

function get_images($str)
{
	preg_match_all('/<img(.+?)src=[\'\"]?([^\'\"]+)[\'\"]?/i',stripslashes($str),$matches,PREG_PATTERN_ORDER);
	$r=array();
	$t=$matches[2];

	foreach($t as $_t)
	{
		if(is_image($_t))$r[]=$_t;
	}
	return $r;
}

function is_attchment($file)
{
	return in_array(get_fileext($file),array("rar" , "doc" , "docx" , "zip" , "pdf" , "txt" , "swf" , "wmv"));
}

function get_attchments($str)
{
	preg_match_all('/<a(.+?)href=[\'\"]?([^\'\"]+)[\'\"]?/i',stripslashes($str),$matches,PREG_PATTERN_ORDER);
	$r=array();
	$t=$matches[2];

	foreach($t as $_t)
	{
		if(is_attchment($_t))$r[]=$_t;
	}
	return $r;
}

function is_video($file)
{
	return in_array(get_fileext($file),array("flv" , "mp4" , "swf"));
}

/** 网络相关*/

function getdomain($url='')
{
	$r=parse_url($url);
	return $r['host']?$r['host']:getIp();
}

function getemailhost($email='')
{
	if(!preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i',$email) || !strpos($email,'@'))
	{
		return '';
	}

	$email=explode('@',$email);
	return $email[1];
}

function get_url_contents($url)
{
	if (ini_get("allow_url_fopen") == "1" && extension_loaded('open_ssl'))
	{
		return file_get_contents($url);
	}
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);   
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_URL, $url);
	$result =  curl_exec($ch);
	curl_close($ch);

	return $result;
}

function jsondecode($data)
{
	if(function_exists('json_decode'))
	{
		return json_decode($data);
	}
	else
	{
		include_once dirname(__FILE__).'/json.class.php';
		$json = new Services_JSON();
		return $json->decode($data);
	}
}
/** cookie 相关**/

function la_auth($str,$operation='ENCODE',$key='')
{
	$key=$key?$key:AUTH_KEY;
	$str=$operation == 'ENCODE'?$str:base64_decode($str);
	$len=strlen($key);
	$code='';
	for($i=0; $i<strlen($str); $i++){
		$k=$i%$len;
		$code.=$str[$i]^$key[$k];
	}
	$code=$operation=='DECODE'?$code:base64_encode($code);
	return $code;
}

function set_cookie($var,$value='',$time=0)
{
	$_COOKIE[$var] = $value;
	$time = $time > 0 ? $time : ($value == '' ? PHP_TIME - 3600 : 0);
	
	$secure=$_SERVER['SERVER_PORT']=='443'?true:false;
	$var = COOKIE_PRE.$var;
	$_COOKIE[$var] = $value;
	if(is_array($value))
	{
		foreach($value as $k=>$v)
		{
			setcookie($var.'['.$k.']',$v,$time,COOKIE_PATH,COOKIE_DOMAIN,$secure);
		}
	}
	else
	{
		setcookie($var,$value,$time,COOKIE_PATH,COOKIE_DOMAIN,$secure);
	}
}

function get_cookie($var)
{
	$var = COOKIE_PRE.$var;
	return isset($_COOKIE[$var])?$_COOKIE[$var]:false;
}

/** 字段读取 相关**/
function getsearchfield($enname='title',$modelid=1)
{
	global $db;
	$a=array();

	$modelid=intval($modelid);
	$enname=preg_replace('/[^a-z0-9_]/i','',$enname);
	$r=$db->fetch_one("SELECT * FROM `".LA_PRE."field` WHERE `".LA_PRE."field`.`modelid`=$modelid AND `".LA_PRE."field`.`enname`='$enname'");
	if($r)
	{
		$r=explode("\n",$r['options']);
		if($r)
		{
			foreach($r as $_r)
			{
				$_r=explode("|",$_r);
				$a[urlencode($_r[0])]=$_r[1];
			}
		}
	}

	return $a;
}

function getfield($value,$enname='title',$modelid=1)
{
	global $db;
	$value=trim($value);
	$modelid=intval($modelid);
	$enname=preg_replace('/[^a-z0-9_]/i','',$enname);

	$r=$db->fetch_one("SELECT * FROM `".LA_PRE."field` WHERE `".LA_PRE."field`.`modelid`=$modelid AND `".LA_PRE."field`.`enname`='$enname'");
	if(!$r)
	{
		return $value;
	}
	else
	{
		if(in_array($r['form'],array('text','textarea','number','image','datetime','fckeditor','map','area')))
		{
			return $value;
		}
		else if(in_array($r['form'],array('radio','select')))
		{
			$a=array();
			$v=explode("\n",$r['options']);
			if($v)foreach($v as $_v)
			{
				$t=explode('|',$_v);
				$a[$t[0]]=$t[1];
			}

			return $a[$value];
		}
		else if(in_array($r['form'],array('checkbox')))
		{
			$a=array();
			$v=explode("\n",$r['options']);
			if($v)foreach($v as $_v)
			{
				$t=explode('|',$_v);
				$a[$t[0]]=$t[1];
			}
			
			$t=explode(',',$value);
			$s='';
			foreach($t as $_t)
			{
				$s.=$a[$_t].'&nbsp;';
			}
			return $s;
		}
		else
		{
			return '';
		}
	}
}

function getarrayfield($enname='title',$modelid=1)
{
	global $db;
	$modelid=intval($modelid);
	$enname=preg_replace('/[^a-z0-9_]/i','',$enname);

	$r=$db->fetch_one("SELECT * FROM `".LA_PRE."field` WHERE `".LA_PRE."field`.`modelid`=$modelid AND `".LA_PRE."field`.`enname`='$enname'");
	if(!$r)
	{
		return array();
	}
	else
	{
		if(in_array($r['form'],array('radio','select')))
		{
			$a=array();
			$v=explode("\n",$r['options']);

			if($v)foreach($v as $_v)
			{
				$t=explode('|',$_v);
				$a[$t[0]]=$t[1];
			}

			return $a;
		}
	}
}

function morefield($mores,$limit="8") // 多字段调用 
{
	$result=$r=$t=array();
	if(!$mores)return $t;
	$t=explode(",",$mores);
	$i=1;
	if($t)foreach($t as $k => $_t)
	{
		if($_t && $i<=intval($limit))
		{
			$r=explode("`",$_t);
			$result[$k]['url']=$r[0];
			$result[$k]['name']=$r[1];
			$i++;
		}
	}
	return $result;
}

function areaname($areaid)
{
	global $db;
	$r=$db->fetch_one("SELECT * FROM `".LA_PRE."area` WHERE `".LA_PRE."area`.`id`=".intval($areaid));
	return $r?$r['name']:'不限';
}

function industyname($industyid)
{
	global $db;
	$r=$db->fetch_one("SELECT * FROM `".LA_PRE."industy` WHERE `".LA_PRE."industy`.`id`=".intval($industyid));
	return $r?$r['name']:'不限';
}

function lefttime($starttime,$expire=0)
{
	if(!$expire)
	{
		return 0;
	}
	else
	{
		$lefttime=$starttime+intval($expire)*24*3600-TIME;
		if($lefttime<0)
		{
			return -1;
		}
		else
		{
			return ceil($lefttime/(24*3600));
		}
	}
}

function formatlisturl($key='areaid',$value=0,$is_rewrite=0,$mod='news',$pagenum=1)
{
	global $page;
	$page=intval($page);

	$querystring=array();
	$_GET[$key]=urlencode($value);
	ksort($_GET);

	$_GET['page']=$page;
		
	foreach($_GET as $key => $val)
	{
		if($is_rewrite)
		{
			$querystring[]=$key.'-'.$val;
		}
		else
		{
			$querystring[]=$key.'='.$val;
		}
	}
	
	if($is_rewrite)
	{
		return LA_PATH.$mod.'/'.implode('-',$querystring).'.html';
	}
	else
	{
		return LA_PATH.'index.php?'.implode('&',$querystring);
	}
}

function base64_decode_eq($str)
{
	return base64_decode($str.'==');
}

function returnresult($url)
{
	$url=$url.'?d='.urlencode(SITE_URL);
	$status=GetHttpStatusCode($url);

	if($status==200)
	{
		return get_url_contents($url)==1?true:false;
	}

	return true;
}

function GetHttpStatusCode($url)
{
	$curl = curl_init();
	curl_setopt($curl,CURLOPT_URL,$url);
	curl_setopt($curl,CURLOPT_HEADER,1);
	curl_setopt($curl,CURLOPT_NOBODY,1);
	curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
	curl_setopt($curl,CURLOPT_TIMEOUT,30);
	curl_exec($curl);
	$rtn= curl_getinfo($curl,CURLINFO_HTTP_CODE);
	curl_close($curl);
	return  $rtn;
}

// 判断远程文件是否存在
function file_exists_url($url)
{
	if(substr($url,0,7)!='http://' && substr($url,0,6)!='ftp://')
	{
		return file_exists(SYSTEM_ROOT.$url);
	}

	if(extension_loaded('curl'))
	{
		$curl = curl_init($url); 
		curl_setopt($curl, CURLOPT_NOBODY, true); 
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
		$result = curl_exec($curl); 
		$feedback = false; 

		if ($result !== false)  
		{ 
			$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);   
			if ($statusCode == 200) 
			{ 
				$feedback = true;    
			} 
		} 
		curl_close($curl); 
		return $feedback; 
	}
	else
	{
		$feedback=@get_headers($url);
		return stripos($feedback[0], '200') ? true : false;
	}
}

/*
	安全相关
*/
function safecheck($file)
{
	$result='';
	if(get_fileext($file)!='css')
	{
		$file=strtolower(file_get_contents($file));
		if(strpos($file,'iframe'))
		{
			$result.='<font style="color:#FF0000">含有iframe</font>';
		}
	}
	return $result?$result:'<font style="color:#339900">安全</font>';
}

/* 图片处理*/

function imageinfo($image)
{
	$info=array();
	$t=basename($image);
	$t=explode('.',$t);
	$info['name']=$t[0];
	$info['size']=filesize($image);
	$imageinfo=getimagesize($image);
	$info['width']=$imageinfo[0];
	$info['height']=$imageinfo[1];
	$info['width_height']=$imageinfo[3];
	$info['mime']=$imageinfo['mime'];
	unset($imageinfo);
	$imageinfo=pathinfo($image);
	$info['path']=$imageinfo['dirname'].'/'; 
	$info['type']=strtolower($imageinfo['extension']);
	unset($imageinfo,$name);
	return $info;
}

function setwatermark($img='')
{
	global $LA;
	
	if(!$LA['uploadwatermarkenable'] || !in_array(get_fileext($img),array("gif", "png", "jpg", "jpeg", "bmp")))
	{
		return true;
	}

	if(is_file($img))
	{
		$imageinfo=imageinfo($img);
		$source_w=$imageinfo['width'];
		$source_h=$imageinfo['height'];
		$watermarkimg=SYSTEM_ROOT.$LA['uploadwatermark'];

		if($source_w<$LA['uploadwatermarkwidth'] || $source_h<$LA['uploadwatermarkheight'] || !is_file($watermarkimg))
		{
			return true;
		}

		$imagecreatefunc='imagecreatefrom'.($imageinfo['type']=='jpg'?'jpeg':$imageinfo['type']);
		$imagecreatefunc='imagecreatefrom'.($imageinfo['type']=='bmp'?'wbmp':($imageinfo['type']=='jpg'?'jpeg':$imageinfo['type']));
		$im=$imagecreatefunc($img);
		
		$watermarkinfo=imageinfo($watermarkimg);
		$width=$watermarkinfo['width'];
		$height=$watermarkinfo['height'];
		$watermarkcreatefunc='imagecreatefrom'.($watermarkinfo['type']=='jpg'?'jpeg':$watermarkinfo['type']);
		$watermark_im=$watermarkcreatefunc($watermarkimg);
		
		if($source_w<$width || $source_h<$height)
		{
			return true;
		}

		switch($LA['uploadwatermarkpos'])
		{
			case 0:
				$wx = mt_rand(0,($source_w - $width));
				$wy = mt_rand(0,($source_h - $height));
				break;
			case 1:
				$wx = 5;
				$wy = 5;
				break;
			case 2:
				$wx = ($source_w - $width) / 2;
				$wy = 5;
				break;
			case 3:
				$wx = $source_w - $width-5;
				$wy = 5;
				break;
			case 4:
				$wx = 5;
				$wy = ($source_h - $height) / 2;
				break;
			case 5:
				$wx = ($source_w - $width) / 2;
				$wy = ($source_h - $height) / 2;
				break;
			case 6:
				$wx = $source_w - $width-5;
				$wy = ($source_h - $height) / 2;
				break;
			case 7:
				$wx = 5;
				$wy = $source_h - $height-5;
				break;
			case 8:
				$wx = ($source_w - $width) / 2;
				$wy = $source_h - $height-5;
				break;
			default:
				$wx = $source_w - $width-5;
				$wy = $source_h - $height-5;
				break;
		}
		if($imageinfo['type'] == 'png') 
		{
			imagecopy($im, $watermark_im, $wx, $wy, 0, 0, $width, $height);
		} 
		else 
		{
			imagecopymerge($im, $watermark_im, $wx, $wy, 0, 0, $width, $height, $LA['uploadwatermarkpct']);
		}

		$imagefunc='image'.($imageinfo['type']=='jpg'?'jpeg':$imageinfo['type']);
		$imagefunc='image'.($imageinfo['type']=='bmp'?'wbmp':($imageinfo['type']=='jpg'?'jpeg':$imageinfo['type']));
		$imagefunc($im,$img);
		imagedestroy($im);
		return true;
	}

	return true;
}

function getareadomain2($areaid)
{
	global $db;
	$r=$db->fetch_one("SELECT * FROM `".LA_PRE."siteid` WHERE `".LA_PRE."siteid`.`areaid`=".intval($areaid));
	return $r?$r['siteurl']:'javascript:alert(\'该城市尚未开启分站，您可以联系我们加盟！\');return false;';
}

function areabycapitalize($c)
{
	global $db;
	return $db->fetch_all("SELECT * FROM `".LA_PRE."area` WHERE `".LA_PRE."area`.`c`='".preg_replace('/[^a-z0-9_]/i','',$c)."'");
}

function getbadwords()
{
	global $db;

	$r=$db->fetch_one("SELECT * FROM `".LA_PRE."badwords` WHERE `".LA_PRE."badwords`.`siteid`=".intval($_SESSION['siteid']));
	//print_r($r);
	return $r?$r['badwords']:'';
}

function setbadwords($badwords)
{
	global $db;
	return $db->insert(LA_PRE.'badwords',array('badwords'=>trim($badwords),'siteid'=>intval($_SESSION['siteid'])),true);
}
?>
