<?php
function Purl($urlkey){//常用链接
   if($urlkey=='go_back') return '-1';
   if(strpos($urlkey,'=')) return rewrite::request("{$urlkey}");
   $urlkey = explode('_',$urlkey);
   $url = $urlkey[1]=='' ? rewrite::request("?mod={$urlkey[0]}") : rewrite::request("?mod={$urlkey[0]}&act=$urlkey[1]");
   if($urlkey[0]=='tools'&&$urlkey[1]=='swfupload'){
	  $url .=  config::get('rewrite') ? rewrite::request("&ImgPath={$urlkey[2]}")."?cms=true" : "" ;
   }
   return $url;
}

function json($arr){
  $json = new Services_JSON();
  return $json->encode($arr);
}
function rescheck($type,$time=''){
   $check[0] = '排队中';
   $check[1] = '分红中';
   $check[2] = '已出局';
   if($time==''){
     return $check[$type];
   }else{
	 if($type=='1') return formattime($time,"Y-m-d");
	 return $check[$type]; 
   }
}
function language($message){//网站语言
   return $message;	
}
function errorpage(){//错误转向
   include template('errorpage','admin');
}
function formattime($time='',$format="Y-m-d H:i"){//时间戳转换时间
  if($time!=''){
   return date($format,$time);	
  }else{
   return '-';  
  }
}
function getval($val,$floor='0',$money='0'){
   if(strstr($val,"|")){
	 $val = explode('|',$val);
	 $val = $val[$floor];
   }
	 $val = formatnum($val*$money);
   return $val;
}

function formatnum($number,$length=2,$zero=''){
   $number = $number=='' ? 0 : $number;
   $array = explode(".",$number);
   $array[1] = substr($array[1],0,$length);
   if($zero==''){
	 $number = $array[0].".".str_pad($array[1],$length,"0",STR_PAD_RIGHT);
   }else{
	 $number = $array[0].".".$array[1];
   }
   if($length==0) return $array[0];
   return $number;
}

function formatn($number,$length=2,$zero=''){
   $number = $number=='' ? 0 : $number;
   $array = explode(".",$number);
   $array[1] = substr($array[1],0,$length);
   if($zero==''){
	 $number = $array[0].".".str_pad($array[1],$length,"0",STR_PAD_RIGHT);
   }else{
	 $number = $array[0].".".$array[1];
   }
   if($length==0) return $array[0];
   return $number;
}

function fnum($number,$length=2,$zero=''){
   $number = $number=='' ? 0 : $number;
   $array = explode(".",$number);
   $array[1] = substr($array[1],0,$length);
   if($zero==''){
	 $number = $array[0].".".str_pad($array[1],$length,"0",STR_PAD_RIGHT);
   }else{
	 $number = $array[0].".".$array[1];
   }
   if($length==0) return $array[0];
   return $number;
}

function untime($time){	
  return strtotime($time);
}
function geturl(){//获取当前页面地址
   if (isset($_SERVER['HTTP_X_REWRITE_URL'])){ 
     $request = $_SERVER['HTTP_X_REWRITE_URL'];
   }elseif(isset($_SERVER['REQUEST_URI'])){
     $request = $_SERVER['REQUEST_URI'];
   }elseif (isset($_SERVER['ORIG_PATH_INFO'])){ 
     $request = $_SERVER['ORIG_PATH_INFO'];
     if (!empty($_SERVER['QUERY_STRING'])){
       $request .= '?' . $_SERVER['QUERY_STRING'];
     }
   }else{
     $request = null;
   }
   return $request;
}
function geturlval($how){
   $request = geturl();
   $posnum = strpos($request,'?');
   if($posnum){
	  $request = substr($request,$posnum+1);
	  $request = explode("&",$request);
	  foreach($request as $val){
		if(strpos($val,$how.'=')!==false){
		   $value = str_replace($how.'=',"",$val);	
		}
	  }
   }
   return $value;
}
function reurl($urlkey){
   $url = Purl($urlkey)=='-1' ? $_SERVER["HTTP_REFERER"] : Purl($urlkey);
   $url = explode("?",$url);
   $request = explode("&",$url[1]);
   foreach($request as $val){
      $value .= "&back_".$val;
   }
   return $value;
}
function seturl($url){
   $url = explode("?",$url);
   $request = explode("&",$url[1]);
   unset($request[0],$request[1],$request[2]);
   foreach($request as $val){
	  if(strpos($val,'back_')!==false){
        $get = explode("=",$val);
	    $get[0] = str_replace('back_','',$get[0]);
	    $value[$get[0]] = $get[1];
	  }
   }
   return $value;
}
function getip() {
		if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
			$ip = getenv("HTTP_CLIENT_IP");
		} else
			if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
				$ip = getenv("HTTP_X_FORWARDED_FOR");
			} else
				if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
					$ip = getenv("REMOTE_ADDR");
				} else
					if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
						$ip = $_SERVER['REMOTE_ADDR'];
					} else {
						$ip = "unknown";
					}
		return ($ip);
}
function purviews(){//权限数组
   return array (  
	  'admin_main'=>array('系统信息',1,1),		 
	  'admin_config'=>array('管理部署',1,1),
	  'admin_user'=>array('用户管理',1,1),
	  'admin_news'=>array('新闻管理',1,1),
	  'admin_about'=>array('单页管理',1,1),
	  'admin_ads'=>array('广告管理',1,1),
	  'admin_company'=>array('商家管理',1,1),
	  'admin_refund'=>array('业务管理',1,1),
	  'admin_shop'=>array('商城管理',1,1), 	  
	  
	  'member_main'=>array('用户中心',1,1),
	  'member_record'=>array('推广中心',1,1),
	  'member_upywy'=>array('升级业务员',1,1),
	  'member_openywy'=>array('开通业务员',1,1),
	  
	  'member_addywy'=>array('申请业务员',1,1),

	  
	  'member_money'=>array('资金明细',1,1),
	  'member_payment'=>array('现金充值',1,1),
	  'member_myatm'=>array('现金提现',1,1),
	  
	  'member_shopcart'=>array('购物清单',1,1),
	  'member_order'=>array('我的订单',1,1),
	  
	  'member_addstore'=>array('商户下单',1,1),
	  'member_stores'=>array('商户账单',1,1), 
	  
	  'member_addjoin'=>array('申请商户',1,1),
	  'member_joins'=>array('我的商户',1,1),
	  'member_qjoins'=>array('区域商户',1,1), 

	  
	  'member_addagent'=>array('申请代理',1,1),
	  'member_agents'=>array('我的代理',1,1),
	  
	  'member_password'=>array('修改密码',1,1),
	  'member_auth'=>array('用户认证',1,1),
	  'member_profile'=>array('个人资料',1,1),
	  
	  'member_addbank'=>array('添加银行',1,1),

	  'shop_buy'=>array('购买商品',1,1),	  
	  'shop_shopcart'=>array('加入购物',1,1),	
   );  
}

function admin_menu_top(){
   return array (  
	  'main'=>'后台首页',		 
	  'config'=>'部署',
	  'user'=>'用户',
	  'news'=>'新闻', 
	  'about'=>'单页',
	  'ads'=>'广告',
	  'company'=>'商户',
	  'refund'=>'业务',
	  'shop'=>'商城', 
   );  
}
function admin_menu_left($top){
   $menu['main'] = array(  
	  'system'=>'系统信息',
	  'template'=>'模板管理',
	  'link'=>'友情链接',
	  'cache'=>'更新缓存',
   );
   $menu['config'] = array(  
	  'basic'=>'网站配置',
	  'bili'=>'常用比例',
	  'seo'=>'SEO优化',
	  'email'=>'邮件设置',
	  'pay'=>'支付配置',
	  'sms'=>'短信设置',
   );
   $menu['user'] = array(  
	  'list'=>'所有用户',
	  'password'=>'密码重置',
	  'add'=>'添加用户',
	  'clear'=>'清除用户',
	  'edit'=>'编辑用户-no',
   );
   
   $menu['ads'] = array(  
	  'list'=>'广告列表',
	  'add'=>'添加广告',
	  'edit'=>'修改广告-no',
	  'focus'=>'焦点图片',
	  'addfocus'=>'添加焦点',
	  'editfocus'=>'修改焦点-no',
   );
   
   
   $menu['about'] = array(  
	  'list'=>'单页列表',
	  'add'=>'添加单页',
	  'edit'=>'编辑单页-no',
   );
   
   $menu['news'] = array(  
	  'list'=>'新闻列表',
	  'add'=>'发布新闻',
	  'type'=>'新闻分类',
	  'edit'=>'编辑新闻-no',
   );
   
   $menu['company'] = array(  
	  'list'=>'商家列表',
	  'type'=>'商家分类',
	  'edit'=>'编辑商家-no',
   );
   
  
   $menu['refund'] = array(  
	  'store'=>'消费记录',				 
	  'atmlog'=>'提现记录',
	  'reslog'=>'返利记录',
	  'payorder'=>'充值记录',
	  'res'=>'返现统计',
	  'settle'=>'每日结算',
   );
      
   $menu['shop'] = array(  
	  'list'=>'商品列表',
	  'add'=>'添加商品',
	  'type'=>'商品分类',
	  'order'=>'订单管理',
	  'edit'=>'编辑商品-no',
   );   
   return $menu[$top];
}

function userpic($userpic){
	return $userpic=='' ? config::get('siteurl').'images/noavatar_middle.gif' : $userpic;
}


function isChinese($str){
    return preg_match("/[\x80-\xff]./", $str) ? 1 : 0;      
}

function submit(){//判断是否提交信息
   $post = implode('',$_POST);
   if($post!=''){
     if($_SESSION['stopoutenable']!=$_POST[stopoutenable]) location($_SERVER["HTTP_REFERER"],1);
	 unset($_POST['stopoutenable'],$_POST['submit'],$_SESSION['stopoutenable'],$_POST['button']);
   }
   return $post=='' ? false : true; 
}
function location($url,$or=0){
   $url = $or ? $url : Purl($url); 
   @header("Location: ".$url);
   exit;
}
function error($message=''){
	$errorurl = "<br><br>Go <a href=\"".config::get('siteurl')."\">home</a> <a href=\"javascript:history.back(-1)\">Back</a>！ ";
    return config::get("error") ? exit('<span style=\'font-family: "Times New Roman", Times, serif;\'>'.$message.$errorurl.'</span>') : errorpage();	
}
function checkemail($email){ //邮箱验证
   $exp = "^[a-z'0-9]+([._-][a-z'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";
   return eregi($exp,$email);
}
function checkstr($val){//中文验证
   if(preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$val)){ 
      return true;
   }else{
	  return false;
   } 
}
function sintrim($val){//替换所有空字符
   $val = trim($val);
   $val = str_replace(" ","",$val);
   return $val;
}

function paycheck($i,$o,$id=''){
   $check[0] = '未支付<span class="pay">(<a href="'.Purl("?mod=member&act=payment&get=pay&orderid=".$o).'">取消</a>)</span>';
   $check[1] = '<font color="#FF3300">支付成功</font>';
   $check[2] = '<font color="#999999">交易关闭</font><span class="pay">(<a href="'.Purl("?mod=member&act=payment&get=pay&orderid=".$o).'">取消</a>)</span>';
   if($id!=''){
	   $check[0] = '未支付<span class="pay">(<a href="'.Purl("?mod=admin&act=refund&get=payorder&id=".$id).'">取消</a>)</span>';
	   $check[2] = '<font color="#999999">交易关闭</font><span class="pay">(<a href="'.Purl("?mod=admin&act=refund&get=payorder&id=".$id).'">取消</a>)</span>';
   }
   return $check[$i];
}

function atmcheck($i){
   $check[0] = '待支付';
   $check[1] = '<font color="#FF3300">支付成功</font>';
   return $check[$i];
}
function usercheck($i){
   $check[0] = '<font color="#FF3300">待审核</font>';
   $check[1] = '已审核';
   return $check[$i];
}

function reslog($i){
   $check[1] = '天天返利分红';
   $check[2] = '区县代理分成';
   $check[3] = '下线消费提成';
   $check[4] = '推荐代理分成';
   $check[5] = '推荐商户分成';
   $check[6] = '市级代理分成';
   $check[7] = '省级代理分成';
   $check[8] = '推荐业务员分成';
   return $check[$i];
}

function Sanitize($value){
   //$value = @iconv('utf-8', 'gb2312', $value);
   return $value;
}

function Sitize($value){
   $value = @iconv('utf-8', 'gb2312', $value);
   return $value;
}

function randomkeys($length){
  $pattern='abcdefghijklmnopqrstuvwxyz';
  for($i=0;$i<$length;$i++){
     $key .= $pattern{mt_rand(0,25)};    //生成php随机数
  }
  return $key;
}

function isCact(){
  $Cact[] = 'cfb1bf5535f1e1004d5677e6e7e4cafb';
  $Host = md5($_SERVER['HTTP_HOST']);
  return in_array($Host,$Cact);
}


//字符截取函数
function msubstr($string,$start=0,$length){
	$strlen=strlen($string);
	if($strlen<=$length)
	{
		return $string;
	}
	$string = str_replace(array('&nbsp;','&amp;','&quot;','&lt;','&gt;','&#039;'), array(' ','&','"','<','>',"'"), $string);
	$strcut = '';
	$n = $tn = $noc = 0;
	while($n < $strlen) {

			$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);
	$strcut = str_replace(array('&','"','<','>',"'"), array('&amp;','&quot;','&lt;','&gt;','&#039;'), $strcut);
	return $strcut;
}
function dirpath($path){
	if($path=='') return false;
	$extarr = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
    if ($handle = opendir($path)) {
	    $i = 0;
	    while(false !== ($filename = readdir($handle))) {
	 	    if ($filename{0} == '.') continue;
		    $file = $path .'/'.$filename;
		    if (is_dir($file)){			
			    $list[$i]['is_dir'] = true; //是否文件夹
				$has_file = dirpath($file);
			    $list[$i]['has_file'] = is_array($has_file); //文件夹是否包含文件
			    $list[$i]['filesize'] = 0; //文件大小
			    $list[$i]['is_photo'] = false; //是否图片
			    $list[$i]['filetype'] = ''; //文件类别，用扩展名判断
				
			}else{
			    $list[$i]['is_dir'] = false;
			    $list[$i]['has_file'] = false;
			    $list[$i]['filesize'] = filesize($file);
			    $list[$i]['dir_path'] = '';
			    $file_ext = strtolower(array_pop(explode('.', trim($file))));
			    $list[$i]['is_photo'] = in_array($file_ext, $extarr);
			    $list[$i]['filetype'] = $file_ext;
		    }
		    $list[$i]['filename'] = $filename; //文件名，包含扩展名
		    $list[$i]['datetime'] = date('Y-m-d H:i:s', filemtime($file)); //文件最后修改时间
		    $i++;		
	    }
	    closedir($handle);
    }
	return $list;
}
function cmp_func($a, $b) {
    $order = empty($_GET['order']) ? 'name' : strtolower($_GET['order']);
	if ($a['is_dir'] && !$b['is_dir']) {
		return -1;
	} else if (!$a['is_dir'] && $b['is_dir']) {
		return 1;
	} else {
		if ($order == 'size') {
			if ($a['filesize'] > $b['filesize']) {
				return 1;
			} else if ($a['filesize'] < $b['filesize']) {
				return -1;
			} else {
				return 0;
			}
		} else if ($order == 'type') {
			return strcmp($a['filetype'], $b['filetype']);
		} else {
			return strcmp($a['filename'], $b['filename']);
		}
	}
}

function sendmail($sendto,$subject,$body,$username=''){
  require(PATH.'library/sendmail/class.phpmailer.php');
  $mail = new PHPMailer();
  if(!config::get('mailsend')){
    $mail->IsSMTP();
    $mail->Host = config::get('mailserver');
    $mail->SMTPAuth = config::get('mailauth');
    $mail->Username = config::get('mailusername');
    $mail->Password = config::get('mailpassword');
    $mail->From = config::get('mailfrom');
    $mail->FromName =  config::get('sitename');
  }else{
    $mail->AddReplyTo(config::get('mailfrom'),config::get('sitename'));
    $mail->SetFrom(config::get('mailfrom'),config::get('sitename'));  
  }  
  $mail->CharSet = "utf-8";
  $mail->Encoding = "base64"; 
  $mail->AddAddress($sendto,$username);
  $mail->IsHTML(true);
  $mail->Subject = $subject;
  $htmlfile = PATH."./template/admin/email.htm";
  $fp = @fopen($htmlfile, 'r');	
  $html = @fread($fp, filesize($htmlfile));
  fclose($fp);
  $html = str_replace('{subject}',$subject,$html);
  $html = str_replace('{sitedomain}',config::get('sitedomain'),$html);
  $html = str_replace('{sitename}',config::get('sitename'),$html);
  $html = str_replace('{body}',$body,$html);
  $mail->Body = $html;
  $mail->AltBody ="text/html"; 
  return $mail->Send();
}
function sendsms($message,$mobiles){
  $message = Sanitize($message);
  $message = urlencode($message);
  $mobiles = urlencode($mobiles);
  $uname = config::get("smsuname");
  $upwd = config::get("smspwd");
  $url = "http://sdkhttp.eucp.b2m.cn/sdkproxy/sendsms.action";
  $url .= "?cdkey=3SDK-EMY-0130-MGQRM&password=645895&phone={$mobiles}&message={$message}";
  $fp = fopen($url,"r");
  $ret = fgetss($fp,255);
  fclose($fp);
  return $ret;
}
function is_mobile($str){ 
  $pattern = "/^(13|15|18)\d{9}$/"; 
  if(preg_match($pattern,$str)){ 
     return true; 
  }else{ 
     return false; 
  } 
} 
function pic($val,$num='1'){
  if($num=='') $num='1';
  if(!$val||!$num) return "images/nopic.jpg";
  $num = $num-1;
  preg_match_all("/src=\"(.*?)\"/",$val,$pic);//
  $pics = $pic[1][0];
  return $pics=='' ? "images/nopic.jpg" : $pics;
}
function noHtml($val){
  $val=strip_tags($val);
  $val=str_replace("&nbsp;","",$val);
  $val=str_replace("　","",$val);
  return $val;
}

function setgl($value){
  return '<font color="#FF3300">'.$value.'</font>';	
}
?>