<?php
// +----------------------------------------------------------------------
// | 云业内容管理系统 (云业CMS或yunyecms)
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2030 http://www.yunyecms.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 刘晓飞 <15003219@qq.com>
// +----------------------------------------------------------------------
//YmM0OWM5ZWY1ODk5ZGRkNzM0NUxxUjVMaWE1WWFGNWE2NTU2Nmg1NUNHNTdPNzU3dWZJQ2prdXBIa3VKcERUVlBtaUpaNWRXNTVaV050Y3lrc1EyOXdlWEpwWjJoMElDaGpLU0F5TURFMkxUSXdNekFnYUhSMGNEb3ZMM2QzZHk1NWRXNTVaV050Y3k1amIyMGdRV3hzSUhKcFoyaDBjeUJ5WlhObGNuWmxaQzRnUVhWMGFHOXlPaURsaUpqbW1aUHBvNTRnUERFMU1EQXpNakU1UUhGeExtTnZiVDQ9OGQ3ZTc5OTU5YjQ0MmEyNWQxNGVlMzg2ZmQyODM2OTkzNGE
//MD5:c610bc3d074f2ea0c833d32de3bfa0c3
// +----------------------------------------------------------------------
function uaddslashes($string){
	if(!is_array($string)) return addslashes($string);
	foreach($string as $key => $val) $string[$key] = uaddslashes($val);
	return $string;
}
function ustripslashes($string){
	if(!is_array($string)) return stripslashes($string);
	foreach($string as $key => $val) $string[$key] = ustripslashes($val);
	return $string;
}
function uhtmlspecialchars($content) {
		$content = str_ireplace('%','%&lrm;',$content);
		$content = str_ireplace("<", "&lt;", $content);
		$content = str_ireplace(">", "&gt;", $content);
		$content = str_ireplace("\n", "<br/>", $content);
		//$content = str_replace(" ", "&nbsp;", $content);
		$content = str_ireplace('"', "&quot;", $content);
		$content = str_ireplace("'", "&#39;", $content);
		$content = str_ireplace("$", "&#36;", $content);
		//$content = str_replace('&','&amp;',$content);
		return $content;
}
function uhtmlspecialchars_decode($content) {
		$content = str_ireplace("&#36;","$",  $content);
		$content = str_ireplace("&#39;","'",  $content);
		$content = str_ireplace("&quot;",'"',  $content);
		//$content = str_replace("&nbsp;"," ",$content);
		$content = str_ireplace("<br/>","\n", $content);
		$content = str_ireplace("&gt;",">", $content);
		$content = str_ireplace("&lt;","<",  $content);
		$content = str_ireplace('%&lrm;','%',$content);
		//$content = str_replace('&amp;','&',$content);
		return $content;
}

function usafestr($string,$flitersql=1,$fliter_script=1,$fliter_xss=1) {
	$string=str_ireplace("%","",$string);
    $string = str_ireplace('%20','',$string);
    $string = str_ireplace('%27','',$string);
    $string = str_ireplace('%2527','',$string);
	$string=str_ireplace("\t","",$string);
    $string = str_ireplace('*','',$string);
    $string = str_ireplace("'",'',$string);
    $string = str_ireplace(';','',$string);
    //$string = str_replace("{",'',$string);
    //$string = str_replace('}','',$string);
	$string=str_ireplace("#","",$string);
	$string=str_ireplace("--","",$string);
	$string=str_ireplace("\"","",$string);
	$string=str_ireplace("/","",$string);
    $string = str_ireplace('\\','',$string);
	if($flitersql){
		$string=safestring::fliter_sql($string);
		}
	if($fliter_script){
		$string=safestring::fliter_script($string);
		}
	if($fliter_xss){
		$string=safestring::remove_xss($string);
	}
	$string=safestring::fliter_escape($string);
	$string=htmlspecialchars($string);
	$string = str_ireplace("$", "&#36;", $string);
	$string = str_ireplace("\n", "<br/>", $string);	
	$string = str_ireplace('%','%&lrm;',$string);
	$string=addslashes($string);
    return $string;
}

function usafepic($string,$flitersql=1,$fliter_script=1,$fliter_xss=1) {
	if(stripos($string,'/uploads/')!==0){
		 return false;
	}
	$string = str_ireplace('%2F','',$string);
	$string = str_ireplace('%5C','',$string);
	$string=str_ireplace("%","",$string);
	$string=str_ireplace("..\"","",$string);
	$string=str_ireplace("../","",$string);
    $string = str_ireplace('\\','',$string);
    $string = str_ireplace('//','',$string);
	$string = str_ireplace('%20','',$string);
    $string = str_ireplace('%27','',$string);
    $string = str_ireplace('%2527','',$string);
	$string=str_ireplace("\t","",$string);
    $string = str_ireplace('*','',$string);
    $string = str_ireplace("'",'',$string);
    $string = str_ireplace(';','',$string);
    //$string = str_replace("{",'',$string);
    //$string = str_replace('}','',$string);
	$string=str_ireplace("#","",$string);
	$string=str_ireplace("--","",$string);

	if($flitersql){
		$string=safestring::fliter_sql($string);
		}
	if($fliter_script){
		$string=safestring::fliter_script($string);
		}
	if($fliter_xss){
		$string=safestring::remove_xss($string);
	}
	$string=safestring::fliter_escape($string);
	$string=htmlspecialchars($string);
	$string = str_ireplace("$", "&#36;", $string);
	$string = str_ireplace("\n", "<br/>", $string);	
	$string = str_ireplace('%','%&lrm;',$string);
	$string=addslashes($string);
    return $string;
  }


function yytrim($string){
	if(is_array($string)){
		foreach($string as $key=>$var){
			$string[$key]=usafestr(trim($var));
		}
	  }else{
	$string=usafestr(trim($string));
	}
	return $string;
}

/*	if (!get_magic_quotes_gpc()) {   
		 uaddslashes($_GET);   
		 uaddslashes($_POST);   
		 uaddslashes($_COOKIE);   
	}*/   
	  function uhtmldecode($str)
      {
      if(empty($str)) return;
      if($str=="") return $str;
      $str=str_replace("sel&#101;ct","select",$str);
      $str=str_replace("jo&#105;n","join",$str);
      $str=str_replace("un&#105;on","union",$str);
      $str=str_replace("wh&#101;re","where",$str);
      $str=str_replace("ins&#101;rt","insert",$str);
      $str=str_replace("del&#101;te","delete",$str);
      $str=str_replace("up&#100;ate","update",$str);
      $str=str_replace("lik&#101;","like",$str);
      $str=str_replace("dro&#112;","drop",$str);
      $str=str_replace("cr&#101;ate","create",$str);
      $str=str_replace("mod&#105;fy","modify",$str);
      $str=str_replace("ren&#097;me","rename",$str);
      $str=str_replace("alt&#101;r","alter",$str);
      $str=str_replace("ca&#115;","cast",$str);
      $str=str_replace("&amp;","&",$str);
      $str=str_replace("&gt;",">",$str);
      $str=str_replace("&lt;","<",$str);
      $str=str_replace("&nbsp;",chr(32),$str); 
      $str=str_replace("&nbsp;",chr(9),$str);
      // $str=str_replace("&#160;&#160;&#160;&#160;",chr(9),$str);
      $str=str_replace("&",chr(34),$str);
      $str=str_replace("&#39;",chr(39),$str);
      $str=str_replace("<br />",chr(13),$str);
      $str=str_replace("''","'",$str);
      return $str;
      }
        //编码
      function uhtmlencode($str)
      {
      if(empty($str)) return;
      if($str=="") return $str;
      $str=trim($str);
      $str=str_replace("&","&amp;",$str);
      $str=str_replace(">","&gt;",$str);
      $str=str_replace("<","&lt;",$str);
      $str=str_replace(chr(32),"&nbsp;",$str);
      $str=str_replace(chr(9),"&nbsp;",$str);
      // $str=str_replace(chr(9),"&#160;&#160;&#160;&#160;",$str);
      $str=str_replace(chr(34),"&",$str);
      $str=str_replace(chr(39),"&#39;",$str);
      $str=str_replace(chr(13),"<br />",$str);
      $str=str_replace("'","''",$str);
      $str=str_replace("select","sel&#101;ct",$str);
      $str=str_replace("join","jo&#105;n",$str);
      $str=str_replace("union","un&#105;on",$str);
      $str=str_replace("where","wh&#101;re",$str);
      $str=str_replace("insert","ins&#101;rt",$str);
      $str=str_replace("delete","del&#101;te",$str);
      $str=str_replace("update","up&#100;ate",$str);
      $str=str_replace("like","lik&#101;",$str);
      $str=str_replace("drop","dro&#112;",$str);
      $str=str_replace("create","cr&#101;ate",$str);
      $str=str_replace("modify","mod&#105;fy",$str);
      $str=str_replace("rename","ren&#097;me",$str);
      $str=str_replace("alter","alt&#101;r",$str);
      $str=str_replace("cast","ca&#115;",$str);
      return $str;
      }
function  yypwd($password){
	$pwd=md5('~*Y^U^N-Y&*E^=(C^&M#&*S'.md5(SHA1($password.'l~#i#~u^').'x#i#a^o-f^e^i'));
	return $pwd;
}
function YUNYECMSadmPwd($password,$salt){
	$pwd=md5($salt.'~*Y^U^N-Y&*E$^=(C^&M#&*S'.md5(SHA1($password.'l~#i#~u^').$salt.'x#i#a^o-f^e^i').$salt);
	return $pwd;
}
function GetCurdir(){
	return str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',dirname(__FILE__)));
}
function make_rand($length = 8 ){  
    $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',  
    'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's',  
    't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D',  
    'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O',  
    'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z',  
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!',
    '@','#', '$', '%', '^', '&', '*', '(', ')', '-', '_',  
    '[', ']', '{', '}', '<', '>', '~', '`', '+', '=', ',', 
    '.', ';', ':', '/', '?', '|');
    $keys = array_rand($chars, $length);  
    $rerand = '';  
    for($i = 0; $i < $length; $i++)
    {  
        $rerand .= $chars[$keys[$i]];
    }  
    return $rerand;  
}  

function make_rand_letternum($length = 8 ){  
    $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',  
    'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's',  
    't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D',  
    'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O',  
    'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z',  
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
    $keys = array_rand($chars, $length);  
    $rerand = '';  
    for($i = 0; $i < $length; $i++)
    {  
        $rerand .= $chars[$keys[$i]];
    }  
    return $rerand;  
} 

function make_rand_letter($length =4){  
    $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',  
    'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's',  
    't', 'u', 'v', 'w', 'x', 'y','z');
    $keys = array_rand($chars, $length);  
    $rerand = '';  
    for($i = 0; $i < $length; $i++)
    {  
        $rerand .= $chars[$keys[$i]];
    }  
    return $rerand;  
}  


function yyact_get($act=""){
	 $yyact="";
	 if(isset($_GET)){
		 if(array_key_exists("yyact",$_GET)){$yyact=uhtmlspecialchars($_GET['yyact']);}else{ $yyact=$act;  }
	 }else{
	 $yyact=$act;
	 }
	 return $yyact;
}
function yyact_post($act=""){
	 $yyact="";
	 if(isset($_POST)){
		 if(array_key_exists("yyact",$_POST)){ $yyact=uhtmlspecialchars($_POST['yyact']);}else{ $yyact=$act;  }
	 }else{
	 $yyact=$act;
	 }
	 return $yyact;
}
/**
* 语言文件处理
* @param	string		$language	标示符
* @param	array		$pars	转义的数组,二维数组 ,'key1'=>'value1','key2'=>'value2',
* @param	string		$modules 多个模块之间用半角逗号隔开，如：member,guestbook
* @return	string		语言字符
*/
function Lan($language = 'no_language',$pars = array(), $modules = '') {
	static $LANG = array();
	static $LANG_MODULES = array();
	static $lang = '';
	if(defined('IN_YUNYECMSAdmin')) {
		$lang = YUNYECMS_LAN ? YUNYECMS_LAN : 'gb';
	 }else{
		$lang = LAN ? LAN : 'cn';
	  }
	if(!$LANG){
		if(defined('IN_YUNYECMSAdmin')) {
		require_once YUNYECMS_CORE.'admin'.DIRECTORY_SEPARATOR.'language'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'admin.lang.php';
        require_once YUNYECMS_CORE.'admin'.DIRECTORY_SEPARATOR.'language'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'admin_menu.lang.php';		if(file_exists(YUNYECMS_CORE.'admin'.DIRECTORY_SEPARATOR.'language'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php')) require_once YUNYECMS_CORE.'admin'.DIRECTORY_SEPARATOR.'language'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php';	
		}else{
		  if(file_exists(YUNYECMS_CORE.'language'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php')) require_once YUNYECMS_CORE.'language'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php';
		  require_once YUNYECMS_CORE.'language'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'common.lang.php';	
		}
	}
	if(!empty($modules)) {
		$modules = explode(',',$modules);
		foreach($modules AS $m) {
			if(!isset($LANG_MODULES[$m])) require_once YUNYECMS_CORE.'language'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.$m.'.lang.php';
		}
	}
	if(!array_key_exists($language,$LANG)) {
		return $language;
	}else {
		$language = $LANG[$language];
		if($pars) {
			foreach($pars AS $_k=>$_v) {
				$language = str_replace('{'.$_k.'}',$_v,$language);
			}
		}
		return $language;
	}
 }
function tpl_adm($template = 'main'){	
 $file =  YUNYECMS_CORE.'admin/tpl/'.$template.'.tpl.php';
 if(file_exists($file)) return $file;
  else{
	exit('The "'.$file .'" template file does not exist');
   }
}

function yunyecms_getarrayvalue($arr,$key,$subkey=""){
	 if(empty($key)||empty($arr)) return 0;
	 if(array_key_exists($key,$arr)){
		 if(empty($subkey)){
			 return $arr[$key];
		  }else{
			  if(array_key_exists($subkey,$arr[$key])){
				  return $arr[$key][$subkey];
				  }else{
					  return 0; 
					  }
			  }
		 }else{
			 return 0;
			 }
 }
function yunyecms_strencode($string,$salt='~^y#u%n$y^e*c%m^s^~'){
	return base64_encode(substr(md5($salt),8,18).base64_encode($string).substr(sha1($salt),0,35));
}
function yunyecms_strdecode($string,$salt='~^y#u%n$y^e*c%m^s^~'){
	$retstr=base64_decode($string);
	$SHA1salt=substr(sha1($salt),0,35);
	$md5salt=substr(md5($salt),8,18);
    $retstr=substr($retstr,strlen($md5salt));
    $retstr=substr($retstr,0,(strlen($retstr)-strlen($SHA1salt)));
	return base64_decode($retstr);
}
function yunyecms_strrange_encode($string,$salt='~^y#u%n$y^e*c%m^s^~',$range){
	$rangearr=yunyecms_json_decode($range);
	return base64_encode(substr(md5($salt),$rangearr['md5']['min'],$rangearr['md5']['max']).base64_encode($string).substr(sha1($salt),$rangearr['sha1']['min'],$rangearr['sha1']['max']));
}
function yunyecms_strrange_decode($string,$salt='~^y#u%n$y^e*c%m^s^~',$range){
	$retstr=base64_decode($string);
	$rangearr=yunyecms_json_decode($range);
	$SHA1salt=substr(sha1($salt),$rangearr['sha1']['min'],$rangearr['sha1']['max']);
	$md5salt=substr(md5($salt),$rangearr['md5']['min'],$rangearr['md5']['max']);
    $retstr=substr($retstr,strlen($md5salt));
    $retstr=substr($retstr,0,(strlen($retstr)-strlen($SHA1salt)));
	return base64_decode($retstr);
}
 function  yunyecms_json_decode($encodestr){
	 return json_decode(base64_decode($encodestr),true);
	}
 function  yunyecms_json_encode($sarray){
	 return base64_encode(json_encode($sarray));
	}
	
function DelADMFileRnd($userid){
	$path=YUNYECMS_DATA.'admin/admlogin/';
	if(!is_dir($path)) @mkdir($path, 0777, true);
	$hand=@opendir($path);
	while($file=@readdir($hand))
	{
		if($file=='.'||$file=='..')
		{
			continue;
		}
		if(strstr($file,'user'.$userid.'_'))
		{
			@unlink($path.$file);
		}
	}
}

function CreateCookieRnd($userid,$username,$rnd,$roleid,$logintime){
	$ip=getip();
	$yunyecmsckpass=md5(md5($rnd.SAFE_ADMCOOKIERND).'-'.$ip.'-'.$_SERVER['HTTP_USER_AGENT'].'-'.$userid.'-'.$username.'-'.$rnd.$roleid);
	usetcookie("loginyunyecmsckpass",$yunyecmsckpass,1);
	$file=YUNYECMS_DATA.'admin/admlogin/user'.$userid.'_'.md5(md5($username.'-yunyecms_^^_^usercookie'.$logintime.'-'.$rnd.SAFE_ADMCOOKIERND).'-'.$ip.'-'.$userid.'-'.$rnd.'-'.$roleid).'.php';
	$filetext=GetAdminLoginFile($userid);
	fwritetext($file,$filetext);
}

//返回用户缓存信息
function GetAdminLoginFile($userid){
	$adminlogins='';
	$ernd=make_rand_letternum(27);
	$erndtwo=make_rand_letternum(20);
	$erndadd=make_rand_letternum(32);
	$ehash=make_rand_letternum(10);
	$ehashname='usv_'.make_rand_letternum(4);
	$rhash=make_rand_letternum(6);
	$rhashname='dsv_'.make_rand_letternum(4);
	$userid=(int)$userid;
	$defhash=$ehashname.'='.$ehash.'||'.$rhashname.'='.$rhash.'||'.$ernd.'||'.$erndtwo;
	define('YUNYECMSDefHash',$defhash);
	$adminlogins.="<?php
\$yunyecms_admlogin=array();
\$yunyecms_admlogin=array('userid'=>'".$userid."',
'ernd'=>'".addslashes($ernd)."',
'erndtwo'=>'".addslashes($erndtwo)."',
'erndadd'=>'".addslashes($erndadd)."',
'ehash'=>'".addslashes($ehash)."',
'ehashname'=>'".addslashes($ehashname)."',
'rhash'=>'".addslashes($rhash)."',
'rhashname'=>'".addslashes($rhashname)."');
?>";
	usetcookie("loginyunyecmsfilernd",$ernd,1);
	return $adminlogins;
}

function GetYunyecmsHashStrDef($wh=0,$yunyecms='ehref'){
	if(SAFE_CKHASH==1)//关闭HASH模式
	{
		return '';
	}
	$str='';
	$fh=$wh?'?':'&';
	$hr=explode('||',YUNYECMSDefHash);
	if($yunyecms=='href')
	{
		if(SAFE_CKHASH==0)
		{
			$str=$fh.$hr[0].'&'.$hr[1];
		}
	}
	elseif($yunyecms=='ehref')
	{
		$str=$fh.$hr[0];
	}
	return $str;
}

function GetyunyecmsHashStrAll(){
	global $yunyecms_admlogin;
	$ehashvar=$yunyecms_admlogin['ehashname'];
	$ehash=$yunyecms_admlogin['ehash'];
	$rhashvar=$yunyecms_admlogin['rhashname'];
	$rhash=$yunyecms_admlogin['rhash'];	
	//返回
	if(SAFE_CKHASH==1)//关闭HASH模式
	{
		$hashurl['svg']='';
		$hashurl['svp']='';
		$hashurl['usvg']='';
		$hashurl['usvp']='';
	}
	else
	{
		$hashurl['svg']='&'.$ehashvar.'='.$ehash.'&'.$rhashvar.'='.$rhash;
		$hashurl['svp']='<input type=hidden name='.$ehashvar.' value='.$ehash.'><input type=hidden name='.$rhashvar.' value='.$rhash.'>';
		$hashurl['usvg']='&'.$ehashvar.'='.$ehash;
		$hashurl['usvp']='<input type=hidden name='.$ehashvar.' value='.$ehash.'>';
	}
	return $hashurl;
}

function GetyunyecmsHash(){
	global $yunyecms_admlogin;
	$ehashvar=$yunyecms_admlogin['ehashname'];
	$ehash=$yunyecms_admlogin['ehash'];
	$rhashvar=$yunyecms_admlogin['rhashname'];
	$rhash=$yunyecms_admlogin['rhash'];	
		$hashurl['ehashvar']=$ehashvar;
		$hashurl['ehash']=$ehash;
		$hashurl['rhashvar']=$rhashvar;
		$hashurl['rhash']=$rhash;
	return $hashurl;
}

function YUNYECMS_CHECKCookieRnd($userid,$username,$rnd,$roleid,$logintime){
	$ip=getip();
	$yunyecmsckpass=md5(md5($rnd.SAFE_ADMCOOKIERND).'-'.$ip.'-'.$_SERVER['HTTP_USER_AGENT'].'-'.$userid.'-'.$username.'-'.$rnd.$roleid);
	if($yunyecmsckpass!=ugetcookie('loginyunyecmsckpass',1))
	{
	    messagebox(Lan('adminlogin_notlogin'),url_admin('init','login'),"warn");	
	}
	DoECheckFileRnd($userid,$username,$rnd,$roleid,$logintime,$ip);
	//ehash
   if($_SERVER['REQUEST_URI']!="/admin.php")hCheckyunyecmsEHash();
}

function DoECheckFileRnd($userid,$username,$rnd,$roleid,$logintime,$ip){
	global $yunyecms_admlogin;
	$file=YUNYECMS_DATA.'admin/admlogin/user'.$userid.'_'.md5(md5($username.'-yunyecms_^^_^usercookie'.$logintime.'-'.$rnd.SAFE_ADMCOOKIERND).'-'.$ip.'-'.$userid.'-'.$rnd.'-'.$roleid).'.php';
	if(!file_exists($file))
	{
	    messagebox(Lan('adminlogin_OneUser'),url_admin('init','login'),"warn","top");
	}
	include($file);
	hCheckAadminLoginFileInfo();
}

function hCheckAadminLoginFileInfo(){
	global $yunyecms_admlogin;
	if(!$yunyecms_admlogin['ernd']||$yunyecms_admlogin['ernd']!=ugetcookie('loginyunyecmsfilernd',1))
	{
	    messagebox(Lan('adminlogin_notlogin'),url_admin('init','login'),"warn");	
	}
}

function hCheckyunyecmsEHash(){
	global $yunyecms_admlogin;
	if(SAFE_CKHASH==1)//关闭HASH模式
	{
		return '';
	}
	$ehashvar=$yunyecms_admlogin['ehashname'];
	$ehash=$yunyecms_admlogin['ehash'];
	$rhashvar=$yunyecms_admlogin['rhashname'];
	$rhash=$yunyecms_admlogin['rhash'];
	if(empty($_GET[$ehashvar])&&empty($_POST[$ehashvar])){
		messagebox(Lan('admin_failhash'),'back',"warn");	
	  }
	if(!empty($_POST)){
		 if(empty($_POST[$ehashvar])){
			 messagebox(Lan('admin_failhash'),'back',"warn");	
		 }else{
			 if($_POST[$rhashvar]!=$rhash||$_POST[$ehashvar]!=$ehash){
				 messagebox(Lan('admin_failhash'),'back',"warn");	
			 }
		 }
	}
	if(!empty($_GET)){
		 if(empty($_GET[$ehashvar])){
			 messagebox(Lan('admin_failhash'),'back',"warn");	
		 }else{
			 if($_GET[$ehashvar]!=$ehash){
				 messagebox(Lan('admin_failhash'),'back',"warn");	
			 }
		 }
	 }	

   }

function getlist($strsql,$db=array()) {
	 if(empty($db)) $db=core::load_model('common_model');
	 $datalist=$db->select($strsql);
	 return $datalist;
}

function getone($strsql,$db=array()) {
	 global $db;
	 $datalist=$db->find($strsql);
	 return $datalist;
}

function query($strsql,$db=array()) {
	 if(empty($db)) $db=core::load_model('common_model');
	 $query=$db->query($strsql);
	 return $query;
 }

 function getcount($strsql){
	   if(empty($db)) $db=core::load_model('common_model');
		$data=$db->GetCount($strsql);
		return $data;
	}

//获取所有的子分类ID
function getsubcatid($catid,&$rs=array()) {
	  if($catid!==false){
			$strsql="select id from `#yunyecms_category` where `pid`= {$catid}";
			$subarr=getlist($strsql);
		   if(!empty($subarr)){
			 foreach($subarr as $key=>$var){
				$rs[]=$var["id"];
				getsubcatid($var["id"],$rs);
				}
			  }
		}
	return $rs;
}
/*
 * 获取分类下所有子分类，并将返回的数据用逗号隔开
 * @param $catid 分类ID
 */
function getcatin($catid) {
	 $rs=getsubcatid($catid);
	 $rs[]=$catid;
	 $retstr=implode(',', $rs);
	 return $retstr;
}

/*
 * 获取分类下所有子分类，包含本分类
 * @param $catid 分类ID
 */
function get_cat_child($catid) {
	 $rs=getsubcatid($catid);
	 if($catid)  $rs[]=$catid;
	 return $rs;
}

/*
 * 返回子分类和当前分类之间的级数
 * @param $catid  当前分类ID
 * @param $subcatid  当前子分类ID
 */
//
function getrank($subcatid,$catid) {
	 $rank =0; 
	 calcrank($subcatid,$catid,$rank);
	 return $rank;
}	 
/*
 * 递归计算分类的级数
 * @param $catid  当前分类ID
 * @param $subcatid  当前子分类ID
 * @param $rank  要计算的级数
 */
//
function calcrank($subcatid,$catid,&$rank) {
	  if($subcatid){
		 $ranktemp=0;
		 $strsql="select id,pid from `#yunyecms_category` where `id`= {$subcatid}";
		 $curcategory=getone($strsql);
		  if(!empty($curcategory)){
			        $pid=$curcategory["pid"];
				    $rank=$rank+1;
			        if($pid==$catid){
					  $ranktemp=$rank;
				    }
			       if($rank>$ranktemp){
			  	      calcrank($pid,$catid,$rank);
				   }
			  }
		   }else{
			return 0;
		  }
    }

function dosubcat($pid,&$rs,$level,$dpid) {
		  $strsql="select id,pid,title from `#yunyecms_category` where `pid`= {$pid}";
		  $subarr=getlist($strsql);
		  if(!empty($subarr)){
			 if($level){
			 foreach($subarr as $key=>$var){
				   $sid=$var["id"];
				   if($dpid){
				   $curlevel=getrank($sid,$dpid);
				   }else{
				   $curlevel=getlevel($sid);
				   }
				    $rs[]=$var;
					if($curlevel<=$level){
					    dosubcat($sid,$rs,$level,$dpid);
					 }
				  }
			   }else{
				    $rs[]=$subarr;
			  }
		}
}

//获取指定分类和级数的分类
function getcat($pid=0,$level=0,$num=0,$lang,$isfoot=0,$catid=""){
	  //dosubcat($pid,$rs,$level,$pid);
	  return getcatTree($pid,$pid,$level,$num,$lang,$isfoot,0,$catid);
}

/*
 * 递归计算分类的级数
 * @param $pid  需要获取的父ID
 * @param $opid  原始父ID
 * @param $level  需要获取的级数
 */
//
function getcatTree($pid,$opid,$level,$num,$lang,$isfoot,$rant,$catid="") {
	      $tree = array();
	      if(!is_numeric($pid)){
			  exit(" category id error");
		  }
		  $strsql="select id,pid,title,modelid,exlink,pic,lang,syn,dismode,catdir from `#yunyecms_category` where `pid`= {$pid} and lang={$lang} and  status=1 and title<>'' order by `ordernum` asc ,`id` asc";
	      if(!empty($num)&&$rant==0){
			 $strsql=$strsql." limit 0,$num";  
		  }
	      if($rant==0){
			  	 $strsql="select id,pid,title,modelid,exlink,pic,lang,syn,dismode,catdir from `#yunyecms_category` where `pid`= {$pid} and lang={$lang}  and isdisplay=1 and status=1 and title<>'' " ;
			     $wherestr="";
			     $limitstr="";
			     $orderstr=' order by `ordernum` asc ,`id` asc ';
			     if(!empty($catid)){
				   $wherestr=" and id in($catid) ";
				 }
			     if(!empty($isfoot)){
					 $wherestr=$wherestr." and isfoot=1 ";  
				  }
			  	 if(!empty($num)){
				   $limitstr=" limit 0,$num";
				  }
				 $strsql= $strsql.$wherestr.$orderstr.$limitstr;
		  }
		  $subarr=getlist($strsql);
		  if(!empty($subarr)){
			 foreach($subarr as $key=>$var){
				  if($level){
				   $sid=$var["id"];
						   if($opid){
						    $curlevel=getrank($sid,$opid);
						   }else{
						    $curlevel=getlevel($sid);
						   }
                    $var['level'] = $curlevel;
					if($curlevel<=$level){
                       $var['child'] = getcatTree($sid,$opid,$level,$num,$lang,$isfoot,$rant+1);
						$modeltype=empty($var['dismode'])?getmodeltype($var["modelid"]):"home";
						if(ROUTE_M!="content") $pathurl='content/index/'.$modeltype; else $pathurl=$modeltype;
						if($var['pic']) $var['pic']=dopic($var['pic']);
						$urlstr=geturl_listpage($modeltype,$var);
						$var['url']=!empty($var['exlink'])?$var['exlink']:$urlstr;
					   $tree[]=$var;
					 }
				    }else{
					    $var['child'] = array();
						$modeltype=empty($var['dismode'])?getmodeltype($var["modelid"]):"home";
						if($var['pic']) $var['pic']=dopic($var['pic']);
						if(ROUTE_M!="content") $pathurl='content/index/'.$modeltype; else $pathurl=$modeltype;
					    $urlstr=geturl_listpage($modeltype,$var);
						$var['url']=!empty($var['exlink'])?$var['exlink']:$urlstr;
					   $tree[]=$var;
					}
				  }
			   }
	    return $tree;
}
  //列表页url
   function geturl_listpage($modeltype,$cat){
	    $urlstr="";
	    $catid=$cat['id'];
	    $child_id=$cat['child'][0]['id'];
	    if(URL_MODEL==5){
	   	    $rootcat=getbyid(getppid($catid));
			$langid=$cat['lang'];
			$curlang=getone("select isdefault,landir from `#yunyecms_lang` where id='{$langid}'");
			if(!$curlang['isdefault']){
				$rootdir=ROOT.$curlang['landir'].'/';
			}else{
				$rootdir=ROOT;
			}
		    if($catid!=$rootcat['id']){
				$urlstr=$rootdir.$rootcat['catdir'].'/'.$cat['catdir'].'/index.html';
			}else{
			  if($modeltype=='singlepage'||$modeltype=='customform'){
				  if($cat['child']){
					 $urlstr=$rootdir.$rootcat['catdir'].'/'.$cat['child'][0]['catdir'].'/index.html';
				  }else{
					 $urlstr=$rootdir.$rootcat['catdir'].'/index.html';
				  } 	 
			  }else{
				$urlstr=$rootdir.$rootcat['catdir'].'/index.html';
			  }
		    }
		 }else{
			  if(ROUTE_M!="content") $pathurl='content/index/'.$modeltype; else $pathurl=$modeltype;
			  if(URL_ROUTE&&URL_MODEL!=0){
			   if($modeltype=='singlepage'||$modeltype=='customform'){
				  $urlstr=empty($child_id)?  url("/{$modeltype}/{$catid}"):url("/{$modeltype}/{$child_id}");
			   }else{
				  $urlstr=url("/{$modeltype}/{$catid}");
			   }
			  }else{
				 if($modeltype=='singlepage'||$modeltype=='customform'){
				   $urlstr= empty($child_id)? url($pathurl,array('catid'=>$catid)):url($pathurl,array('catid'=>$child_id));
				 }else{
				   $urlstr=url($pathurl,array('catid'=>$catid));
				}
			 }
			
		}
		return $urlstr;
     }
  //内容页url
   function geturl($catid,$id,$modeltype='lists'){
	     $urlstr="";
	    if(URL_MODEL==5){
			$cat=getone("select lang,catdir from `#yunyecms_category` where id='{$catid}'");
	   	    $rootcat=getbyid(getppid($catid));
			$langid=$cat['lang'];
			$curlang=getone("select isdefault,landir from `#yunyecms_lang` where id='{$langid}'");
			if(!$curlang['isdefault']){
				$rootdir=ROOT.$curlang['landir'].'/';
			}else{
				$rootdir=ROOT;
			}
		    if($catid!=$rootcat['id']){
				$urlstr=$rootdir.$rootcat['catdir'].'/'.$cat['catdir'].'/'.$id.'.html';
			}else{
			 	$urlstr=$rootdir.$rootcat['catdir'].'/'.$id.'.html';
		    }
		 }else{
			  if(URL_ROUTE&&URL_MODEL!=0){
				 if($modeltype=="singlepage"){
					 $pathurl='/'.$modeltype;
				     $urlstr=url("{$pathurl}/{$catid}");
				 }else{
					 $pathurl='/info';
					 $urlstr=url("{$pathurl}/{$catid}/{$id}");
				 }
			  }else{
				 if($modeltype=="singlepage") $pathurl=$modeltype; else $pathurl='show';
				  $urlstr= url($pathurl,array('catid'=>$catid,'id'=>$id));
			 }
		}
			return $urlstr;
     }


function getinfocount($mid,$catid){
     $modelinfo=getmodel($mid);
     $str=0;
    if($modelinfo){
			$subcatids=getcatin($catid);
			$strsql="select count(*) from `#yunyecms_m_{$modelinfo['tablename']}` where `catid` in({$subcatids})";
            $str=getcount($strsql);
    }
    return $str;
}

//根据指定ID获取父目录树
function getparentTree($catid) {
	      $tree = array();
		  $strsql="select id,pid,title,modelid,exlink,syn,lang from `#yunyecms_category` where `id`= {$catid} ";
		  $parentarr=getone($strsql);
		  if(!empty($parentarr)){
				   $pid=$parentarr["pid"];
					if($pid>=0){
                        $parentarr['parent'] = getparentTree($pid);
				        $modeltype=getmodeltype($parentarr["modelid"]);
						$cid=$parentarr["id"];
					    if($modeltype=='singlepage'){
							     $strsql2="select id,pid,title,modelid,exlink,syn,lang from `#yunyecms_category` where `pid`= {$cid}";
							     $var_singlepage=getone($strsql2);
							     if($var_singlepage){
									 $parentarr['url']=url($modeltype,array('catid'=>$var_singlepage['id'])); 
								 }else{
									 $parentarr['url']=url($modeltype,array('catid'=>$cid)); 
									 
								 }
								if($parentarr['exlink']){
									 $parentarr['url']=$parentarr['exlink'];
								 }
							 }else{
								$parentarr['url']=url($modeltype,array('catid'=>$cid)); 
						 }
					   $tree[]=$parentarr;
					 }
			   }
	    return $tree;
}

function getbreadcumb($catid,&$rs=array()) {
	  if($catid){
		  $strsql="select id,pid,title,modelid,exlink,syn,lang from `#yunyecms_category` where `id`= {$catid}";
		  $curarr=getone($strsql);
		  if(!empty($curarr)){
			    $pid=$curarr["pid"];
                        $modeltype=getmodeltype($curarr["modelid"]);
						$cid=$curarr["id"];
					    if($modeltype=='singlepage'){
							     $strsql2="select id,pid,title,modelid,exlink,syn,lang from `#yunyecms_category` where `pid`= {$cid}";
							     $var_singlepage=getone($strsql2);
							     $singleurl=$var_singlepage?url("/{$modeltype}/{$var_singlepage['id']}"):url("/{$modeltype}/{$cid}");
								 $curarr["url"]=!empty($curarr['exlink'])?$curarr['exlink']:$singleurl; 
							 }else{
								 $curarr["url"]=!empty($curarr['exlink'])?$curarr['exlink']:url("/{$modeltype}/{$cid}"); 
						 }			  
			     $rs[]=$curarr;
			     if($pid>=0){
			         getbreadcumb($pid,$rs);
				   }
			  }

		  }
		  return array_reverse($rs);
     }

 function  getmodel($modelid,$db=null){
	    if(empty($modelid)) {
			return false;
		}else{
		 $strsql="select * from `#yunyecms_model` where `modelid`= {$modelid}";
		 $curmodel=getone($strsql,$db);
		 if(empty($curmodel)){
			 return false;
		  }else{
			 return $curmodel;
			  }
		 }	 
	}

//通过ID获取内容
 function  getbyid($id,$tablename='category'){
	    if(empty($id)) {
			return false;
		}else{
		 $strsql="select * from `#yunyecms_{$tablename}` where `id`= {$id}";
		 $catarr=getone($strsql);
		 if(empty($catarr)){
			 return false;
		  }else{
			 return $catarr;
			  }
		 }	 
	}
//获取会员组名称
 function  GetMemberGroupName($groupid){
	    $retname="";
	    if(!empty($groupid)){
		 $strsql="select * from `#yunyecms_membergroup` where `id`= {$groupid}";
		 $curmembergroup=getone($strsql);
		 if(empty($curmembergroup)){
			  $retname=false;
		  }else{
			 $retname=$curmembergroup["groupname"];
			  }
		 }
	    return $retname;
	}

 function  GetGroupStyle($groupid){
	    $groupname=GetMemberGroupName($groupid);
	    $retname="";
	    if(stripos($groupname,'普通')!==false){
		  $retname="<span class='label label-success'>普通会员</span>";	
		}elseif(stripos($groupname,'VIP')!==false){
		  $retname="<span class='label label-danger'>VIP会员</span>";	
		}elseif(stripos($groupname,'游客')!==false){
		  $retname="<span class='label label-info'>游客</span>";	
		}else{
		  $retname="<span class='label label-info'>游客</span>";	
		}
	    return $retname;
	}


//通过分类获取模型ID
 function  getmodelid($catid){
	    if(empty($catid)) {
			return false;
		}else{
		 $strsql="select modelid from `#yunyecms_category` where `id`= {$catid}";
		 $catarr=getone($strsql);
		 if(empty($catarr)){
			 return false;
		  }else{
			 return $catarr['modelid'];
			  }
		 }	 
	}


  function  gettable($modelid){
	    if(empty($modelid)) {
			return false;
		}else{
		 $strsql="select tablename from `#yunyecms_model` where `modelid`= {$modelid}";
		 $curmodel=getone($strsql);
		 if(empty($curmodel)){
			 return false;
		  }else{
			 return $curmodel["tablename"];
			  }
		 }
	}

  function  getmodelname($modelid){
	    if(empty($modelid)) {
			return false;
		}else{
		 $strsql="select modelname from `#yunyecms_model` where `modelid`= {$modelid}";
		 $curmodel=getone($strsql);
		 if(empty($curmodel)){
			 return false;
		  }else{
			 return $curmodel["modelname"];
			  }
		 }
	}

  function  returnmodeltype($modeltype){
	    $retstr="";
	    if(empty($modeltype)){
			return false;
		}else{
			switch($modeltype){
				case 1:
	            $retstr="lists";
				break;
				case 2:
	            $retstr="singlepage";
				break;
				case 3:
	            $retstr="customform";
				break;	
				default:
	            $retstr="lists";
			}
		}
	    return $retstr;
	}

  function  getmodeltype($modelid){
	    if(empty($modelid)) {
			return false;
		}else{
		 $strsql="select modeltype from `#yunyecms_model` where `modelid`= {$modelid}";
		 $curmodel=getone($strsql);
		 if(empty($curmodel)){
			 return false;
		  }else{
				$retinfo=returnmodeltype($curmodel["modeltype"]);
				return $retinfo;
			  }
		 }		   
	}

function getcatppid($catid,&$ppid) {
	  if($catid){
		  $strsql="select `id`,`pid` from `#yunyecms_category` where `id`= {$catid}";
		  $curarr=getone($strsql);
		  if(!empty($curarr)){
			    $pid=$curarr["pid"];
			    $ppid=$curarr["id"];
			    if($pid>0){
			         getcatppid($pid,$ppid);
				   }
			  }
		  }else{
			return 0;
			}
     }

function getppid($catid) {
	 if(empty($catid)) return false;
	 $ppid =0;
	 getcatppid($catid,$ppid);
	 return $ppid;
}


function getsubcatsel($catid,$level,$pcatid=0,$lang=0){
	$strspace="";
	 if($level){
		 for($i=0;$i<$level;$i++){
			$strspace=$strspace."&nbsp;&nbsp;&nbsp;&nbsp;";
			 }
		 $strspace.="|--";
		 }
	  if(isset($catid)){
		  if($lang){
			 $strsql="select `id`,`title` from `#yunyecms_category` where `pid`= {$catid} and lang={$lang}";
		  }else{
		  $strsql="select `id`,`title` from `#yunyecms_category` where `pid`= {$catid}";
		  }
		  $subarr=getlist($strsql);
		  if(!empty($subarr)){
			 foreach($subarr as $key=>$var){
				 $sid=$var["id"];
				  if($pcatid==$sid){
					  $retstr= '<option value="'.$sid.'" selected>'.$strspace.$var["title"].'</option>';
					  }else{
					  $retstr= '<option value="'.$sid.'">'.$strspace.$var["title"].'</option>';
						  }
				 echo $retstr;
				 getsubcatsel($sid,$level+1,$pcatid);
				}
			  }
		}
 }

function getparentid($catid) {
	  if($catid){
		  $strsql="select `id`,`pid` from `#yunyecms_category` where `id`= {$catid}";
		  $parentarr=getone($strsql);
		  if(!empty($parentarr)){
			return $parentarr["pid"];
			  }else{
			return 0;
				  }
		}else{
			return 0;
			}
}

function calclevel($catid,&$level) {
	  if($catid){
		  $strsql="select `id`,`pid` from `#yunyecms_category` where `id`= {$catid}";
		  $curarr=getone($strsql);
		  if(!empty($curarr)){
			   $pid=$curarr["pid"];
			    if($pid>0){
				    $level=$level+1;
			        calclevel($pid,$level);
				   }
			  }
		  }else{
			return 0;
			}
     }
function getlevel($catid) {
	 $level =1;
	 calclevel($catid,$level);
	 return $level;
 }

function getcatbyid($id,$key='title') {
	  $strsql="select $key from `#yunyecms_category` where `id`= {$id}";
	  $retres=getone($strsql);
	  if($retres){
		  return $retres[$key];
	  }	else{
		  return false;
	  }
 }
//获取实际的分类ID
  function getreal_catid($catid,$langid,$tablename='category',$db=array()) {
	  if(empty($db)) $db=core::load_model('common_model');
	  $syn=$db->getfield('syn',$catid,$tablename);
	  if(!empty($syn)&&!empty($langid)){
	     $realcat=$db->find("select  id from `#yunyecms_category` where lang={$langid} and `syn`={$syn} ");
	     if($catid!=$realcat['id']) $catid=$realcat['id'];
	  }
	  return $catid;
 }
//获取实际的信息ID
 function getreal_id($id,$langid,$tablename='category',$db=array()) {
	  if(empty($db)) $db=core::load_model('common_model');
	   $syn=$db->getfield('syn',$id,$tablename);
	   if(!empty($syn)&&!empty($langid)){
		 $realinfo=$db->find("select  id from `#yunyecms_{$tablename}` where lang={$langid} and `syn`={$syn} ");
		 if($id!=$realinfo['id']) $id=$realinfo['id'];
	  }
	  return $id;
 }
//获取网站配置信息
function getcfg(){
			  $strsql="select * from `#yunyecms_config` order by id desc limit 0,1";
			  $curconfig=getone($strsql);
			  if(!empty($curconfig)){
				  $curconfig['email']=unserialize($curconfig['email']);
				  $curconfig['sms']=unserialize($curconfig['sms']);
				  $curconfig['weixin']=unserialize($curconfig['weixin']);
				  $curconfig['alipay']=unserialize($curconfig['alipay']);
				  $curconfig['upload']=unserialize($curconfig['upload']);
				  $curconfig['content']=unserialize($curconfig['content']);
				  $curconfig['mobilecfg']=unserialize($curconfig['mobilecfg']);
				  return $curconfig;
			   }else{
				  return false;
			  }
		}
//获取seo配置信息
function getseocfg(){
			  $strsql="select url_route,url_model from `#yunyecms_config` order by id desc limit 0,1";
			  $curconfig=getone($strsql);
			  if(!empty($curconfig)){
				  return $curconfig;
			   }else{
				  return false;
			  }
		}
//获取默认语言ID
 function  getdefaultlang(){
	   $strsql="select * from `#yunyecms_lang`  where isdefault=1 order by id desc limit 0,1";
	   $deflang=getone($strsql);
	   if($deflang){
		  return $deflang;
	   }else{
		  return false;
	   }
 }
 function  getlangid(){
	   $strsql="select id from `#yunyecms_lang`  where isdefault=1 order by id desc limit 0,1";
	   $deflang=getone($strsql);
	   if($deflang){
		  return $deflang['id'];
	   }else{
		  return false;
	   }
 }
//获取语言版本列表
 function  getlang(){
	   $strsql="select id,title,title_en,isdefault,logo,landir from `#yunyecms_lang`  where status=1  order by ordernum asc";
	   $langlist=getlist($strsql);
	    if(URL_MODEL==5){
			 global $thispageurl,$htmlinfo;
			 foreach($langlist as $key=>$var){
				 	 if(!empty($htmlinfo)){
						 $filename =explode('/', $thispageurl);
						 $filename=end($filename);
						 $filenameurl=substr($thispageurl,0,strlen($thispageurl)-strlen($filename));
						 $realid=getreal_id($htmlinfo['id'],$var['id'],$htmlinfo['tablename']);
						 $thispageurl=$filenameurl.$realid.'.html';
			         }
				  if(!$var['isdefault']){
				    $langlist[$key]["url"]= ROOT.$var['landir'].$thispageurl; 
				   }else{
				    $langlist[$key]["url"]= $thispageurl; 
				  }
			   }
		  }elseif(URL_MODEL==0){
				 $params   =  $_GET;
			     foreach($params as $kp=>$vp){
					 if(empty($vp)) unset($params[$kp]);
				 }
				 foreach($langlist as $key=>$var){
				  if(ROUTE_M=='content'&&ROUTE_C=='index'&&ROUTE_A=='index'){
					$langlist[$key]["url"]=ROOT."index.php?lang=".$var['id'];
				   }else{
					 $params['lang']=$var['id'];
					 $langlist[$key]["url"]=ROOT.'index.php?'.http_build_query($params);
				  }
			   }
		  }elseif(URL_MODEL==1||URL_MODEL==2||URL_MODEL==3){
				$params   =  $_GET;
				if(URL_ROUTE){
					$urlroute=substr($_SERVER['PATH_INFO'],1);
					$urlroutearr=explode('/',$urlroute);
					if($urlroutearr[0])
					$strsql="select count(*) from `#yunyecms_lang` where `landir` ='{$urlroutearr[0]}'";
					$cntcheck=getcount($strsql);
				   }
			    foreach($langlist as $key=>$var){
				  if(ROUTE_M=='content'&&ROUTE_C=='index'&&ROUTE_A=='index'){
					  $langlist[$key]["url"]=ROOT."index.php?lang=".$var['landir'];
					  //$langlist[$key]["url"]=ROOT."index.php/{$var['landir']}";
				   }else{
					 $params['lang']=$var['id'];
					 if(URL_ROUTE){
						 if($cntcheck){
							 $urlroutearr[0]=$var['landir'];
							  $langlist[$key]["url"]=url('/'.implode('/',$urlroutearr));
						  }else{
							 $langlist[$key]["url"]=url('/'.$var['landir'].'/'.$urlroute);
						 }
						} else{
						 $langlist[$key]["url"]=ROOT.'index.php?'.http_build_query($params);
					  }

				  }
			   }
		 }
	   if(count($langlist)>1){
	     return $langlist;
	   }else{
	     return false;
	   }
 }
//获取语言版本列表
 function  getalllang($status=1){
	   $strsql="select id,title,title_en,isdefault,logo,landir,status,lang_icon from `#yunyecms_lang`   where landir<>'' and status={$status}  order by ordernum asc";
	   $lang=getlist($strsql);
	   return $lang;
 }
 function  getlangnum($status=1){
	   $strsql="select count(*) from `#yunyecms_lang`   where landir<>'' and status={$status} ";
	   $nums=getcount($strsql);
	   return $nums;
 }

//获取当前语言版
 function  getcurlang($lang=1,$db=array()){
	   if(is_numeric($lang)){
	   $retlang=getone("select * from `#yunyecms_lang`  where id='$lang'  limit 0,1");
	   }elseif(ctype_alnum($lang)){
	   $retlang=getone("select * from `#yunyecms_lang`  where landir='{$lang}'  limit 0,1");
	   }else{$retlang=false;}
	   return $retlang;
 }
//生成记录编号
 function  create_number($tablename,$lang){
		 $total=getcount("select count(*)  from `#yunyecms_{$tablename}`  where title<>'' and lang=$lang ");
		 $number=$total+1;
		 $checknum=getone("select  number  from `#yunyecms_{$tablename}` where number>$number and lang=$lang  order by number desc limit 0,1 ");
		 if($checknum){
			$number=$checknum["number"]+1;
		 }  
	 return $number;
 }

//模板加载函数
function tpl($template = ROUTE_A,$module='content',$curtpl=CTD){
	global $cfg,$lang;
	$ismobile = false;
	$landir=LAN;
	if(!empty($cfg['mobilecfg']["displaymode"])){
		if (is_mobile()) {
			$landir=LAN."_mobile";
			$ismobile = true;
		}
	 }
	 if(empty($module))$module='content';
				 $tpl_cache = CACHE_ROOT . 'templates/' . $curtpl . '/'.$landir. '/' . $module . '_' . $template . '.php';
				 $tpl_file = YUNYECMS_ROOT.'theme/'.$curtpl . '/'.$landir . '/' . $module . '_' . $template . '.html';
			     if(!file_exists($tpl_file)){
				 $tpl_cache = CACHE_ROOT . 'templates/default/' .$landir. '/'. $module . '_' . $template . '.php';
		         $tpl_file = YUNYECMS_ROOT.'theme/default/' .$landir. '/'. $module . '_' . $template . '.html';  
			    } 
	   if(file_exists($tpl_file)){
		  if(!file_exists($tpl_cache)||@filemtime($tpl_file) > @filemtime($tpl_cache)){
		        $c_template = core::load_class('template_cache');	
				$c_template->cache_template_app($template,$module,$curtpl);
		    }
	   }else{
		  messagebox("模板加载错误","nback","info","","模板文件{$tpl_file}不存在!");
	  }
	 if(CACHE_AUTO_UPDATE) {
		$c_template = core::load_class('template_cache');
		$c_template->cache_template_app($template,$module,$curtpl);
	 }
	return $tpl_cache;
}


//模板加载函数
function tpl_addons($template = ROUTE_A,$module = ROUTE_M,$isadmin=0,$curtpl = CTD){
	global $cfg;
	$ismobile = false;
	$landir=LAN;
	if(!empty($cfg['mobilecfg']["displaymode"])){
		if (is_mobile()) {
			$landir=LAN."_mobile";
			$ismobile = true;
		}
	 }
				 if($isadmin){
				   $tpl_file = YUNYECMS_ROOT.'addons/'.ROUTE_M . '/tpl/'. ROUTE_C.'_'. $template . '.html';
			       $tpl_cache = CACHE_ROOT . 'addons/' . ROUTE_M . '/' . ROUTE_C.'_'.$template . '.php';
				   }else{
				   $tpl_file = YUNYECMS_ROOT.'addons/'.ROUTE_M . '/tpl/'.$landir . '/'. ROUTE_C.'_'. $template . '.html';
			       $tpl_cache = CACHE_ROOT . 'addons/' . ROUTE_M . '/'.$landir. '/' . ROUTE_C.'_'.$template . '.php';
				  }
	   if(file_exists($tpl_file)){
		  if(!file_exists($tpl_cache)||@filemtime($tpl_file) > @filemtime($tpl_cache)){
		        $c_template = core::load_class('template_cache');	
				$c_template->cache_template_addons($template,$module,$isadmin,$curtpl);
		    }
	   }else{
		  messagebox("模板加载错误","nback","info","","模板文件{$tpl_file}不存在!");
	  }
	 if(CACHE_AUTO_UPDATE) {
		$c_template = core::load_class('template_cache');
		 $c_template->cache_template_addons($template,$module,$isadmin,$curtpl);
	 }
	return $tpl_cache;
}



/**
 * 写入缓存，默认为文件缓存，不加载缓存配置。
 * @param $cattpl 缓存名称
 * @param $rootcattpl 缓存数据
 * @param $modeltpl 数据路径（模块名称） caches/cache_$filepath/
 * @param $mode 1返回列表页模板，2返回详情页模板，3返回单页模板，4返回表单模板
 */
function gettpl($cattpl,$rootcattpl,$modeltpl,$contenttpl="",$mode=1){
	    $returntpl=$cattpl;
		if(empty($returntpl)){
			if(!empty($rootcattpl)){
		        $returntpl=$rootcattpl;
			   }else{
				if(!empty($modeltpl)){
		          $returntpl=$modeltpl;
			    }else{
					 switch($mode){
						 case 1:
						   $returntpl="lists";	
						   break;
						 case 2:
						   $returntpl="show";	
						   break;
						 case 3:
						   $returntpl="singlepage";	
						   break;
						 case 4:
						   $returntpl="form";	
						   break;
						 default :
						   $returntpl="lists";	
					 }
				}
		     }
		}
	 return  $returntpl;
}


//判断是否为移动端
function is_mobile()
{ 
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    {
        return true;
    } 
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
    { 
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    } 
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT']))
    {
        $clientkeywords = array ('nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
            ); 
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
        {
            return true;
        } 
    } 
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT']))
    { 
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
        {
            return true;
        } 
    } 
    return false;
} 

function module_exists($m = '') {
	if ($m=='admin') return true;
	$modules = getcache('modules', 'commons');
	$modules = array_keys($modules);
	return in_array($m, $modules);
}

/**
 * 加载模板标签缓存
 * @param string $name 缓存名
 * @param integer $times 缓存时间
 */
function tpl_cache($name,$times = 0) {
	$filepath = 'tpl_data';
	$info = getcacheinfo($name, $filepath);
	if (SYS_TIME - $info['filemtime'] >= $times) {
		return false;
	} else {
		return getcache($name,$filepath);
	}
}
/**
 * 写入缓存，默认为文件缓存，不加载缓存配置。
 * @param $name 缓存名称
 * @param $data 缓存数据
 * @param $filepath 数据路径（模块名称） caches/cache_$filepath/
 * @param $type 缓存类型[file,memcache,apc]
 * @param $config 配置名称
 * @param $timeout 过期时间
 */
function setcache($name, $data, $filepath='', $type='file', $config='', $timeout=0) {
	if(!preg_match("/^[a-zA-Z0-9_-]+$/", $name)) return false;
	if($filepath!="" && !preg_match("/^[a-zA-Z0-9_-]+$/", $filepath)) return false;
	core::load_class('cache_factory',0);
	if($config) {
		$cacheconfig = core::load_config('cache');
		$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
	} else {
		$cache = cache_factory::get_instance()->get_cache($type);
	}

	return $cache->set($name, $data, $timeout, '', $filepath);
}

/**
 * 读取缓存，默认为文件缓存，不加载缓存配置。
 * @param string $name 缓存名称
 * @param $filepath 数据路径（模块名称） caches/cache_$filepath/
 * @param string $config 配置名称
 */
function getcache($name, $filepath='', $type='file', $config='') {
	if(!preg_match("/^[a-zA-Z0-9_-]+$/", $name)) return false;
	if($filepath!="" && !preg_match("/^[a-zA-Z0-9_-]+$/", $filepath)) return false;
	 core::load_class('cache_factory',0);
	if($config) {
		$cacheconfig = core::load_config('cache');
		$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
	} else {
		$cache = cache_factory::get_instance()->get_cache($type);
	}
	return $cache->get($name, '', '', $filepath);
}

/**
 * 删除缓存，默认为文件缓存，不加载缓存配置。
 * @param $name 缓存名称
 * @param $filepath 数据路径（模块名称） caches/cache_$filepath/
 * @param $type 缓存类型[file,memcache,apc]
 * @param $config 配置名称
 */
function delcache($name, $filepath='', $type='file', $config='') {
	if(!preg_match("/^[a-zA-Z0-9_-]+$/", $name)) return false;
	if($filepath!="" && !preg_match("/^[a-zA-Z0-9_-]+$/", $filepath)) return false;
	core::load_class('cache_factory',0);
	if($config) {
		$cacheconfig = core::load_config('cache');
		$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
	} else {
		$cache = cache_factory::get_instance()->get_cache($type);
	}
	return $cache->delete($name, '', '', $filepath);
}

/**
 * 读取缓存，默认为文件缓存，不加载缓存配置。
 * @param string $name 缓存名称
 * @param $filepath 数据路径（模块名称） caches/cache_$filepath/
 * @param string $config 配置名称
 */
function getcacheinfo($name, $filepath='', $type='file', $config='') {
	if(!preg_match("/^[a-zA-Z0-9_-]+$/", $name)) return false;
	if($filepath!="" && !preg_match("/^[a-zA-Z0-9_-]+$/", $filepath)) return false;
	core::load_class('cache_factory',0);
	if($config) {
		$cacheconfig = core::load_config('cache');
		$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
	} else {
		$cache = cache_factory::get_instance()->get_cache($type);
	}
	return $cache->cacheinfo($name, '', '', $filepath);
}

//发送邮件
function send_mail($emailcfg,$to, $name, $subject = '', $body = '', $attachment = null){
	include_once YUNYECMS_CORE.'lib'.DIRECTORY_SEPARATOR.'PHPMailer'.DIRECTORY_SEPARATOR.'class.phpmailer.php'; 
	//从PHPMailer目录导class.phpmailer.php类文件
    $mail             = new PHPMailer(); //PHPMailer对象
    $mail->CharSet    = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();  // 设定使用SMTP服务
    $mail->SMTPDebug  = 0;                     // 关闭SMTP调试功能
	// 1 = errors and messages
                                               // 2 = messages only
    $mail->SMTPAuth   = true;                  // 启用 SMTP 验证功能
    $mail->SMTPSecure = 'ssl';                 // 使用安全协议
    $mail->Host       = $emailcfg['host'];  // SMTP 服务器
    $mail->Port       = $emailcfg['port'];  // SMTP服务器的端口号
    $mail->Username   = $emailcfg['user'];  // SMTP服务器用户名
    $mail->Password   = yunyecms_strdecode($emailcfg['pwd']);  // SMTP服务器密码
    $mail->SetFrom($emailcfg['fromemail'], $emailcfg['fromname']);
    $replyEmail       = !empty($emailcfg['replaymail'])?$emailcfg['replaymail']:"";
    $replyName        = !empty($emailcfg['replayname'])?$emailcfg['replayname']:"";
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject    = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($to, $name);
    if(is_array($attachment)){ // 添加附件
        foreach ($attachment as $file){
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
 }


  function curl_post($url,$post_data){    
      $curl = curl_init();    
      curl_setopt($curl, CURLOPT_URL, $url);    
      curl_setopt($curl, CURLOPT_HEADER, 0);    
      curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);    
      curl_setopt($curl, CURLOPT_POST, 1);    
      curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);    
      $retdata = curl_exec($curl);    
      curl_close($curl);    
      return $retdata;   
    }


function sock_post($url, $data='') {
  $url = parse_url($url);
  $url['scheme'] || $url['scheme'] = 'http';
  $url['host'] || $url['host'] = $_SERVER['HTTP_HOST'];
  $url['path'][0] != '/' && $url['path'] = '/'.$url['path'];
  $query = $data;
  if(is_array($data)) $query = http_build_query($data);
  $fp = @fsockopen($url['host'], $url['port'] ? $url['port'] : 80);
  if (!$fp) return "Failed to open socket to $url[host]";
  fputs($fp, sprintf("POST %s%s%s HTTP/1.0/n", $url['path'], $url['query'] ? "?" : "", $url['query']));
  fputs($fp, "Host: $url[host]/n");
  fputs($fp, "Content-type: application/x-www-form-urlencoded/n");
  fputs($fp, "Content-length: " . strlen($query) . "/n");
  fputs($fp, "Connection: close/n/n");
  fputs($fp, "$query/n");
  $line = fgets($fp,1024);
  if (@!eregi("^HTTP/1/.. 200", $line))  return;
  $results = "";
  $inheader = 1;
  while(!feof($fp)) {
    $line = fgets($fp,1024);
    if ($inheader && ($line == "/n" || $line == "/r/n")) {
      $inheader = 0;
    }elseif (!$inheader) {
      $results .= $line;
    }
  }
  fclose($fp);
  return $results;
}
//获取首页模块显示类型
function  get_dismode(){
	$modearray = array(
		"1"=>array('id'=>'1','name'=>'幻灯片','index'=>'slider'),
		//"2"=>array('id'=>'2','name'=>'关于我们','index'=>'about'),
		//"3"=>array('id'=>'3','name'=>'产品列表','index'=>'product'),
		//"4"=>array('id'=>'4','name'=>'新闻列表','index'=>'news'),
		//"5"=>array('id'=>'5','name'=>'案例列表','index'=>'cases'),
		"8"=>array('id'=>'8','name'=>'图文列表','index'=>'lists'),
		"6"=>array('id'=>'6','name'=>'链接','index'=>'links'),
		"10"=>array('id'=>'10','name'=>'单页面','index'=>'single'),
		"11"=>array('id'=>'11','name'=>'表单','index'=>'form'),
		//"7"=>array('id'=>'7','name'=>'招聘列表','index'=>'job'),
		//"9"=>array('id'=>'9','name'=>'图片列表','index'=>'pic'),
		//"12"=>array('id'=>'12','name'=>'广告','index'=>'ad'),
		//"13"=>array('id'=>'13','name'=>'tab切换','index'=>'tab'),
		//"14"=>array('id'=>'14','name'=>'在线客服','index'=>'online'),
		"99"=>array('id'=>'99','name'=>'其他','index'=>'other')
    );
	return $modearray;
 }
//获取首页模块名称
 function  get_modename($index){
	 $modearr=get_dismode();
	 $retstr="";
	 foreach($modearr as $var){
		 if($var['index']==$index){
			 $retstr= $var['name'];
		 }
	 }
	return $retstr;
 }

//获取首页模块样式
function  get_homestyle(){
	$modearray = array(
		"1"=>array('id'=>'1','name'=>'样式一','index'=>'style1'),
		"2"=>array('id'=>'2','name'=>'样式二','index'=>'style2'),
		"3"=>array('id'=>'3','name'=>'样式三','index'=>'style3'),
		"4"=>array('id'=>'4','name'=>'样式四','index'=>'style4'),
		"5"=>array('id'=>'5','name'=>'样式五','index'=>'style5'),
    );
	return $modearray;
 }

//获取插件类型
function  get_addon_cat(){
	$addonarray = array(
		"1"=>array('id'=>'1','name'=>'内容','index'=>'content'),
		"2"=>array('id'=>'2','name'=>'会员','index'=>'member'),
		"3"=>array('id'=>'3','name'=>'移动端','index'=>'mobile'),
		"4"=>array('id'=>'4','name'=>'商城','index'=>'mall'),
		"5"=>array('id'=>'5','name'=>'客服','index'=>'service'),
		"6"=>array('id'=>'6','name'=>'文件','index'=>'file'),
		"7"=>array('id'=>'7','name'=>'营销','index'=>'sell'),
		"8"=>array('id'=>'8','name'=>'其他','index'=>'other')
    );
	return $addonarray;
 }


	
?>