<?php
/**
 *      [XCECP] (C) COLNET Inc.
 *      This is NOT a freeware, use is subject to license terms
 */
if(!defined("IN_QKWEB")){exit("Access Denied");}
/**
 * 递归方式的对变量中的特殊字符进行转义
 *
 * @access  public
 * @param   mix     $value
 *
 * @return  mix
 */
function addslashes_deep($value)
{
    if (empty($value))
    {
        return $value;
    }
    else
    {
        return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
    }
}

/**
  +----------------------------------------------------------
 * 字符串命名风格转换
 * type
 * =0 将Java风格转换为C的风格
 * =1 将C风格转换为Java的风格
  +----------------------------------------------------------
 * @access protected
  +----------------------------------------------------------
 * @param string $name 字符串
 * @param integer $type 转换类型
  +----------------------------------------------------------
 * @return string
  +----------------------------------------------------------
 */
function parse_name($name, $type=0) {
    if ($type) {
		$c=preg_replace_callback("|_([a-zA-Z])|",create_function('$matches','return strtolower($matches[1]);'),$name);
		return ucfirst($c);
    } else {
        $name = preg_replace("/[A-Z]/", "_\\0", $name);
        return strtolower(trim($name, "_"));
    }
}

function display($tmp=null){
	global $smarty;
	if(!$tmp){if(MODEL_NAME){$tmp = MODEL_NAME;}}
	if(!$tmp){$tmp = "index";}
	if(substr($tmp,-5,5)!=".html"){$tmp = $tmp.".html";}
	$pageInfo =$smarty->getTemplateVars("pageInfo");
	if(!checkCert()){$pageInfo['title'] = $pageInfo['title']." - Powered by XCECP";}
	$smarty->assign("pageInfo",$pageInfo);
	$smarty->display(strtolower($tmp));
}

function assign($name,$value){
	if(isset($GLOBALS['smarty'])){
		$GLOBALS['smarty']->assign($name,$value);
		return true;
	}else{
		return false;
	}
}
function checkCert(){
	$authorize = false;$cert = ROOT_PATH."data/cert.crt";if(file_exists($cert)){$certInfo = @openssl_x509_parse(file_get_contents($cert));if($certInfo){if($certInfo && $certInfo['issuer'] && $certInfo['issuer']['CN']=='Colorful Network Certification Authority' && $certInfo['issuer']['O']=='Colorful Network Ltd.' && $certInfo['extensions'] && $certInfo['extensions']['authorityKeyIdentifier']=='keyid:4C:64:9D:F8:18:52:83:BE:E0:02:D6:6E:CF:2E:B2:C0:53:0C:59:20'."\n"){$certDomain = $certInfo['subject']['CN'];}else{;}};unset($certInfo);if($certDomain){$domain = $_SERVER['HTTP_HOST'];if($certDomain==$domain || preg_match("/\.$certDomain$/",$domain)){$authorize = true;}else{};unset($certDomain);unset($domain);}}unset($cert);return $authorize;
}
function getgpc($k, $type='GP') {
	$type = strtoupper($type);
	switch($type) {
		case 'G': $var = &$_GET; break;
		case 'P': $var = &$_POST; break;
		case 'C': $var = &$_COOKIE; break;
		default:
			if(isset($_GET[$k])) {
				$var = &$_GET;
			} else {
				$var = &$_POST;
			}
			break;
	}

	return isset($var[$k]) ? $var[$k] : NULL;
}

function getTopParent($parentId){
	global $db;
	$res = $db->getOne("select parentId from qk_category where id='".$parentId."'");
	if($res){
		return getTopParent($res);
	}else{
		return $parentId;
	}
}

function getParentCatId($parentId){
	global $db;
	$res = $db->getOne("select parentId from qk_category where id='".$parentId."'");
	if($res){
		return $res;
	}else{
		return false;
	}
}

function getCatName($catId){
	global $db;
	$res = $db->getOne("select name from qk_category where id='".$catId."'");
	if($res){
		return $res;
	}
	return false;
}


function getCats($catId){
	global $db;
	$cats = $catId;
	$sql = "select id from qk_category where parentId='".$catId."'";
	$res = $db->getAll($sql);
		if($res){
			foreach($res as $item){
				$cats .= ",".getCats($item['id']);
			}
		}
	return $cats;
}

function getCatSelect($parentId=0){
	$tmp = getCatOption($parentId);
	return "<select></select>";
}


function getArticleCategory($catId=0){
	global $db;
	$tmp = array();
	$catInfo = $db->getRow("select name,parentId,sortId,id,posttime from qk_article_cat where id='".$catId."' order by sortId asc");
	if(!$catInfo['name'] && $catId!=0){return;}
	if($catId!==0){
			$grade=getArticleCatGrade($catId);
	$tmp[] = array("id"=>$catId,"name"=>$catInfo['name'],"parentId"=>$catInfo['parentId'],"grade"=>$grade,"sortId"=>$catInfo['sortId'],"id"=>$catInfo['id'],"posttime"=>$catInfo['posttime']);
	}
	$sql = "select * from qk_article_cat where parentId=".$catId." and iStatus=1 order by sortId asc";
	$res = $db->getAll($sql);
	if($res){
		foreach($res as $item){
			$tmp = array_merge($tmp,getArticleCategory($item['id']));
		}
	}
	return $tmp;
}

function getArticleCatGrade($catId){
	global $db;
	$grade = 0;
	$cats = $catId;
	$sql = "select parentId from qk_article_cat where id='".$catId."'";
	$res = $db->getRow($sql);
		if($res && $res['parentId']>0){
			$grade++;
			$grade += getCatGrade($res['parentId']);
		}
	return $grade;
}




function getBrand($catId=0){
	global $db;
	$tmp = $db->getAll("select * from qk_brand order by catId asc,id asc");
	return $tmp;
}

/**
 * 生成缩略图
 * @param string     源图绝对完整地址{带文件名及后缀名}
 * @param string     目标图绝对完整地址{带文件名及后缀名}
 * @param int        缩略图宽{0:此时目标高度不能为0，目标宽度为源图宽*(目标高度/源图高)}
 * @param int        缩略图高{0:此时目标宽度不能为0，目标高度为源图高*(目标宽度/源图宽)}
 * @param int        是否裁切{宽,高必须非0}
 * @param int/float  缩放{0:不缩放, 0<this<1:缩放到相应比例(此时宽高限制和裁切均失效)}
 * @return boolean
 */
function img2thumb($src_img, $dst_img, $width = 75, $height = 75, $cut = 0, $proportion = 0)
{
    if(!is_file($src_img))
    {
        return false;
    }
	if(is_file($dst_img)){return false;}
    $ot = fileext($dst_img);
    $otfunc = 'image' . ($ot == 'jpg' ? 'jpeg' : $ot);
    $srcinfo = getimagesize($src_img);
    $src_w = $srcinfo[0];
    $src_h = $srcinfo[1];
    $type  = strtolower(substr(image_type_to_extension($srcinfo[2]), 1));
    $createfun = 'imagecreatefrom' . ($type == 'jpg' ? 'jpeg' : $type);

    $dst_h = $height;
    $dst_w = $width;
    $x = $y = 0;

    /**
     * 缩略图不超过源图尺寸（前提是宽或高只有一个）
     */
    if(($width> $src_w && $height> $src_h) || ($height> $src_h && $width == 0) || ($width> $src_w && $height == 0))
    {
        $proportion = 1;
    }
/*	
    if($width> $src_w)
    {
        $dst_w = $width = $src_w;
    }
    if($height> $src_h)
    {
        $dst_h = $height = $src_h;
    }
*/
    if(!$width && !$height && !$proportion)
    {
        return false;
    }
    if(!$proportion)
    {
        if($cut == 0)
        {
            if($dst_w && $dst_h)
            {
                if($dst_w/$src_w> $dst_h/$src_h)
                {
                    $dst_w = $src_w * ($dst_h / $src_h);
                    $x = 0 - ($dst_w - $width) / 2;
                }
                else
                {
                    $dst_h = $src_h * ($dst_w / $src_w);
                    $y = 0 - ($dst_h - $height) / 2;
                }
            }
            else if($dst_w xor $dst_h)
            {
                if($dst_w && !$dst_h)  //有宽无高
                {
                    $propor = $dst_w / $src_w;
                    $height = $dst_h  = $src_h * $propor;
                }
                else if(!$dst_w && $dst_h)  //有高无宽
                {
                    $propor = $dst_h / $src_h;
                    $width  = $dst_w = $src_w * $propor;
                }
            }
        }
        else
        {
            if(!$dst_h)  //裁剪时无高
            {
                $height = $dst_h = $dst_w;
            }
            if(!$dst_w)  //裁剪时无宽
            {
                $width = $dst_w = $dst_h;
            }
            $propor = min(max($dst_w / $src_w, $dst_h / $src_h), 1);
            $dst_w = (int)round($src_w * $propor);
            $dst_h = (int)round($src_h * $propor);
            $x = ($width - $dst_w) / 2;
            $y = ($height - $dst_h) / 2;
        }
    }
    else
    {
        $proportion = min($proportion, 1);
        $height = $dst_h = $src_h * $proportion;
        $width  = $dst_w = $src_w * $proportion;
    }

    $src = $createfun($src_img);
    $dst = imagecreatetruecolor($width ? $width : $dst_w, $height ? $height : $dst_h);
    $white = imagecolorallocate($dst, 255, 255, 255);
    imagefill($dst, 0, 0, $white);

    if(function_exists('imagecopyresampled'))
    {
        imagecopyresampled($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
    }
    else
    {
        imagecopyresized($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
    }
    $otfunc($dst, $dst_img);
    imagedestroy($dst);
    imagedestroy($src);
    return true;
}

function fileext($file)
{
    return pathinfo($file, PATHINFO_EXTENSION);
}

function load_class($name,$cat=null){
	if(!$cat){$cat="model";}
	if(!@include_once(ROOT_PATH."includes/".$cat."/".ucfirst($name).ucfirst($cat).".class.php")){
		Msg::show('模块不存在');
	}
}

function SendTemplateMail($template,$vals,$mailto,$subject)
{
	global $smarty;
	$config = getConfig("smtp");
	if(!$config || !$config['server'] || !$config['port'] || !$config['user'] || !$config['email']){
		exit('{"success":false,"message":"请管理员配置SMTP邮件发送参数"}');
	}
	$smtpserver = $config['server'];
	$smtpserverport = $config['port'];
	$smtpuser = $config['user'];
	$smtppass = $config['pass'];
	$smtpusermail = $config['email'];
	if(eregi("(\.html)$",$template)){
		$template_dir = $smarty->getTemplateDir();
		$email = new MailTemplate("file=".$template_dir[0]."mailtemplates".DIRECTORY_SEPARATOR."$template");
	}else{
		$email = new MailTemplate($template);
	}
	$email->var2value_ary($vals);
	$email->SmtpServer = $smtpserver;
	$email->SmtpUser = $smtpuser;
	$email->SmtpPW = $smtppass;
	$email->SmtpSender = $smtpusermail;
	$email->fromName = $GLOBALS['siteConf']['siteName'];
	$ret = $email->sendmail($mailto,$subject,$smtpusermail);
	if(!$ret){
		saveLog("邮件发送失败：".$mailto." ".$subject." 原因：".$email->msg);
		if(getgpc("inajax")=='1' && $email->msg)exit('{"success":false,"message":"'.$email->msg.'"}');
	}
	return $ret;
}

function checkCertId($certId){
	//17位加权因子
	$wi=array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);
	$id17=substr($certId,0,17);//获取身份证的前17位
	$idend=substr($certId,17); //获取身份证的效验位（第18位）
	$sum=0;             //加权求和id[i]*wi[i]求和
	for($i=0;$i<strlen($id17);$i++)
	{
	 $sum+=$id17[$i]*$wi[$i];
	}            
	//效验码
	$xiaoyanma=array("1","0","X","9","8","7","6","5","4","3","2");              
	//用加权求和的值与11进行求余运算，并与效验码对应位数进行比较              
	if($idend==$xiaoyanma[$sum%11]) 
	{
	 return true; //成功返回true
	}
	else
	{
	 return false; //失败返回false
	}
}

function saveLog($content="",$catId=0,$isError=0,$userId='',$remark='',$name=''){
	if(!$userId){ $userId = $_SESSION['adminId']; }
	if(!$userId){ $userId = $_SESSION['userId']; }
	if(!$userId){ $userId = '0'; } 
	global $dbname;	
	if(!$GLOBALS['db']->num_rows($GLOBALS['db']->query("show tables from ".$dbname." like 'qk_log'"))){Msg::show("日志数据不存在，请升级.<br/>".$content);return false;
	}
	$param="";
	if(preg_match("/^select /",$content)){
		$param = ",url='".$_SERVER['REQUEST_URI']."',referer='".$_SERVER['HTTP_REFERER']."'";
	}
	$sql = "insert into qk_log set userId='".$userId."'";
	$sql .= ",catId=".$catId.",ip='".getIp()."',remark='".addslashes($remark)."',name='$name',isError=".$isError;
	$sql .= ",content='".addslashes($content)."',posttime=".time().$param;
	$GLOBALS['db']->query($sql);
	return true;
}

function load_api($name){
	include_once(ROOT_PATH."includes/api/".ucfirst($name)."Api.class.php");
}

//**获得客户真实ip地址
if ( ! function_exists('getIp'))
{
	function getIp()
	{
		static $ip = NULL;
		if ($ip !== NULL){return $ip;}
		if (isset($_SERVER))
		{
			if (isset($_SERVER['HTTP_X_FORWARD_FOR']))
			{
				$arr = explode(',', $_SERVER['HTTP_X_FORWARD_FOR']);
				/* 取X-Forwarded-For中第x个非unknown的有效IP字符? */
				foreach ($arr as $xip)
				{
					$xip = trim($xip); if ($xip != 'unknown'){$ip = $xip;break;}
				}
			}else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
			{
				$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
				/* 取X-Forwarded-For中第x个非unknown的有效IP字符? */
				foreach ($arr as $xip)
				{
					$xip = trim($xip); if ($xip != 'unknown'){$ip = $xip;break;}
				}
			}else if (isset($_SERVER['HTTP_X_FORWARD_FOR']))
			{
				$arr = explode(',', $_SERVER['HTTP_X_FORWARD_FOR']);
				/* 取X-Forwarded-For中第x个非unknown的有效IP字符? */
				foreach ($arr as $xip)
				{
					$xip = trim($xip); if ($xip != 'unknown'){$ip = $xip;break;}
				}
			}
			else if(isset($_SERVER['HTTP_CLIENT_IP']))
			{
				$ip = $_SERVER['HTTP_CLIENT_IP'];
			}
			else
			{
				if (isset($_SERVER['REMOTE_ADDR'])){$ip = $_SERVER['REMOTE_ADDR'];}else{$ip = '0.0.0.0';}
			}
		}
		else
		{
			if (getenv('HTTP_X_FORWARDED_FOR'))
			{
				$ip = getenv('HTTP_X_FORWARDED_FOR');
			}
			else if (getenv('HTTP_CLIENT_IP'))
			{
				$ip = getenv('HTTP_CLIENT_IP');
			}
			else
			{
				$ip = getenv('REMOTE_ADDR');
			}
		}
		preg_match("/[\d\.]{7,15}/", $ip, $onlineip);
		$ip = ! empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
		return $ip;
	}
}

function getConfig($param){
	global $db;
	$wheres="";if(defined('SITE_ID')){$wheres = " and (siteId='".SITE_ID."' or siteId=0)";}
	if(is_numeric($param)){
		$config = $db->getOne("select config from qk_config where iStatus=1 and id='$id' $wheres");
	}else{
		$config = $db->getOne("select config from qk_config where iStatus=1 and name='$param' $wheres");
	}
	if(!$config){return false;}
	$config = unserialize($config);
	foreach($config as $item){
		$config[$item['name']] = $item['value'];
	}
	return $config;
}

function getVariable($param){
	global $db;
	if(is_numeric($param)){
		$value = $db->getOne("select `value` from qk_variable where id='$id'");
	}else{
		$value = $db->getOne("select `value` from qk_variable where name='$param'");
	}
	if(!$value){return false;}
	return $value;
}
function decimalTwo($a){
	$b=$a*1000;
	settype($b,'integer');
	if($a*1000>$b){$b=$b+1;}
	$c = $b.'';
	$d = strlen($c);
		if($c{$d-1} >= 1){
			$b=$b/10;settype($b,'integer');
			$e = $b + 1;return ($e / 100);
		}else{
			$b=$b/10;settype($b,'integer');
			$e = $b;return ($e / 100);
		}
}
function randCoupon(){
	$code = substr(strtoupper(md5(time().rand())),0,16);
	global $db;
	$sql = "select id from qk_user_coupon where number='$code'";
	if($db->getOne($sql)){
		randCoupon();
	}else{
		return $code;
	}
}
function utf8_strlen($string = null) {preg_match_all("/./us", $string, $match);return count($match[0]); }
function urlAfter($url='',$key='',$val=''){
	if($url==''){return false;}
	if($key==''){return false;}
	if($val==''){return false;}
	$urlArr = parse_url($url);
	if(isset($urlArr['query'])){
		$has = false;
		$query=$urlArr['query'];
		$queryArr=explode('&',$query);
		if(strpos($query,'=')){
			$param=array();
			if($queryArr && is_array($queryArr) &&count($queryArr)>0){
				foreach($queryArr as $item){
					$tmp = explode('=',$item);
					if($tmp && count($tmp)==2){
						if($tmp[0]==$key){$tmp[1]=$val;$has = true;}
						$param[$tmp[0]]=$tmp[1];
					}
				}
			}
			if(!$has){
				$param[$key]=$val;
			}
			$url=$urlArr['path'].'?';
			$i=0;
			foreach($param as $key=>$val){
				$url.=$key.'='.urlencode($val);
				if($i<count($param)-1){$url.='&';}
				$i++;
			}
			return $url;
		}else{
			$url = $urlArr['path'].'?'.$key.'='.urlencode($val);
		}
	}else{
		$url =  $urlArr['path'].'?'.$key.'='.urlencode($val);
	}
	return $url;
}

?>