PageRenderTime 51ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/xianpipa/ThinkPHP/Library/Think/Upload/Driver/Qiniu/QiniuStorage.class.php

https://gitlab.com/fangfangchen/xianpipa
PHP | 333 lines | 298 code | 28 blank | 7 comment | 20 complexity | b54f31aa2b2eab1d831036244cd86776 MD5 | raw file
  1. <?php
  2. namespace Think\Upload\Driver\Qiniu;
  3. class QiniuStorage {
  4. public $QINIU_RSF_HOST = 'http://rsf.qbox.me';
  5. public $QINIU_RS_HOST = 'http://rs.qbox.me';
  6. public $QINIU_UP_HOST = 'http://up.qiniu.com';
  7. public $timeout = '';
  8. public function __construct($config){
  9. $this->sk = $config['secrectKey'];
  10. $this->ak = $config['accessKey'];
  11. $this->domain = $config['domain'];
  12. $this->bucket = $config['bucket'];
  13. $this->timeout = isset($config['timeout'])? $config['timeout'] : 3600;
  14. }
  15. static function sign($sk, $ak, $data){
  16. $sign = hash_hmac('sha1', $data, $sk, true);
  17. return $ak . ':' . self::Qiniu_Encode($sign);
  18. }
  19. static function signWithData($sk, $ak, $data){
  20. $data = self::Qiniu_Encode($data);
  21. return self::sign($sk, $ak, $data) . ':' . $data;
  22. }
  23. public function accessToken($url, $body=''){
  24. $parsed_url = parse_url($url);
  25. $path = $parsed_url['path'];
  26. $access = $path;
  27. if (isset($parsed_url['query'])) {
  28. $access .= "?" . $parsed_url['query'];
  29. }
  30. $access .= "\n";
  31. if($body){
  32. $access .= $body;
  33. }
  34. return self::sign($this->sk, $this->ak, $access);
  35. }
  36. public function UploadToken($sk ,$ak ,$param){
  37. $param['deadline'] = $param['Expires'] == 0? 3600: $param['Expires'];
  38. $param['deadline'] += time();
  39. $data = array('scope'=> $this->bucket, 'deadline'=>$param['deadline']);
  40. if (!empty($param['CallbackUrl'])) {
  41. $data['callbackUrl'] = $param['CallbackUrl'];
  42. }
  43. if (!empty($param['CallbackBody'])) {
  44. $data['callbackBody'] = $param['CallbackBody'];
  45. }
  46. if (!empty($param['ReturnUrl'])) {
  47. $data['returnUrl'] = $param['ReturnUrl'];
  48. }
  49. if (!empty($param['ReturnBody'])) {
  50. $data['returnBody'] = $param['ReturnBody'];
  51. }
  52. if (!empty($param['AsyncOps'])) {
  53. $data['asyncOps'] = $param['AsyncOps'];
  54. }
  55. if (!empty($param['EndUser'])) {
  56. $data['endUser'] = $param['EndUser'];
  57. }
  58. $data = json_encode($data);
  59. return self::SignWithData($sk, $ak, $data);
  60. }
  61. public function upload($config, $file){
  62. $uploadToken = $this->UploadToken($this->sk, $this->ak, $config);
  63. $url = "{$this->QINIU_UP_HOST}";
  64. $mimeBoundary = md5(microtime());
  65. $header = array('Content-Type'=>'multipart/form-data;boundary='.$mimeBoundary);
  66. $data = array();
  67. $fields = array(
  68. 'token'=>$uploadToken,
  69. 'key'=>$config['saveName']? $config['save_name'] : $file['fileName'],
  70. );
  71. if(is_array($config['custom_fields']) && $config['custom_fields'] !== array()){
  72. $fields = array_merge($fields, $config['custom_fields']);
  73. }
  74. foreach ($fields as $name => $val) {
  75. array_push($data, '--' . $mimeBoundary);
  76. array_push($data, "Content-Disposition: form-data; name=\"$name\"");
  77. array_push($data, '');
  78. array_push($data, $val);
  79. }
  80. //文件
  81. array_push($data, '--' . $mimeBoundary);
  82. $name = $file['name'];
  83. $fileName = $file['fileName'];
  84. $fileBody = $file['fileBody'];
  85. $fileName = self::Qiniu_escapeQuotes($fileName);
  86. array_push($data, "Content-Disposition: form-data; name=\"$name\"; filename=\"$fileName\"");
  87. array_push($data, 'Content-Type: application/octet-stream');
  88. array_push($data, '');
  89. array_push($data, $fileBody);
  90. array_push($data, '--' . $mimeBoundary . '--');
  91. array_push($data, '');
  92. $body = implode("\r\n", $data);
  93. $response = $this->request($url, 'POST', $header, $body);
  94. return $response;
  95. }
  96. public function dealWithType($key, $type){
  97. $param = $this->buildUrlParam();
  98. $url = '';
  99. switch($type){
  100. case 'img':
  101. $url = $this->downLink($key);
  102. if($param['imageInfo']){
  103. $url .= '?imageInfo';
  104. }else if($param['exif']){
  105. $url .= '?exif';
  106. }else if($param['imageView']){
  107. $url .= '?imageView/'.$param['mode'];
  108. if($param['w'])
  109. $url .= "/w/{$param['w']}";
  110. if($param['h'])
  111. $url .= "/h/{$param['h']}";
  112. if($param['q'])
  113. $url .= "/q/{$param['q']}";
  114. if($param['format'])
  115. $url .= "/format/{$param['format']}";
  116. }
  117. break;
  118. case 'video': //TODO 视频处理
  119. case 'doc':
  120. $url = $this->downLink($key);
  121. $url .= '?md2html';
  122. if(isset($param['mode']))
  123. $url .= '/'.(int)$param['mode'];
  124. if($param['cssurl'])
  125. $url .= '/'. self::Qiniu_Encode($param['cssurl']);
  126. break;
  127. }
  128. return $url;
  129. }
  130. public function buildUrlParam(){
  131. return $_REQUEST;
  132. }
  133. //获取某个路径下的文件列表
  134. public function getList($query = array(), $path = ''){
  135. $query = array_merge(array('bucket'=>$this->bucket), $query);
  136. $url = "{$this->QINIU_RSF_HOST}/list?".http_build_query($query);
  137. $accessToken = $this->accessToken($url);
  138. $response = $this->request($url, 'POST', array('Authorization'=>"QBox $accessToken"));
  139. return $response;
  140. }
  141. //获取某个文件的信息
  142. public function info($key){
  143. $key = trim($key);
  144. $url = "{$this->QINIU_RS_HOST}/stat/" . self::Qiniu_Encode("{$this->bucket}:{$key}");
  145. $accessToken = $this->accessToken($url);
  146. $response = $this->request($url, 'POST', array(
  147. 'Authorization'=>"QBox $accessToken",
  148. ));
  149. return $response;
  150. }
  151. //获取文件下载资源链接
  152. public function downLink($key){
  153. $key = urlencode($key);
  154. $key = self::Qiniu_escapeQuotes($key);
  155. $url = "http://{$this->domain}/{$key}";
  156. return $url;
  157. }
  158. //重命名单个文件
  159. public function rename($file, $new_file){
  160. $key = trim($file);
  161. $url = "{$this->QINIU_RS_HOST}/move/" . self::Qiniu_Encode("{$this->bucket}:{$key}") .'/'. self::Qiniu_Encode("{$this->bucket}:{$new_file}");
  162. trace($url);
  163. $accessToken = $this->accessToken($url);
  164. $response = $this->request($url, 'POST', array('Authorization'=>"QBox $accessToken"));
  165. return $response;
  166. }
  167. //删除单个文件
  168. public function del($file){
  169. $key = trim($file);
  170. $url = "{$this->QINIU_RS_HOST}/delete/" . self::Qiniu_Encode("{$this->bucket}:{$key}");
  171. $accessToken = $this->accessToken($url);
  172. $response = $this->request($url, 'POST', array('Authorization'=>"QBox $accessToken"));
  173. return $response;
  174. }
  175. //批量删除文件
  176. public function delBatch($files){
  177. $url = $this->QINIU_RS_HOST . '/batch';
  178. $ops = array();
  179. foreach ($files as $file) {
  180. $ops[] = "/delete/". self::Qiniu_Encode("{$this->bucket}:{$file}");
  181. }
  182. $params = 'op=' . implode('&op=', $ops);
  183. $url .= '?'.$params;
  184. trace($url);
  185. $accessToken = $this->accessToken($url);
  186. $response = $this->request($url, 'POST', array('Authorization'=>"QBox $accessToken"));
  187. return $response;
  188. }
  189. static function Qiniu_Encode($str) {// URLSafeBase64Encode
  190. $find = array('+', '/');
  191. $replace = array('-', '_');
  192. return str_replace($find, $replace, base64_encode($str));
  193. }
  194. static function Qiniu_escapeQuotes($str){
  195. $find = array("\\", "\"");
  196. $replace = array("\\\\", "\\\"");
  197. return str_replace($find, $replace, $str);
  198. }
  199. /**
  200. * 请求百度云服务器
  201. * @param string $path 请求的PATH
  202. * @param string $method 请求方法
  203. * @param array $headers 请求header
  204. * @param resource $body 上传文件资源
  205. * @return boolean
  206. */
  207. private function request($path, $method, $headers = null, $body = null){
  208. $ch = curl_init($path);
  209. $_headers = array('Expect:');
  210. if (!is_null($headers) && is_array($headers)){
  211. foreach($headers as $k => $v) {
  212. array_push($_headers, "{$k}: {$v}");
  213. }
  214. }
  215. $length = 0;
  216. $date = gmdate('D, d M Y H:i:s \G\M\T');
  217. if (!is_null($body)) {
  218. if(is_resource($body)){
  219. fseek($body, 0, SEEK_END);
  220. $length = ftell($body);
  221. fseek($body, 0);
  222. array_push($_headers, "Content-Length: {$length}");
  223. curl_setopt($ch, CURLOPT_INFILE, $body);
  224. curl_setopt($ch, CURLOPT_INFILESIZE, $length);
  225. } else {
  226. $length = @strlen($body);
  227. array_push($_headers, "Content-Length: {$length}");
  228. curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  229. }
  230. } else {
  231. array_push($_headers, "Content-Length: {$length}");
  232. }
  233. // array_push($_headers, 'Authorization: ' . $this->sign($method, $uri, $date, $length));
  234. array_push($_headers, "Date: {$date}");
  235. curl_setopt($ch, CURLOPT_HTTPHEADER, $_headers);
  236. curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
  237. curl_setopt($ch, CURLOPT_HEADER, 1);
  238. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  239. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
  240. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
  241. if ($method == 'PUT' || $method == 'POST') {
  242. curl_setopt($ch, CURLOPT_POST, 1);
  243. } else {
  244. curl_setopt($ch, CURLOPT_POST, 0);
  245. }
  246. if ($method == 'HEAD') {
  247. curl_setopt($ch, CURLOPT_NOBODY, true);
  248. }
  249. $response = curl_exec($ch);
  250. $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  251. curl_close($ch);
  252. list($header, $body) = explode("\r\n\r\n", $response, 2);
  253. if ($status == 200) {
  254. if ($method == 'GET') {
  255. return $body;
  256. } else {
  257. return $this->response($response);
  258. }
  259. } else {
  260. $this->error($header , $body);
  261. return false;
  262. }
  263. }
  264. /**
  265. * 获取响应数据
  266. * @param string $text 响应头字符串
  267. * @return array 响应数据列表
  268. */
  269. private function response($text){
  270. $headers = explode(PHP_EOL, $text);
  271. $items = array();
  272. foreach($headers as $header) {
  273. $header = trim($header);
  274. if(strpos($header, '{') !== False){
  275. $items = json_decode($header, 1);
  276. break;
  277. }
  278. }
  279. return $items;
  280. }
  281. /**
  282. * 获取请求错误信息
  283. * @param string $header 请求返回头信息
  284. */
  285. private function error($header, $body) {
  286. list($status, $stash) = explode("\r\n", $header, 2);
  287. list($v, $code, $message) = explode(" ", $status, 3);
  288. $message = is_null($message) ? 'File Not Found' : "[{$status}]:{$message}]";
  289. $this->error = $message;
  290. $this->errorStr = json_decode($body ,1);
  291. $this->errorStr = $this->errorStr['error'];
  292. }
  293. }