Cos.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. <?php
  2. namespace crmeb\services\upload\storage;
  3. use crmeb\basic\BaseUpload;
  4. use crmeb\exceptions\UploadException;
  5. use Guzzle\Http\EntityBody;
  6. use Qcloud\Cos\Client;
  7. use think\Exception;
  8. use think\exception\ValidateException;
  9. /**
  10. * 腾讯云COS文件上传
  11. * Class COS
  12. * @package crmeb\services\upload\storage
  13. */
  14. class Cos extends BaseUpload
  15. {
  16. /**
  17. * accessKey
  18. * @var mixed
  19. */
  20. protected $accessKey;
  21. /**
  22. * secretKey
  23. * @var mixed
  24. */
  25. protected $secretKey;
  26. /**
  27. * 句柄
  28. * @var Client
  29. */
  30. protected $handle;
  31. /**
  32. * 空间域名 Domain
  33. * @var mixed
  34. */
  35. protected $uploadUrl;
  36. /**
  37. * 存储空间名称 公开空间
  38. * @var mixed
  39. */
  40. protected $storageName;
  41. /**
  42. * COS使用 所属地域
  43. * @var mixed|null
  44. */
  45. protected $storageRegion;
  46. /**
  47. * 初始化
  48. * @param array $config
  49. * @return mixed|void
  50. */
  51. public function initialize(array $config)
  52. {
  53. parent::initialize($config);
  54. $this->accessKey = $config['accessKey'] ?? null;
  55. $this->secretKey = $config['secretKey'] ?? null;
  56. $this->uploadUrl = $this->checkUploadUrl($config['uploadUrl'] ?? '');
  57. $this->storageName = $config['storageName'] ?? null;
  58. $this->storageRegion = $config['storageRegion'] ?? null;
  59. }
  60. /**
  61. * 实例化cos
  62. * @return Client
  63. */
  64. protected function app()
  65. {
  66. if (!$this->accessKey || !$this->secretKey) {
  67. throw new UploadException('Please configure accessKey and secretKey');
  68. }
  69. $this->handle = new Client(['region' => $this->storageRegion, 'credentials' => [
  70. 'secretId' => $this->accessKey, 'secretKey' => $this->secretKey
  71. ]]);
  72. return $this->handle;
  73. }
  74. /**
  75. * 上传文件
  76. * @param string|null $file
  77. * @param bool $isStream 是否为流上传
  78. * @param string|null $fileContent 流内容
  79. * @return array|bool|\StdClass
  80. */
  81. protected function upload(string $file = null, bool $isStream = false, string $fileContent = null)
  82. {
  83. if (!$isStream) {
  84. $fileHandle = app()->request->file($file);
  85. if (!$fileHandle) {
  86. return $this->setError('Upload file does not exist');
  87. }
  88. if ($this->validate) {
  89. try {
  90. validate([$file => $this->validate])->check([$file => $fileHandle]);
  91. } catch (ValidateException $e) {
  92. return $this->setError($e->getMessage());
  93. }
  94. }
  95. $key = $this->saveFileName($fileHandle->getRealPath(), $fileHandle->getOriginalExtension());
  96. $body = fopen($fileHandle->getRealPath(), 'rb');
  97. } else {
  98. $key = $file;
  99. $body = $fileContent;
  100. }
  101. try {
  102. $this->fileInfo->uploadInfo = $this->app()->putObject([
  103. 'Bucket' => $this->storageName,
  104. 'Key' => $key,
  105. 'Body' => $body
  106. ]);
  107. $this->fileInfo->filePath = $this->uploadUrl . '/' . $key;
  108. $this->fileInfo->fileName = $key;
  109. return $this->fileInfo;
  110. } catch (UploadException $e) {
  111. return $this->setError($e->getMessage());
  112. }
  113. }
  114. /**
  115. * 文件流上传
  116. * @param string $fileContent
  117. * @param string|null $key
  118. * @return array|bool|mixed|\StdClass
  119. */
  120. public function stream(string $fileContent, string $key = null)
  121. {
  122. if (!$key) {
  123. $key = $this->saveFileName();
  124. }
  125. return $this->upload($key, true, $fileContent);
  126. }
  127. /**
  128. * 文件上传
  129. * @param string $file
  130. * @param string $path
  131. * @return array|bool|mixed|\StdClass
  132. */
  133. public function move(string $file = 'file',$path=null)
  134. {
  135. return $this->upload($file);
  136. }
  137. /**
  138. * TODO 删除资源
  139. * @param $key
  140. * @return mixed
  141. */
  142. public function delete(string $filePath)
  143. {
  144. try {
  145. return $this->app()->deleteObject(['Bucket' => $this->storageName, 'Key' => $filePath]);
  146. } catch (\Exception $e) {
  147. return $this->setError($e->getMessage());
  148. }
  149. }
  150. /**
  151. * 获取腾讯云存储临时密钥
  152. * @return array|bool|mixed|null|string
  153. */
  154. public function getTempKeys()
  155. {
  156. // TODO: Implement getTempKeys() method.
  157. $config = array(
  158. 'url' => 'https://sts.tencentcloudapi.com/',
  159. 'domain' => 'sts.tencentcloudapi.com',
  160. 'proxy' => '',
  161. 'secretId' => $this->accessKey, // 固定密钥
  162. 'secretKey' => $this->secretKey, // 固定密钥
  163. 'bucket' => $this->storageName, // 换成你的 bucket
  164. 'region' => $this->storageRegion, // 换成 bucket 所在园区
  165. 'durationSeconds' => 1800, // 密钥有效期
  166. 'allowPrefix' => '*', // 这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径,例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
  167. // 密钥的权限列表。简单上传和分片需要以下的权限,其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
  168. 'allowActions' => array (
  169. // 简单上传
  170. 'name/cos:PutObject',
  171. 'name/cos:PostObject',
  172. // 分片上传
  173. 'name/cos:InitiateMultipartUpload',
  174. 'name/cos:ListMultipartUploads',
  175. 'name/cos:ListParts',
  176. 'name/cos:UploadPart',
  177. 'name/cos:CompleteMultipartUpload'
  178. )
  179. );
  180. $result = null;
  181. try{
  182. if(array_key_exists('policy', $config)){
  183. $policy = $config['policy'];
  184. }else{
  185. if(array_key_exists('bucket', $config)){
  186. $ShortBucketName = substr($config['bucket'],0, strripos($config['bucket'], '-'));
  187. $AppId = substr($config['bucket'], 1 + strripos($config['bucket'], '-'));
  188. }else{
  189. throw new Exception("bucket== null");
  190. }
  191. if(array_key_exists('allowPrefix', $config)){
  192. if(!(strpos($config['allowPrefix'], '/') === 0)){
  193. $config['allowPrefix'] = '/' . $config['allowPrefix'];
  194. }
  195. }else{
  196. throw new Exception("allowPrefix == null");
  197. }
  198. $policy = array(
  199. 'version'=> '2.0',
  200. 'statement'=> array(
  201. array(
  202. 'action'=> $config['allowActions'],
  203. 'effect'=> 'allow',
  204. 'principal'=> array('qcs'=> array('*')),
  205. 'resource'=> array(
  206. 'qcs::cos:' . $config['region'] . ':uid/' . $AppId . ':' . $config['bucket'] . $config['allowPrefix']
  207. )
  208. )
  209. )
  210. );
  211. }
  212. $policyStr = str_replace('\\/', '/', json_encode($policy));
  213. $Action = 'GetFederationToken';
  214. $Nonce = rand(10000, 20000);
  215. $Timestamp = time();
  216. $Method = 'POST';
  217. if(array_key_exists('durationSeconds', $config)){
  218. if(!(is_integer($config['durationSeconds']))){
  219. throw new exception("durationSeconds must be a int type");
  220. }
  221. }
  222. $params = array(
  223. 'SecretId'=> $config['secretId'],
  224. 'Timestamp'=> $Timestamp,
  225. 'Nonce'=> $Nonce,
  226. 'Action'=> $Action,
  227. 'DurationSeconds'=> $config['durationSeconds'],
  228. 'Version'=>'2018-08-13',
  229. 'Name'=> 'cos',
  230. 'Region'=> $config['region'],
  231. 'Policy'=> urlencode($policyStr)
  232. );
  233. $params['Signature'] = $this->getSignature($params, $config['secretKey'], $Method, $config);
  234. $url = $config['url'];
  235. $ch = curl_init($url);
  236. if(array_key_exists('proxy', $config)){
  237. $config['proxy'] && curl_setopt($ch, CURLOPT_PROXY, $config['proxy']);
  238. }
  239. curl_setopt($ch, CURLOPT_HEADER, 0);
  240. curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
  241. curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
  242. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  243. curl_setopt($ch, CURLOPT_POST, 1);
  244. curl_setopt($ch, CURLOPT_POSTFIELDS, $this->json2str($params));
  245. $result = curl_exec($ch);
  246. if(curl_errno($ch)) $result = curl_error($ch);
  247. curl_close($ch);
  248. $result = json_decode($result, 1);
  249. if (isset($result['Response'])) {
  250. $result = $result['Response'];
  251. if(isset($result['Error'])){
  252. throw new Exception("get cam failed");
  253. }
  254. $result['startTime'] = $result['ExpiredTime'] - $config['durationSeconds'];
  255. }
  256. $result = $this->backwardCompat($result);
  257. $result['url'] = $this->uploadUrl.'/';
  258. $result['type'] = 'COS';
  259. return $result;
  260. }catch(Exception $e){
  261. if($result == null){
  262. $result = "error: " . + $e->getMessage();
  263. }else{
  264. $result = json_encode($result);
  265. }
  266. throw new Exception($result);
  267. }
  268. }
  269. /**
  270. * 计算临时密钥用的签名
  271. * @param $opt
  272. * @param $key
  273. * @param $method
  274. * @param $config
  275. * @return string
  276. */
  277. public function getSignature($opt, $key, $method, $config) {
  278. $formatString = $method . $config['domain'] . '/?' . $this->json2str($opt, 1);
  279. $sign = hash_hmac('sha1', $formatString, $key);
  280. $sign = base64_encode($this->_hex2bin($sign));
  281. return $sign;
  282. }
  283. public function _hex2bin($data) {
  284. $len = strlen($data);
  285. return pack("H" . $len, $data);
  286. }
  287. // obj 转 query string
  288. public function json2str($obj, $notEncode = false) {
  289. ksort($obj);
  290. $arr = array();
  291. if(!is_array($obj)){
  292. return $this->setError($obj . " must be a array");
  293. }
  294. foreach ($obj as $key => $val) {
  295. array_push($arr, $key . '=' . ($notEncode ? $val : rawurlencode($val)));
  296. }
  297. return join('&', $arr);
  298. }
  299. // v2接口的key首字母小写,v3改成大写,此处做了向下兼容
  300. public function backwardCompat($result) {
  301. if(!is_array($result)){
  302. return $this->setError($result . " must be a array");
  303. }
  304. $compat = array();
  305. foreach ($result as $key => $value) {
  306. if(is_array($value)) {
  307. $compat[lcfirst($key)] = $this->backwardCompat($value);
  308. } elseif ($key == 'Token') {
  309. $compat['sessionToken'] = $value;
  310. } else {
  311. $compat[lcfirst($key)] = $value;
  312. }
  313. }
  314. return $compat;
  315. }
  316. }