<?php
namespace model;
use \model;
/**
 * Class 翻译接口
 * @package model
 */
class fanyi
{
	protected $config = null;

	function __construct()
	{
		$this->config = \mvc::$cfg['fanyi'];
	}


	//翻译入口
	function translate($query, $from, $to)
	{
		$arr = [];
		if(empty($query)) return $arr;
		$args = array(
			'q' => $query,
			'appid' => $this->config['APP_ID'],
			'salt' => rand(10000,99999),
			'from' => $from,
			'to' => $to,
		);
		$args['sign'] = $this->buildSign($query, $this->config['APP_ID'], $args['salt'], $this->config['SEC_KEY']);
		for($i = 0; $i < 5; $i++){
			$jsonstr = $this->callOnce("http://api.fanyi.baidu.com/api/trans/vip/translate", $args);
			$ret = json_decode($jsonstr, true);
			if($ret['trans_result']){
				$arr = [
					'from'=>$ret['from'],
					'to'=>$ret['to'],
					'src'=>$ret['trans_result'][0]['src'],
					'dst'=>$ret['trans_result'][0]['dst']
				];
				break;
			}else if(stripos($ret['error_msg'], 'Limit')){
				usleep(500*1000);
			}else{
				exitJson('翻译接口异常：'.$jsonstr);
			}
		}
		return $arr; 
	}

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

	
	function callOnce($url, $args=null, $method="post", $withCookie = false, $timeout = 10, $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;
	}/*}}}*/

	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;
	}/*}}}*/
}