<?php
use WHMCS\Database\Capsule;
function _pdoQuery($sql){
	$pdo = Capsule::connection()->getPdo();
	if(strpos(trim(strtolower($sql)),'select') === 0){
		$re = $pdo->query($sql);
		return $re->fetchAll(PDO::FETCH_ASSOC);
	}else{
		return $pdo->exec($sql);
	}
}
function _pdoInsert($table,$array){
	$pdo = Capsule::connection()->getPdo();
	foreach ($array as $key => $val){
		$keys[] ="`". $key."`" ;
		$values[] = "'".((get_magic_quotes_gpc()) ? trim($val) : addslashes(trim($val)))."'";
	}
	$sql="INSERT INTO `$table` (".implode(',', $keys).") VALUES (".implode(',', $values).")";
	return $pdo->exec($sql);
	//return $pdo->lastInsertId();

}
function _pdoBatchInsert($table,$arrayKey,$array2){
	$pdo = Capsule::connection()->getPdo();
	foreach ($arrayKey as $val){
		$keys[] ="`". $val."`" ;
	}
	$values="";$ke=0;
	foreach ($array2 as $val){
		$value=array();		
		foreach($val as $k=>$v){				
			$value[] = "'".((get_magic_quotes_gpc()) ? trim($v) : addslashes(trim($v)))."'";
		}
			
		$values.="(".implode(',', $value).")";
		if(($ke+1)<count($array2))$values.=",";
		$ke++;
	}
	$sql="INSERT INTO `$table` (".implode(',', $keys).") VALUES $values";
	return $pdo->exec($sql);
	//return $pdo->lastInsertId();
}  	
function _pdoUpdate($table,$array,$id){
	$pdo = Capsule::connection()->getPdo();
	foreach ($array as $key => $val){
		$valstr[] = "`". $key . "` = '" . ((get_magic_quotes_gpc()) ? $val : addslashes($val)) . "'";
	}
	$sql="UPDATE `$table` SET ".implode(' , ', $valstr)." WHERE ".$id;
	return $pdo->exec($sql);
}
function _pdoBatchUpdate($table, $arrayKey = [], $array2 = [], $fields="id", $where = ''){  
	$pdo = Capsule::connection()->getPdo();
	$when="";$in_id="";$ke=0;
	$where=(!empty($where))?" AND ".$where:"";
	foreach ($arrayKey as $val){
		$keys[] ="`". $val."`" ;
		$when.="`$val`=CASE `$fields`";
		foreach ($array2 as $k => $v){	
			$when.=" WHEN '".$v[$fields]."' THEN '" . ((get_magic_quotes_gpc()) ? $v[$val] : addslashes($v[$val])) . "'";	
			
			if($ke==0) $in_id.="'".$v[$fields]."',";	
		}
		$when.=" END";
		if(($ke+1)<count($arrayKey))$when.=",";
		$ke++;
	}			
	$sql="UPDATE `$table` SET ".$when." WHERE ".$fields." IN (".trim($in_id,",").") $where";
	return $pdo->exec($sql);
}
function _pdoSelect($table,$columnName="*",$where="",$limit=""){
	$pdo = Capsule::connection()->getPdo();
	$where=(!empty($where))?'WHERE '.$where:'';
	if($limit=="all") $limit2='';
	else $limit2=(!empty($limit))?'LIMIT '.$limit:'';
	$columnName=!empty($columnName)?$columnName:"*";
	$sql="SELECT $columnName FROM `$table` $where $limit2";

	$re=$pdo->query($sql);
	if(empty($limit)){
		return $re->fetch(PDO::FETCH_ASSOC);//一条数据
	}
	return $re->fetchAll(PDO::FETCH_ASSOC);

}
function billingcycle(){
	return ['monthly','quarterly','semiannually','annually','biennially','triennially'];	
}

//获取的优惠码
function agentCode($level){
	if(empty($level)) return [];
	//$addons_clients = _pdoSelect("idcsmart_agent_addons_clients","`userid`,`apikey`,`disabled`,`level`","`userid`='{$userid}'");
	if($level){
		$agentlevel = _pdoSelect("idcsmart_agent_addons_agentlevel","prom_id","`id`='{$level}'");
		if($agentlevel['prom_id']){
			$tblpromotions = _pdoSelect("tblpromotions","code,appliesto","`id`='{$agentlevel['prom_id']}'");
			$data['code']=$tblpromotions['code'];
			$data['appliesto']=$tblpromotions['appliesto'];
			$data['products']=array_unique(array_filter(explode(",",$tblpromotions['appliesto'])));
		}else{
			$data['code']="";
			$data['appliesto']="";
		}
	}
	return $data;
}

/**
 * 数据类型判断  get,post,put,delete
 * @params  string $method 请求类型
 * @return boole
 */
function _requsetMethod($method="get"){		
	return (strtolower($_SERVER["REQUEST_METHOD"])==strtolower($method))?true:false;
}
/**
 * 获取数据
 * @params  string $type 类型
 * @params  string $key 要获取的参数名
 * @return array
 */
function _httpRequest($type="GET",$key=''){
	$type=strtolower($type);
	if($type=="get")
		$requert=$_GET;
	else if($type=="post")
		$requert=!empty($_POST)?$_POST:_getInput();
	else 
		$requert=_getInput();	
	$requert=_filterEscape($requert);
	return (!empty($key))?$requert[$key]:$requert;
}
/**
 * 获取请求头
 * @params  string $name 字符串
 * @return string
 */
function _httpHeader($name = ""){
    $header = [];
    if (function_exists('getallheaders')) {
        $header = getallheaders();
    } else {
        $server = $_SERVER;
        foreach ($server as $key => $val) {
            if (0 === strpos($key, 'HTTP_')) {
                $key          = str_replace('_', '-', strtolower(substr($key, 5)));
                $header[$key] = $val;
            }
        }
        if (isset($server['CONTENT_TYPE'])) {
            $header['content-type'] = $server['CONTENT_TYPE'];
        }
        if (isset($server['CONTENT_LENGTH'])) {
            $header['content-length'] = $server['CONTENT_LENGTH'];
        }
    }
    $header = array_change_key_case($header);
    if ($name==="") return $header;
    $name = str_replace('_', '-', strtolower($name));
    return isset($header[$name]) ? $header[$name] : null;
}
/**
 * 输出json
 * @params  
 */
function _json($data=[]){
	header("Content-Type: application/json; charset=UTF-8"); 
	header("HTTP/1.0 200 Not Found");
	echo json_encode($data,JSON_UNESCAPED_UNICODE);
	exit;
}
/**
 * 获取原始数据
 */
function _getInput(){
	$inputStr=file_get_contents('php://input');
	if(strpos($_SERVER['CONTENT_TYPE'],"json")!==false){
		$requestData=json_decode($inputStr,true);
	}else if(strpos($inputStr,"=")!==false){
		parse_str($inputStr,$requestData);
	}
	return $requestData;
}
/**
 * 安全过滤类-字符串过滤 过滤特殊有危害字符
 * @params string $value 需要过滤的变量
 * @return string|array
 */
function _filterEscape($value){
	if(is_array($value)){
		foreach ($value as $k => $v){
			$value[$k] = _filterEscape($v);
		}
	}else{
		$value = str_replace(array("\0","%00","\r"), '', $value); 
		$value = preg_replace(array('/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]/','/&(?!(#[0-9]+|[a-z]+);)/is'), array('', '&amp;'), $value);
		$value = str_replace(array("%3C",'<'), '&lt;', $value);
		$value = str_replace(array("%3E",'>'), '&gt;', $value);
		$value = str_replace(array('"',"'","\t"), array('&quot;','&#39;','    '), $value);
	}
	return $value;
}
/**
 * 停止执行_exit
 * 
 * @params  
 */
function _exit($data=""){
	header("Content-Type: text/html; charset=UTF-8"); 
	header("HTTP/1.0 404 Not Found");
	echo $data;
	exit;
}
/**
 * 随机字符串
 * @params  string $length 字符串长度,
 * @params  string $type 字符串类型 lower小写字母，upper大写字母，number数字，special特殊字符
 * @return string
 */
function _strRandom($length=12,$type="all"){
    $lower="abcdefghijklmnopqrstuvwxyz";
    $upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $number="0123456789";
    $special="!@#%^*-~+=,;:?|";
    $str="";
    if($type=="all"){
        $type = "lower_upper_number_special";
    }
    if(strpos($type,"_")!==false){
        $type_arr=explode("_",trim($type,"_"));
        foreach($type_arr as $k=>$v){
           $str_result[$k]=str_shuffle($$v);
        }
    }else{
        $str_result=str_shuffle($$type);
    }
    $str_count=count($str_result);
    if($str_count>1){
        $str_int_count=intval($length/$str_count);
        $str_y_count=$length%$str_count;
        if($str_int_count==0){
            for($i=0;$i<=$length-1;$i++){
               $str_rand=array_rand($str_result);
               $str.=mb_substr($str_result[$str_rand],0,1);
            }
        }else{
            if($str_y_count>0){
               foreach($str_result as $v){
                   $str.=mb_substr($v,0,$str_int_count);
               }
               $arr1=array_rand($str_result);
               $str_y=mb_substr($str_result[$arr1],0,$str_y_count);
               $str=$str.$str_y;
               $str=str_shuffle($str);
            }else{
                foreach($str_result as $v){
                    $str.=mb_substr($v,0,$str_int_count);
                }
                $str=str_shuffle($str);
            }
        }
    }else{
        $str=mb_substr($str_result,0,$length);
    }
    return $str;
} 
/**
 * 分页
 * @params  string $url 网址,
 * @params  string $pagecount 每页显示条数,
 * @params  string $count 总数据条数
 * @params  string $page 当前页数
 * @params  string $num 显示条数
 * @return  string
 */
function _page($params){
	$params['page']=empty($params['page'])?1:$params['page'];
	$totalpage = ceil($params['count'] / $params['pagecount']);//总页数
	$prev=$params['page']==1?0:($params['page']-1);//上一页
	$next=$params['page']>=$totalpage?0:($params['page']+1);//下一页
	$url=$params['url'].'&page=';
	//if($totalpage>1)$page.='<a href="'.$url.'1">首页</a>';	
	if($prev>0)$page.='<li class="previous"><span class="page-selector"><a href="'.$url.$prev.'">« 上一页</a></span></li>';
	else $page.='<li class="previous disabled"><span class="page-selector">« 上一页</span></li>';
	$plus=ceil($params['num']/2);
	if($params['num']-$plus+$params['page']>$totalpage)
		$plus=$params['num']-$totalpage+$params['page'];
	$begin=$params['page']-$plus+1;
	$begin=($begin>=1)?$begin:1;
	for($p=$begin;$p<$begin+$params['num'];$p++){
		if($p<=$totalpage){
			if($p==$params['page']){
				$page.='<li class="hidden-xs"><span href="#" class="page-selector active"><strong>'.$p.'</strong></span></li>';
			}else{
				$page.='<li class="hidden-xs"><a href="'.$url.$p.'"><span href="#" class="page-selector">'.$p.'</span></a></li>';
			}
		}
	}
	if($next>0) $page.='<li class="next"><span class="page-selector"><a href="'.$url.$next.'">下一页 »</a></span></li>';
	else $page.='<li class="next disabled"><span class="page-selector">下一页 »</span></li>';	
	//if($totalpage>1)$page.='<a href="'.$url.$totalpage.'">最后一页</a>';	
	return $page;
}

/**
* @title CURL
* @desc 公共curl
* @author xiong
* @version v1
* @param string url - url地址 require
* @param array data [] 传递的参数
* @param string timeout 30 超时时间
* @param string request POST 请求类型
* @param array header [] 头部参数
* @return int http_code - http状态码
* @return string error - 错误信息
* @return string content - 内容
*/
function curl($url, $data = [], $timeout = 30, $request = 'POST', $header = [])
{
    $curl = curl_init();
    $request = strtoupper($request);

    if($request == 'GET'){
        $s = '';
        if(!empty($data)){
            foreach($data as $k=>$v){
                if(empty($v)){
                    $data[$k] = '';
                }
            }
            $s = http_build_query($data);
        }
        if(strpos($url, '?') !== false){
            if($s){
                $s = '&'.$s;
            }
        }else{
            if($s){
                $s = '?'.$s;
            }
        }
        curl_setopt($curl, CURLOPT_URL, $url.$s);
    }else{
        curl_setopt($curl, CURLOPT_URL, $url);
    }
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_REFERER, request() ->host());
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    if($request == 'GET'){
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPGET, 1);
    }
    if($request == 'POST'){
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        if(is_array($data)){
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        }else{
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
    }
    if($request == 'PUT' || $request == 'DELETE'){
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $request);
        if(is_array($data)){
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        }else{
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
    }
    if(!empty($header)){
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    }
    $content = curl_exec($curl);
    $error = curl_error($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
	curl_close($curl);
	return ['http_code'=>$http_code, 'error'=>$error , 'content' => $content];
}