QiniuStorage.class.php 12 KB

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