OSSUtils.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. <?php
  2. namespace AlibabaCloud\Tea\OSSUtils;
  3. use Adbar\Dot;
  4. use AlibabaCloud\Tea\Request;
  5. class OSSUtils
  6. {
  7. const SIGN_KEY_LIST = [
  8. 'location',
  9. 'cors',
  10. 'objectMeta',
  11. 'uploadId',
  12. 'partNumber',
  13. 'security-token',
  14. 'position',
  15. 'img',
  16. 'style',
  17. 'styleName',
  18. 'replication',
  19. 'replicationProgress',
  20. 'replicationLocation',
  21. 'cname',
  22. 'qos',
  23. 'startTime',
  24. 'endTime',
  25. 'symlink',
  26. 'x-oss-process',
  27. 'response-content-type',
  28. 'response-content-language',
  29. 'response-expires',
  30. 'response-cache-control',
  31. 'response-content-disposition',
  32. 'response-content-encoding',
  33. 'udf',
  34. 'udfName',
  35. 'udfImage',
  36. 'udfId',
  37. 'udfImageDesc',
  38. 'udfApplication',
  39. 'udfApplicationLog',
  40. 'restore',
  41. 'callback',
  42. 'callback-var',
  43. 'policy',
  44. 'encryption',
  45. 'versions',
  46. 'versioning',
  47. 'versionId',
  48. ];
  49. private static $defaultUserAgent = '';
  50. /**
  51. * @param string $msg
  52. *
  53. * @return array
  54. */
  55. public static function getErrMessage($msg)
  56. {
  57. $data = self::parseXml($msg);
  58. return $data['Error'];
  59. }
  60. /**
  61. * @param array $val
  62. * @param string $prefix
  63. *
  64. * @return array
  65. */
  66. public static function toMeta($val, $prefix)
  67. {
  68. if (empty($val)) {
  69. return [];
  70. }
  71. $res = [];
  72. foreach ($val as $k => $v) {
  73. $newKey = strtolower($k);
  74. if (0 !== strpos($k, $prefix)) {
  75. $newKey = $prefix . $newKey;
  76. }
  77. $res[$newKey] = $v;
  78. }
  79. return $res;
  80. }
  81. public static function parseMeta($val, $prefix)
  82. {
  83. if (empty($val)) {
  84. return [];
  85. }
  86. $res = [];
  87. foreach ($val as $k => $v) {
  88. $newKey = strtolower($k);
  89. if (0 === strpos($newKey, $prefix)) {
  90. $newKey = str_replace($prefix, '', $newKey);
  91. }
  92. $res[$newKey] = $v;
  93. }
  94. return $res;
  95. }
  96. public static function getContentType($fileName)
  97. {
  98. $mapping = require(dirname(__DIR__) . '/mime.types.php');
  99. if (!empty($fileName) && !empty(trim($fileName))) {
  100. $ext = pathinfo($fileName, PATHINFO_EXTENSION);
  101. $ext = strtolower(trim($ext));
  102. if (!empty($mapping['mimes'][$ext])) {
  103. return $mapping['mimes'][$ext][0];
  104. }
  105. }
  106. return null;
  107. }
  108. public static function getContentMD5($body, $isEnableMD5)
  109. {
  110. if (false === $isEnableMD5) {
  111. return '';
  112. }
  113. return base64_encode(md5($body, true));
  114. }
  115. public static function encode($val, $encodeType)
  116. {
  117. $strs = explode('/', $val);
  118. $len = \count($strs);
  119. switch ($encodeType) {
  120. case 'Base64':
  121. $strs[$len - 1] = base64_encode($strs[$len - 1]);
  122. break;
  123. case 'UrlEncode':
  124. $strs[$len - 1] = rawurlencode($strs[$len - 1]);
  125. break;
  126. }
  127. return implode('/', $strs);
  128. }
  129. public static function getUserAgent($val)
  130. {
  131. if (empty($val)) {
  132. return self::getDefaultUserAgent();
  133. }
  134. return self::getDefaultUserAgent() . ' ' . $val;
  135. }
  136. public static function getHost($bucketName, $regionId, $endpoint, $hostModel)
  137. {
  138. if (empty($regionId) || empty(trim($regionId))) {
  139. $regionId = 'cn-hangzhou';
  140. }
  141. if (empty($endpoint) || empty(trim($endpoint))) {
  142. $endpoint = 'oss-' . $regionId . '.aliyuncs.com';
  143. }
  144. if (!empty($bucketName)) {
  145. $hostModel = null === $hostModel ? '' : $hostModel;
  146. if ('ip' === $hostModel) {
  147. $host = $endpoint . '/' . $bucketName;
  148. } elseif ('cname' == $hostModel) {
  149. $host = $endpoint;
  150. } else {
  151. $host = $bucketName . '.' . $endpoint;
  152. }
  153. } else {
  154. $host = $endpoint;
  155. }
  156. return $host;
  157. }
  158. /**
  159. * @param resource $body
  160. * @param array $res
  161. *
  162. * @return VerifyStream
  163. */
  164. public static function inject($body, &$res)
  165. {
  166. return new VerifyStream($body, $res);
  167. }
  168. /**
  169. * @param Request $request
  170. * @param string $bucketName
  171. * @param string $accessKeyId
  172. * @param string $accessKeySecret
  173. * @param string $signatureVersion
  174. * @param string[] $addtionalHeaders
  175. *
  176. * @return string
  177. */
  178. public static function getSignature($request, $bucketName, $accessKeyId, $accessKeySecret, $signatureVersion, $addtionalHeaders)
  179. {
  180. $signatureVersion = strtolower($signatureVersion);
  181. if ('v2' === $signatureVersion) {
  182. if (empty($addtionalHeaders)) {
  183. return 'OSS2 AccessKeyId:' . $accessKeyId .
  184. ',Signature:' . self::getSignatureV2($request, $bucketName, $accessKeySecret, $addtionalHeaders);
  185. }
  186. return 'OSS2 AccessKeyId:' . $accessKeyId .
  187. ',AdditionalHeaders:' . implode(';', $addtionalHeaders) .
  188. ',Signature:' . self::getSignatureV2($request, $bucketName, $accessKeySecret, $addtionalHeaders);
  189. }
  190. return 'OSS ' . $accessKeyId . ':' . self::getSignatureV1($request, $bucketName, $accessKeySecret);
  191. }
  192. /**
  193. * @param string $val
  194. * @param string $decodeType
  195. *
  196. * @return string
  197. */
  198. public static function decode($val, $decodeType)
  199. {
  200. switch ($decodeType) {
  201. case 'Base64Decode':
  202. $res = base64_decode($val);
  203. return false === $res ? '' : $res;
  204. case 'UrlDecode':
  205. return rawurldecode($val);
  206. }
  207. return $val;
  208. }
  209. private static function parseXml($xmlStr)
  210. {
  211. if (\PHP_VERSION_ID < 80000) {
  212. libxml_disable_entity_loader(true);
  213. }
  214. $xml = simplexml_load_string($xmlStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  215. $rootName = $xml->getName();
  216. return [
  217. $rootName => json_decode(
  218. json_encode(
  219. $xml
  220. ),
  221. true
  222. ),
  223. ];
  224. }
  225. private static function getDefaultUserAgent()
  226. {
  227. if (empty(self::$defaultUserAgent)) {
  228. self::$defaultUserAgent = 'Alibaba Cloud (' . PHP_OS . ') ';
  229. self::$defaultUserAgent .= 'TeaCore/3';
  230. }
  231. return self::$defaultUserAgent;
  232. }
  233. /**
  234. * @param Request $request
  235. * @param string $bucketName
  236. * @param string $accessKeySecret
  237. *
  238. * @return string
  239. */
  240. private static function getSignatureV1($request, $bucketName, $accessKeySecret)
  241. {
  242. $canonicalizeResource = '';
  243. if (!empty($bucketName)) {
  244. $canonicalizeResource = '/' . $bucketName;
  245. }
  246. $canonicalizeResource .= $request->pathname;
  247. $query = $request->query;
  248. ksort($query);
  249. if (!empty($query)) {
  250. if (false === strpos($canonicalizeResource, '?')) {
  251. $canonicalizeResource .= '?';
  252. }
  253. foreach ($query as $k => $v) {
  254. if (\in_array($k, self::SIGN_KEY_LIST) && null !== $v && '' !== $v) {
  255. if ('?' === $canonicalizeResource[\strlen($canonicalizeResource) - 1]) {
  256. $canonicalizeResource .= $k . '=' . $v;
  257. } else {
  258. $canonicalizeResource .= '&' . $k . '=' . $v;
  259. }
  260. }
  261. }
  262. }
  263. $headers = new Dot($request->headers);
  264. $signString = implode("\n", [
  265. strtoupper($request->method),
  266. $headers->get('content-md5', ''),
  267. $headers->get('content-type', ''),
  268. $headers->get('date', ''),
  269. implode("\n", self::getCanonicalizeHeaders($request->headers)),
  270. $canonicalizeResource,
  271. ]);
  272. return base64_encode(
  273. hash_hmac(
  274. 'sha1',
  275. $signString,
  276. $accessKeySecret,
  277. true
  278. )
  279. );
  280. }
  281. /**
  282. * @param Request $request
  283. * @param string $bucketName
  284. * @param string $accessKeySecret
  285. * @param string[] $addtionalHeaders
  286. *
  287. * @return string
  288. */
  289. private static function getSignatureV2($request, $bucketName, $accessKeySecret, $addtionalHeaders)
  290. {
  291. if (empty($addtionalHeaders)) {
  292. $addtionalHeaders = [];
  293. }
  294. $canonicalizeResource = '';
  295. $pathname = $request->pathname;
  296. if (!empty($bucketName)) {
  297. $pathname = '/' . $bucketName . $pathname;
  298. }
  299. $tmp = explode('?', $pathname);
  300. $canonicalizeResource .= rawurlencode($tmp[0]);
  301. $sortDict = $request->query;
  302. if (\count($tmp) > 1 && !empty($tmp[1])) {
  303. $sortDict[$tmp[1]] = '';
  304. }
  305. ksort($sortDict);
  306. if (\count($sortDict) > 0 && false === strpos($canonicalizeResource, '?')) {
  307. $canonicalizeResource .= '?';
  308. }
  309. $flag = '?' === $canonicalizeResource[\strlen($canonicalizeResource) - 1];
  310. foreach ($sortDict as $k => $v) {
  311. if (!$flag) {
  312. $canonicalizeResource .= '&';
  313. } else {
  314. $flag = false;
  315. }
  316. if (!empty($v)) {
  317. $canonicalizeResource .= rawurlencode($k) . '=' . rawurlencode($v);
  318. } else {
  319. $canonicalizeResource .= rawurlencode($k);
  320. }
  321. }
  322. $headers = [];
  323. $headerKeys = [];
  324. foreach ($request->headers as $k => $v) {
  325. $key = strtolower($k);
  326. if (0 === strpos($key, 'x-oss-')) {
  327. $headers[$key] = $v;
  328. }
  329. $headerKeys[$key] = $k;
  330. }
  331. foreach ($addtionalHeaders as $header) {
  332. $header = strtolower($header);
  333. if (isset($headerKeys[$header]) && !isset($headers[$header])) {
  334. $headers[$header] = $request->headers[$headerKeys[$header]];
  335. }
  336. }
  337. $requestHeaders = new Dot($request->headers);
  338. $signString = implode("\n", [
  339. strtoupper($request->method),
  340. $requestHeaders->get('content-md5', ''),
  341. $requestHeaders->get('content-type', ''),
  342. $requestHeaders->get('date', ''),
  343. implode("\n", self::getCanonicalizeHeaders($headers)),
  344. implode(';', $addtionalHeaders),
  345. $canonicalizeResource,
  346. ]);
  347. return base64_encode(
  348. hash_hmac(
  349. 'sha256',
  350. $signString,
  351. $accessKeySecret,
  352. true
  353. )
  354. );
  355. }
  356. /**
  357. * @param array $headers
  358. *
  359. * @return array
  360. */
  361. private static function getCanonicalizeHeaders($headers)
  362. {
  363. $canonicalizeHeaders = [];
  364. foreach ($headers as $k => $v) {
  365. $headerName = strtolower($k);
  366. if (0 === strpos($headerName, 'x-oss-')) {
  367. array_push($canonicalizeHeaders, $headerName . ':' . $v);
  368. }
  369. }
  370. ksort($canonicalizeHeaders);
  371. return $canonicalizeHeaders;
  372. }
  373. }