<?php
/*
*跑街令API
*/
class LibPjlApi
{
	protected $config = null;

	function __construct()
	{
		$this->config = mvc::$cfg['PJLAPI'];
	}
	
	/**
	  * @method 发送短信
	  * @http  POST
	  * @param  $url_path           string [必填] action/method
	  * @param  $get_arr            array  [可选] ['name'=>'soul',....]
	  * @param  $post_arr           array  [可选] ['name'=>'soul',....]
	  * @param  $onlyRes            bool   [可选] 直接返回原始结果？
	  * @author soul
	  * @copyright 2017/4/13
	  * @return array
	  */
	public function Get($url_path, $get_arr=[], $post_arr=[], $onlyRes = false, $run = 0)
	{
		try {
			$run++;
			$url = $this->config['base_url'].$url_path;
			$get_arr['devcode'] =  $this->config['devcode'];
			$get_arr['from'] =  $this->config['from'];
			$get_arr['ip'] = empty($this->config['ip'])? LibFc::GetClientIp(): $get_arr['ip'];
			$get_arr['token'] =  !empty($_SESSION['_pjltoken'])? $_SESSION['_pjltoken']: $this->config['token'];
			$url = $url.'?'.http_build_query($get_arr);

			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_TIMEOUT, 5000);
			curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
			if(!empty($post_arr))
			{
				curl_setopt($ch, CURLOPT_POST, true);
				curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_arr));
			}
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$ssl = substr($url, 0, 8) == "https://" ? true : false;
			if($ssl)
			{
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);// 信任任何证书
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);// 检查证书中是否设置域名
			}
			$html = curl_exec($ch);
			curl_close($ch);
			//处理错误提示
			$return = json_decode($html, true);
			if(is_array($return))
			{
				if($return['encry'] == 1){
					$LibEncry = new LibEncry();
					$return['data'] = $LibEncry->decode($return['data']);
					$tdata = json_decode($return['data'], true);
					if(is_array($tdata)){
						$return['data'] = $tdata;
					}
				}
				if($return['code'] === 'apitoken') unset($_SESSION['_pjltoken']);
				if($onlyRes) return $return;
				return LibFc::ReturnData($return['status'], $return['data'], $return['code']);
			}else{
				if($run < 5) return $this->Get($url_path, $get_arr, $post_arr, $onlyRes, $run);
				LibLog::write("PJLAPI请求出错:".$url.'=>'.json_encode($post_arr, JSON_UNESCAPED_UNICODE).'=>'.$html);
				return LibFc::ReturnData(false, $url_path.'接口请求异常'.$html);
			}
		}catch (Exception $e) {
			if($run < 5) return $this->Get($url_path, $get_arr, $post_arr, $onlyRes, $run);
			LibLog::write("PJLAPI请求出错:".$url.'=>'.json_encode($post_arr, JSON_UNESCAPED_UNICODE).'=>'.$e->getMessage());
			return LibFc::ReturnData(false, $url_path."接口请求出错");
		}
	}
}