AipBase.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. <?php
  2. namespace addons\blog\library\aip\lib;
  3. /*
  4. * Copyright (c) 2017 Baidu.com, Inc. All Rights Reserved
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  7. * use this file except in compliance with the License. You may obtain a copy of
  8. * the License at
  9. *
  10. * Http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  14. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  15. * License for the specific language governing permissions and limitations under
  16. * the License.
  17. */
  18. use Exception;
  19. /**
  20. * Aip Base 基类
  21. */
  22. class AipBase
  23. {
  24. /**
  25. * 获取access token url
  26. * @var string
  27. */
  28. protected $accessTokenUrl = 'https://aip.baidubce.com/oauth/2.0/token';
  29. /**
  30. * 反馈接口
  31. * @var string
  32. */
  33. protected $reportUrl = 'https://aip.baidubce.com/rpc/2.0/feedback/v1/report';
  34. /**
  35. * appId
  36. * @var string
  37. */
  38. protected $appId = '';
  39. /**
  40. * apiKey
  41. * @var string
  42. */
  43. protected $apiKey = '';
  44. /**
  45. * secretKey
  46. * @var string
  47. */
  48. protected $secretKey = '';
  49. /**
  50. * 权限
  51. * @var array
  52. */
  53. protected $scope = 'brain_all_scope';
  54. /**
  55. * @param string $appId
  56. * @param string $apiKey
  57. * @param string $secretKey
  58. */
  59. public function __construct($appId, $apiKey, $secretKey)
  60. {
  61. $this->appId = trim($appId);
  62. $this->apiKey = trim($apiKey);
  63. $this->secretKey = trim($secretKey);
  64. $this->isCloudUser = null;
  65. $this->client = new AipHttpClient();
  66. $this->version = '2_2_2';
  67. $this->proxies = array();
  68. }
  69. /**
  70. * 查看版本
  71. * @return string
  72. *
  73. */
  74. public function getVersion()
  75. {
  76. return $this->version;
  77. }
  78. /**
  79. * 连接超时
  80. * @param int $ms 毫秒
  81. */
  82. public function setConnectionTimeoutInMillis($ms)
  83. {
  84. $this->client->setConnectionTimeoutInMillis($ms);
  85. }
  86. /**
  87. * 响应超时
  88. * @param int $ms 毫秒
  89. */
  90. public function setSocketTimeoutInMillis($ms)
  91. {
  92. $this->client->setSocketTimeoutInMillis($ms);
  93. }
  94. /**
  95. * 代理
  96. * @param array $proxy
  97. * @return string
  98. *
  99. */
  100. public function setProxies($proxies)
  101. {
  102. $this->client->setConf($proxies);
  103. }
  104. /**
  105. * 处理请求参数
  106. * @param string $url
  107. * @param array $params
  108. * @param array $data
  109. * @param array $headers
  110. */
  111. protected function proccessRequest($url, &$params, &$data, $headers)
  112. {
  113. $params['aipSdk'] = 'php';
  114. $params['aipSdkVersion'] = $this->version;
  115. }
  116. /**
  117. * Api 请求
  118. * @param string $url
  119. * @param mixed $data
  120. * @return mixed
  121. */
  122. protected function request($url, $data, $headers = array())
  123. {
  124. try {
  125. $result = $this->validate($url, $data);
  126. if ($result !== true) {
  127. return $result;
  128. }
  129. $params = array();
  130. $authObj = $this->auth();
  131. if ($this->isCloudUser === false) {
  132. $params['access_token'] = $authObj['access_token'];
  133. }
  134. // 特殊处理
  135. $this->proccessRequest($url, $params, $data, $headers);
  136. $headers = $this->getAuthHeaders('POST', $url, $params, $headers);
  137. $response = $this->client->post($url, $data, $params, $headers);
  138. $obj = $this->proccessResult($response['content']);
  139. if (!$this->isCloudUser && isset($obj['error_code']) && $obj['error_code'] == 110) {
  140. $authObj = $this->auth(true);
  141. $params['access_token'] = $authObj['access_token'];
  142. $response = $this->client->post($url, $data, $params, $headers);
  143. $obj = $this->proccessResult($response['content']);
  144. }
  145. if (empty($obj) || !isset($obj['error_code'])) {
  146. $this->writeAuthObj($authObj);
  147. }
  148. } catch (Exception $e) {
  149. return array(
  150. 'error_code' => 'SDK108',
  151. 'error_msg' => 'connection or read data timeout',
  152. );
  153. }
  154. return $obj;
  155. }
  156. /**
  157. * Api 多个并发请求
  158. * @param string $url
  159. * @param mixed $data
  160. * @return mixed
  161. */
  162. protected function multi_request($url, $data)
  163. {
  164. try {
  165. $params = array();
  166. $authObj = $this->auth();
  167. $headers = $this->getAuthHeaders('POST', $url);
  168. if ($this->isCloudUser === false) {
  169. $params['access_token'] = $authObj['access_token'];
  170. }
  171. $responses = $this->client->multi_post($url, $data, $params, $headers);
  172. $is_success = false;
  173. foreach ($responses as $response) {
  174. $obj = $this->proccessResult($response['content']);
  175. if (empty($obj) || !isset($obj['error_code'])) {
  176. $is_success = true;
  177. }
  178. if (!$this->isCloudUser && isset($obj['error_code']) && $obj['error_code'] == 110) {
  179. $authObj = $this->auth(true);
  180. $params['access_token'] = $authObj['access_token'];
  181. $responses = $this->client->post($url, $data, $params, $headers);
  182. break;
  183. }
  184. }
  185. if ($is_success) {
  186. $this->writeAuthObj($authObj);
  187. }
  188. $objs = array();
  189. foreach ($responses as $response) {
  190. $objs[] = $this->proccessResult($response['content']);
  191. }
  192. } catch (Exception $e) {
  193. return array(
  194. 'error_code' => 'SDK108',
  195. 'error_msg' => 'connection or read data timeout',
  196. );
  197. }
  198. return $objs;
  199. }
  200. /**
  201. * 格式检查
  202. * @param string $url
  203. * @param array $data
  204. * @return mix
  205. */
  206. protected function validate($url, &$data)
  207. {
  208. return true;
  209. }
  210. /**
  211. * 格式化结果
  212. * @param $content string
  213. * @return mixed
  214. */
  215. protected function proccessResult($content)
  216. {
  217. return json_decode($content, true);
  218. }
  219. /**
  220. * 返回 access token 路径
  221. * @return string
  222. */
  223. private function getAuthFilePath()
  224. {
  225. return dirname(__FILE__) . DIRECTORY_SEPARATOR . md5($this->apiKey);
  226. }
  227. /**
  228. * 写入本地文件
  229. * @param array $obj
  230. * @return void
  231. */
  232. private function writeAuthObj($obj)
  233. {
  234. if ($obj === null || (isset($obj['is_read']) && $obj['is_read'] === true)) {
  235. return;
  236. }
  237. $obj['time'] = time();
  238. $obj['is_cloud_user'] = $this->isCloudUser;
  239. @file_put_contents($this->getAuthFilePath(), json_encode($obj));
  240. }
  241. /**
  242. * 读取本地缓存
  243. * @return array
  244. */
  245. private function readAuthObj()
  246. {
  247. $content = @file_get_contents($this->getAuthFilePath());
  248. if ($content !== false) {
  249. $obj = json_decode($content, true);
  250. $this->isCloudUser = $obj['is_cloud_user'];
  251. $obj['is_read'] = true;
  252. if ($this->isCloudUser || $obj['time'] + $obj['expires_in'] - 30 > time()) {
  253. return $obj;
  254. }
  255. }
  256. return null;
  257. }
  258. /**
  259. * 认证
  260. * @param bool $refresh 是否刷新
  261. * @return array
  262. */
  263. private function auth($refresh = false)
  264. {
  265. //非过期刷新
  266. if (!$refresh) {
  267. $obj = $this->readAuthObj();
  268. if (!empty($obj)) {
  269. return $obj;
  270. }
  271. }
  272. $response = $this->client->get($this->accessTokenUrl, array(
  273. 'grant_type' => 'client_credentials',
  274. 'client_id' => $this->apiKey,
  275. 'client_secret' => $this->secretKey,
  276. ));
  277. $obj = json_decode($response['content'], true);
  278. $this->isCloudUser = !$this->isPermission($obj);
  279. return $obj;
  280. }
  281. /**
  282. * 判断认证是否有权限
  283. * @param array $authObj
  284. * @return boolean
  285. */
  286. protected function isPermission($authObj)
  287. {
  288. if (empty($authObj) || !isset($authObj['scope'])) {
  289. return false;
  290. }
  291. $scopes = explode(' ', $authObj['scope']);
  292. return in_array($this->scope, $scopes);
  293. }
  294. /**
  295. * @param string $method HTTP method
  296. * @param string $url
  297. * @param array $param 参数
  298. * @return array
  299. */
  300. private function getAuthHeaders($method, $url, $params = array(), $headers = array())
  301. {
  302. //不是云的老用户则不用在header中签名 认证
  303. if ($this->isCloudUser === false) {
  304. return $headers;
  305. }
  306. $obj = parse_url($url);
  307. if (!empty($obj['query'])) {
  308. foreach (explode('&', $obj['query']) as $kv) {
  309. if (!empty($kv)) {
  310. list($k, $v) = explode('=', $kv, 2);
  311. $params[$k] = $v;
  312. }
  313. }
  314. }
  315. //UTC 时间戳
  316. $timestamp = gmdate('Y-m-d\TH:i:s\Z');
  317. $headers['Host'] = isset($obj['port']) ? sprintf('%s:%s', $obj['host'], $obj['port']) : $obj['host'];
  318. $headers['x-bce-date'] = $timestamp;
  319. //签名
  320. $headers['authorization'] = AipSampleSigner::sign(array(
  321. 'ak' => $this->apiKey,
  322. 'sk' => $this->secretKey,
  323. ), $method, $obj['path'], $headers, $params, array(
  324. 'timestamp' => $timestamp,
  325. 'headersToSign' => array_keys($headers),
  326. ));
  327. return $headers;
  328. }
  329. /**
  330. * 反馈
  331. *
  332. * @param array $feedbacks
  333. * @return array
  334. */
  335. public function report($feedback)
  336. {
  337. $data = array();
  338. $data['feedback'] = $feedback;
  339. return $this->request($this->reportUrl, $data);
  340. }
  341. }