<?php
	class CTbaidu_translate {

		const CURL_TIMEOUT = 10;
		const URL = 'http://api.fanyi.baidu.com/api/trans/vip/translate';


        //翻译入口
		public static function translate($app_id, $sec_key, $query, $from, $to)
		{
			$args = array(
				'q' => $query,
				'appid' => $app_id,
				'salt' => rand(10000,99999),
				'from' => $from,
				'to' => $to,

			);
			$args['sign'] = (new self())->buildSign($query, $app_id, $args['salt'], $sec_key);
			$ret = (new self())->call(self::URL, $args);
			$ret = json_decode($ret, true);
            if (isset($ret['error_code'])) {
				$ret['state'] = 0;
				$error_msg = (new self())->error();
				$code = $ret['error_code'];
                if (array_key_exists($code,$error_msg)) $ret['error_msg'] = $error_msg[$code];
			} else {
            	$ret['state'] = 1;
			}
			return $ret;
		}

		//语言
		public static function language() {
            $baidu_language = array(
                'auto'  => '自动检测',
                'zh'    => '中文',
                'en'    => '英语',
                'yue'   => '粤语',
                'wyw'   => '文言文',
                'jp'    => '日语',
                'kor'   => '韩语',
                'fra'   => '法语',
                'spa'   => '西班牙语',
                'th'    => '泰语',
                'ara'   => '阿拉伯语',
                'ru'    => '俄语',
                'pt'    => '葡萄牙语',
                'de'    => '德语',
                'it'    => '意大利语',
                'el'    => '希腊语',
                'nl'    => '荷兰语',
                'pl'    => '波兰语',
                'bul'   => '保加利亚语',
                'est'   => '爱沙尼亚语',
                'dan'   => '丹麦语',
                'fin'   => '芬兰语',
                'cs'    => '捷克语',
                'rom'   => '罗马尼亚语',
                'slo'   => '斯洛文尼亚语',
                'swe'   => '瑞典语',
                'hu'    => '匈牙利语',
                'cht'   => '繁体中文',
                'vie'   => '越南语',
            );
            return $baidu_language;
		}

		//错误消息
		private function error()
		{
			$error_code = array(
				'52001' => '请求超时,请重试',
				'52002' => '系统错误,请重试',
				'52003' => 'APP ID 错误',
				'54000' => '翻译内容不能为空',
				'54001' => 'KEY 密匙错误',
				'54003' => '访问频率受限,请降低您的调用频率',
				'54004' => '免费翻译字数已使用完,请充值',
				'54005' => '请降低翻译发送频率，3s后再试',
				'58000' => '检查个人资料里填写的 IP地址 是否正确',
				'58001' => '译文语言方向不支持',
			);
			return $error_code;
		}

		//加密
		public function buildSign($query, $appID, $salt, $secKey)
		{/*{{{*/
			$str = $appID . $query . $salt . $secKey;
			$ret = md5($str);
			return $ret;
		}/*}}}*/

		//发起网络请求
		public function call($url, $args=null, $method="post", $testflag = 0, $timeout = self::CURL_TIMEOUT, $headers=array())
		{/*{{{*/
			$ret = false;
			$i = 0;
			while($ret === false)
			{
				if($i > 1)
					break;
				if($i > 0)
				{
					sleep(1);
				}
				$ret = $this->callOnce($url, $args, $method, false, $timeout, $headers);
				$i++;
			}
			return $ret;
		}/*}}}*/

		private function callOnce($url, $args=null, $method="post", $withCookie = false, $timeout = CURL_TIMEOUT, $headers=array())
		{/*{{{*/
			$ch = curl_init();
			if($method == "post")
			{
				$data = $this->convert($args);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
				curl_setopt($ch, CURLOPT_POST, 1);
			}
			else
			{
				$data = $this->convert($args);
				if($data)
				{
					if(stripos($url, "?") > 0)
					{
						$url .= "&$data";
					}
					else
					{
						$url .= "?$data";
					}
				}
			}
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			if(!empty($headers))
			{
				curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			}
			if($withCookie)
			{
				curl_setopt($ch, CURLOPT_COOKIEJAR, $_COOKIE);
			}
			$r = curl_exec($ch);
			curl_close($ch);
			return $r;
		}/*}}}*/

		private function convert(&$args)
		{/*{{{*/
			$data = '';
			if (is_array($args))
			{
				foreach ($args as $key=>$val)
				{
					if (is_array($val))
					{
						foreach ($val as $k=>$v)
						{
							$data .= $key.'['.$k.']='.rawurlencode($v).'&';
						}
					}
					else
					{
						$data .="$key=".rawurlencode($val)."&";
					}
				}
				return trim($data, "&");
			}
			return $args;
		}/*}}}*/
	}
?>
