<?php
/**
 * 全局启动函数
 */
function doxcx_start(){
	$_SERVER['WEB_NAME'] = Conf::$webname?:'DOXCX';
	$_SERVER['WEI_URL'] = '';
	$_SERVER['IS_OEM'] = true;
	$_SERVER['OEM_ID'] = '0';
	//记录访问日志
	//Log::error(Request::ip().'：'.$_SERVER['HTTP_USER_AGENT'].'-'.Request::url());	
}

//判断是否微信访问
function openurl(){
	$isflag = 1;
	$agent = $_SERVER['HTTP_USER_AGENT'];
	if(!strpos($agent,"MicroMessenger")) {
		$isflag = 0;
	}
	return $isflag;
}


//获取企业微信的code
function QYWX_getCode($appId,$redirectUrl,$state=null,$scope='snsapi_base',$agentId=null){
	$url = 'https://open.weixin.qq.com/connect/oauth2/authorize';
	$params = [];
	if($scope == 'snsapi_userinfo' || $scope == 'snsapi_privateinfo'){
		$params['agentid'] = $agentId;
	}
	if(!empty($state)){
		$params['state'] = $state;
	}
	$params['redirect_uri'] = $redirectUrl;
	$params['appid'] = $appId;
	$requestUrl = $url.'?'.http_build_query($params).'#wechat_redirect';
	return $requestUrl;
}

//获取企业微信用户信息
function QYWX_getUserInfo($code,$access_token){
	$url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo';
	$params = [];
	$params['code'] = $code;
	$params['access_token'] = $access_token;
	$requestUrl = $url.'?'.http_build_query($params);
	$res = json_decode(curlGets($requestUrl),true);
	return $res;
}



//获取access_token
function WX_getAccessToken($wid){
    $data = json_decode(file_get_contents(DOXCX_FRAME_PATH."jssdk/access_token_".$wid.".json"));
    if ($data->expire_time < time()) {
        $appkey = new Model('vshop_weixin_pay');
        $appkey->field('id,AppId,AppSecret')->find(array('wid'=>$wid));
	        //获取AppID、AppSecret
	        $appid = $appkey->AppId;
	        $secret = $appkey->AppSecret;
	        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
	        $res = json_decode(curlGets($url));
	        $access_token = $res->access_token;
	        if ($access_token) {
            $data->expire_time = time() + 3600;
            $data->access_token = $access_token;
            $fp = fopen(DOXCX_FRAME_PATH."jssdk/access_token_".$wid.".json", "w");
            fwrite($fp, json_encode($data));
            fclose($fp);
        }
    } else {
        $access_token = $data->access_token;
    }
    return $access_token;
}

//获取企业微信access_token
function QYWX_getAccessToken($wid){
	$data = json_decode(file_get_contents(DOXCX_FRAME_PATH."jssdk/qy_access_token_".$wid.".json"));
	if ($data->expire_time < time() || $data == null) {
		$appkey = new Model('vshop_supercard_set');
		$appkey->field('id,qiye_id,qiye_secret')->find(array('wid'=>$wid));
		//获取AppID、AppSecret
		$corpid= $appkey->qiye_id;
		$secret = $appkey->qiye_secret;
		$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" . $corpid . "&corpsecret=" . $secret;
		$res = json_decode(curlGets($url));
		$access_token = $res->access_token;
		if ($access_token) {
			$data->expire_time = time() + 7000;
			$data->access_token = $access_token;
			$fp = fopen(DOXCX_FRAME_PATH."jssdk/qy_access_token_".$wid.".json", "w");
			fwrite($fp, json_encode($data));
			fclose($fp);
		}
	} else {
		$access_token = $data->access_token;
	}
	return $access_token;
}

//获取阿拉丁access_token
function ALD_getAccessToken($code,$url){
	$userAgency=new Model('user_agency');
	$userAgency->find(array('isadmin'=>1));
	$clientId=$userAgency->client_id;
	$clientSecret=$userAgency->client_secret;

	$urls = "http://openapi.aldwx.com/Main/action/Oauth/Oauth/access_token";
	//初始化
      $curl = curl_init();
      //设置抓取的url
     curl_setopt($curl, CURLOPT_URL, $urls);   
     //设置获取的信息以文件流的形式返回，而不是直接输出。
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     //设置post方式提交
     curl_setopt($curl, CURLOPT_POST, 1);
     //设置post数据
     $post_data = array(
         "grant_type" => "authorization_code",
         "client_id" => $clientId,
		 "client_secret"=>$clientSecret,
		 "code"=>$code,
		 "redirect_uri"=>$url
         );
     curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
     //执行命令
     $data = curl_exec($curl);
     //关闭URL请求
     curl_close($curl);
     $arr = json_decode($data,true);
     $accessToken=$arr['access_token'];
	 $refreshToken=$arr['refresh_token'];
	 if($accessToken){
		$wid = Session::get('wid');//当前登录的用户id
		$m = new Model('ald_set');
		$m->find(array('wid'=>$wid));
		$m->wid = $wid;
		$m->ald_access_token = $accessToken;
		$m->ald_refresh_toke = $refreshToken;
		$m->ald_create_time = date('Y-m-d H:i:s', time());
		$m->save();
	 }
	 return $accessToken;
}


function curl_get_https($url)
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.1 Safari/537.11');
	$res = curl_exec($ch);
	$rescode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	curl_close($ch);
	return $res;
}

function curl_post_https($url,$post_data)
{
	//初始化
	$ch = curl_init();

	curl_setopt($ch,CURLOPT_URL,$url);

	curl_setopt($ch,CURLOPT_HEADER,0);

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书

	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不验证证书

	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1 );

	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);

	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

	$res = curl_exec($ch);
	return $res;
}


//获取图片信息
function downloadImageFromWeXin($url){
	
	set_time_limit(0);//0表示没有限制
	ini_set("max_execution_time", "0");
	ini_set("memory_limit", "1024M");
	
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_NOBODY, 0);//只取body头
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$package = curl_exec($ch);
	$httpinfo = curl_getinfo($ch);
	curl_close($ch);
    $imageAll = array_merge(array('body' => $package), array('header' => $httpinfo));
	return $imageAll;
}


//会员级别翻译
function translate_level($level_id=null,$justtext = false){

	$u = new Model('user_type');
	$types = $u->order('typeid')->list_all();
	foreach($types as $v){
		$l_arr[$v->typeid]=$v->typename;
	}
	if($level_id===null){
		return $justtext ? '' : $l_arr;
	}else{
		return $l_arr[$level_id];
	}	
}

/*
 *   @desc代理级别翻译 
 *   @param $level 
 *  */
function translate_agency_level($level_id=null,$justtext = false){

	$u = new Model('agency_type');
	$types = $u->order('id')->list_all();
	foreach($types as $v){
		$l_arr[$v->id]=$v->typename;
	}
	if($level_id===null){
		return $justtext ? '' : $l_arr;
	}else{
		return $l_arr[$level_id];
	}
}

//员工级别
function translate_employee_level($level_id=null,$justtext = false){
	$l_arr = array('1'=>'网络销售','2'=>'财务主管','3'=>'财务人员','4'=>'客服主管','5'=>'客服人员','6'=>'业务主管','7'=>'业务人员','8'=>'招商主管','9'=>'招商人员');
	if($level_id===null){
		return $justtext ? '' : $l_arr;
	}else{
		return $l_arr[$level_id];
	}
}


function curlGet($url, $method = 'get', $data = ''){
    $ch = curl_init();
    $header = "Accept-Charset: utf-8";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $temp = curl_exec($ch);
    return $temp;
}

function curlGets($url) {
    $ch = curl_init();
    $header = "Accept-Charset: utf-8";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $temp = curl_exec($ch);
    return $temp;
}
/**
 * Jeffrey
 * 数据查询
 */
function db_query ($sql="",$params=[]) {
  $db=DB::get_db(false);
  return $db->query($sql,$params);
}

/**
 * 获取payload形式的参数
 * @return mixed
 */
function getPayloadParams ($assoc=1) {
  $postStr = file_get_contents("php://input");
  $data = json_decode($postStr,$assoc);//获取数据
  return $data;
}

/**
 * 输出响应数据
 * @param $data
 */
function sendResponse ($data,$exit=false) {
    if(version_compare(PHP_VERSION,'5.5.0','>=')){
        echo json_encode($data,JSON_PARTIAL_OUTPUT_ON_ERROR);
    }else{
        echo json_encode($data);
    }

    if ($exit){
        exit();
    }
}

function arr_get($arr, $key, $default = null)
{
  if (key_exists($key, $arr)) {
    return $arr[$key];
  }
  return $default;
}

function array_to_cdata_xml($params)
{
  if (!is_array($params) || count($params) <= 0) {
    return false;
  }
  $xml = "<xml>";
  foreach ($params as $key => $val) {
    if (is_numeric($val)) {
      $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
    } else {
      $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
    }
  }
  $xml .= "</xml>";
  return $xml;
}

function array_to_string($params)
{
  $string = '';
  if (!empty($params)) {
    $array = [];
    foreach ($params as $key => $value) {
      $array[] = $key . '=' . $value;
    }
    $string = implode("&", $array);
  }
  return $string;
}

function make_sign($params, $key)
{
  ksort($params);
  $string = array_to_string($params);  //参数进行拼接key=value&k=v
  //签名步骤二：在string后加入KEY
  $string = $string . "&key=" . $key;
  //签名步骤三：MD5加密
  $string = md5($string);
  //签名步骤四：所有字符转为大写
  $result = strtoupper($string);
  return $result;
}

function postXmlCurl($url, $xml, $useCert = false, $second = 5)
{
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_TIMEOUT, $second);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  curl_setopt($ch, CURLOPT_HEADER, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  if ($useCert == true) {
    curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
    curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
  }
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
  $data = curl_exec($ch);
  if ($data) {
    curl_close($ch);
    return $data;
  } else {
    $error = curl_errno($ch);
    curl_close($ch);
    return false;
  }
}

function xml_to_array($xml)
{
  $res = simplexml_load_string($xml, 'SimpleXmlElement', LIBXML_NOCDATA);
  return json_decode(json_encode($res), true);
}
function confirm_sign ($data,$key,$sign_key='sign') {
  $sign=arr_get($data, $sign_key,false);
  if (!$sign){
    return false;
  }
  $data2=$data;
  unset($data2['sign']);
  $sign2=make_sign($data2, $key);
  return $sign==$sign2;
}

function diy_log ($data) {
   file_put_contents(DOXCX_FRAME_PATH.'/log/info/diy.log', date('H:i:s',time()).': '.json_encode($data,JSON_UNESCAPED_UNICODE)."\n",FILE_APPEND);
}

function diy_vd ($some) {
  echo "<pre>";
  var_dump($some);
  echo "</pre>";;
}
function array_to_obj ($arr,$obj,$except=[]) {
  foreach ($arr as $k=>$v){
    if (!in_array($k, $except)){
    $obj->$k=$v;
    }
  }
  return $obj;
}
function getFileList($dir){
$file_arr = array();
if(is_dir($dir)){
     //打开
     if($dh = @opendir($dir)){
         //读取
		while(($file = readdir($dh)) !== false){
			if($file != '.' && $file != '..'){
				$file_arr[] = $file;
            }
         }
                //关闭
         closedir($dh);
      }
}
return $file_arr;
}

/**
 * 获取插件文件
 * @param string $file_name
 * @return array
 */
function getAddonsFileList($file_name=''){
    $file_list=[];
    if(!$file_name)return $file_list;

    $addons_dir   = DOXCX_FRAME_PATH. 'Addons';
    $dirs = scandir($addons_dir);
    foreach ($dirs as $dir) {
        $path=$addons_dir.'/'.$dir;
        if($dir!='.'&&$dir!='..'){
            if(is_file($path."/{$file_name}.php")){
                $file_list[]=$path."/{$file_name}.php";
            }
        }
    }
    return $file_list;
}
require_once "func.php";
require_once "mysqli_php7.php";
$dir = DOXCX_FRAME_PATH.'fun/func';
$fileList=getFileList($dir);
foreach($fileList as $value){
	require_once $dir.'/'.$value;
}


?>