Completed
Push — master ( b4c21f...0af6cb )
by Bai
15s queued 10s
created

BucketManager::putReferAntiLeech()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 5
dl 0
loc 6
ccs 0
cts 1
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
namespace Qiniu\Storage;
3
4
use Qiniu\Auth;
5
use Qiniu\Config;
6
use Qiniu\Zone;
7
use Qiniu\Http\Client;
8
use Qiniu\Http\Error;
9
10
/**
11
 * 主要涉及了空间资源管理及批量操作接口的实现,具体的接口规格可以参考
12
 *
13
 * @link https://developer.qiniu.com/kodo/api/1274/rs
14
 */
15
final class BucketManager
16
{
17
    private $auth;
18
    private $config;
19
20 42
    public function __construct(Auth $auth, Config $config = null)
21
    {
22 42
        $this->auth = $auth;
23 42
        if ($config == null) {
24 42
            $this->config = new Config();
25 42
        } else {
26
            $this->config = $config;
27
        }
28 42
    }
29
30
    /**
31
     * 获取指定账号下所有的空间名。
32
     *
33
     * @return string[] 包含所有空间名
34
     */
35 3
    public function buckets($shared = true)
36
    {
37 3
        $includeShared = "false";
38 3
        if ($shared === true) {
39 3
            $includeShared = "true";
40 3
        }
41 3
        return $this->rsGet('/buckets?shared=' . $includeShared);
42
    }
43
44
    /**
45
     * 列举空间,返回bucket列表
46
     * region 指定区域,global 指定全局空间。
47
     * 在指定了 region 参数时,
48
     * 如果指定 global 为 true,那么忽略 region 参数指定的区域,返回所有区域的全局空间。
49
     * 如果没有指定 global 为 true,那么返回指定区域中非全局空间。
50
     * 在没有指定 region 参数时(包括指定为空""),
51
     * 如果指定 global 为 true,那么返回所有区域的全局空间。
52
     * 如果没有指定 global 为 true,那么返回指定区域中所有的空间,包括全局空间。
53
     * 在指定了line为 true 时,只返回 Line 空间;否则,只返回非 Line 空间。
54
     * share 参数用于指定共享空间。
55
     */
56
57
    public function listbuckets(
58
        $region = null,
59
        $line = 'false',
60
        $shared = 'false'
61
    ) {
62
        $path = '/v3/buckets?region=' . $region . '&line=' . $line . '&shared=' . $shared;
63
        $info = $this->ucPost($path);
64
        return $info;
65
    }
66
67
    /**
68
     * 创建空间
69
     *
70
     * @param $name     创建的空间名
71
     * @param $region    创建的区域,默认华东
72
     *
73
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
74
     */
75
    public function createBucket($name, $region = 'z0')
76
    {
77
        $path = '/mkbucketv3/'.$name.'/region/' . $region;
78
        return $this->rsPost($path, null);
79
    }
80
81
    /**
82
     * 删除空间
83
     *
84
     * @param $name     删除的空间名
85
     *
86
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
87
     */
88
    public function deleteBucket($name)
89
    {
90
        $path = '/drop/'.$name;
91
        return $this->rsPost($path, null);
92
    }
93
94
    /**
95
     * 获取指定空间绑定的所有的域名
96
     *
97
     * @return string[] 包含所有空间域名
98
     */
99
    public function domains($bucket)
100
    {
101
        return $this->apiGet('/v6/domain/list?tbl=' . $bucket);
102
    }
103
104
    /**
105
     * 获取指定空间的相关信息
106
     *
107
     * @return string[] 包含空间信息
108
     */
109
    public function bucketInfo($bucket)
110
    {
111
        $path = '/v2/bucketInfo?bucket=' . $bucket;
112
        $info = $this->ucPost($path);
113
        return $info;
114
    }
115
116
    /**
117
     * 获取指定zone的空间信息列表
118
     * 在Region 未指定且Global 不为 true 时(包含未指定的情况,下同),返回用户的所有空间。
119
     * 在指定了 region 参数且 global 不为 true 时,只列举非全局空间。
120
     * shared 不指定shared参数或指定shared为rw或false时,返回包含具有读写权限空间,
121
     * 指定shared为rd或true时,返回包含具有读权限空间。
122
     * fs:如果为 true,会返回每个空间当前的文件数和存储量(实时数据)。
123
     * @return string[] 包含空间信息
124
     */
125
    public function bucketInfos($region = null, $shared = 'false', $fs = 'false')
126
    {
127
        $path = '/v2/bucketInfos?region=' . $region . '&shared=' . $shared . '&fs=' . $fs;
128
        $info = $this->ucPost($path);
129
        return $info;
130
    }
131
132
    /**
133
     * 获取空间绑定的域名列表
134
     * @return string[] 包含空间绑定的所有域名
135
     */
136
137
    /**
138
     * 列取空间的文件列表
139
     *
140
     * @param $bucket     空间名
141
     * @param $prefix     列举前缀
142
     * @param $marker     列举标识符
143
     * @param $limit      单次列举个数限制
144
     * @param $delimiter  指定目录分隔符
145
     *
146
     * @return array    包含文件信息的数组,类似:[
147
*                                              {
148
*                                                 "hash" => "<Hash string>",
149
*                                                  "key" => "<Key string>",
150
*                                                  "fsize" => "<file size>",
151
*                                                  "putTime" => "<file modify time>"
152
*                                              },
153
*                                              ...
154
*                                            ]
155
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/list.html
156
     */
157 3
    public function listFiles(
158
        $bucket,
159
        $prefix = null,
160
        $marker = null,
161
        $limit = 1000,
162
        $delimiter = null
163
    ) {
164 3
        $query = array('bucket' => $bucket);
165 3
        \Qiniu\setWithoutEmpty($query, 'prefix', $prefix);
166 3
        \Qiniu\setWithoutEmpty($query, 'marker', $marker);
167 3
        \Qiniu\setWithoutEmpty($query, 'limit', $limit);
168 3
        \Qiniu\setWithoutEmpty($query, 'delimiter', $delimiter);
169 3
        $url = $this->getRsfHost() . '/list?' . http_build_query($query);
170 3
        return $this->get($url);
171
    }
172
173
    /**
174
     * 列取空间的文件列表
175
     *
176
     * @param $bucket     空间名
177
     * @param $prefix     列举前缀
178
     * @param $marker     列举标识符
179
     * @param $limit      单次列举个数限制
180
     * @param $delimiter  指定目录分隔符
181
     * @param $skipconfirm  是否跳过已删除条目的确认机制
182
     *
183
     * @return array    包含文件信息的数组,类似:[
184
*                                              {
185
*                                                 "hash" => "<Hash string>",
186
*                                                  "key" => "<Key string>",
187
*                                                  "fsize" => "<file size>",
188
*                                                  "putTime" => "<file modify time>"
189
*                                              },
190
*                                              ...
191
*                                            ]
192
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/list.html
193
     */
194
    public function listFilesv2(
195
        $bucket,
196
        $prefix = null,
197
        $marker = null,
198
        $limit = 1000,
199
        $delimiter = null,
200
        $skipconfirm = true
201
    ) {
202
        $query = array('bucket' => $bucket);
203
        \Qiniu\setWithoutEmpty($query, 'prefix', $prefix);
204
        \Qiniu\setWithoutEmpty($query, 'marker', $marker);
205
        \Qiniu\setWithoutEmpty($query, 'limit', $limit);
206
        \Qiniu\setWithoutEmpty($query, 'delimiter', $delimiter);
207
        \Qiniu\setWithoutEmpty($query, 'skipconfirm', $skipconfirm);
208
        $path = '/v2/list?' . http_build_query($query);
209
        $url = $this->getRsfHost() . $path;
210
        $headers = $this->auth->authorization($url, null, 'application/x-www-form-urlencoded');
211
        $ret = Client::post($url, null, $headers);
212
        if (!$ret->ok()) {
213
            return array(null, new Error($url, $ret));
214
        }
215
        $r = explode("\n", $ret->body);
216
        $pop = array_pop($r);
0 ignored issues
show
Unused Code introduced by
$pop is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
217
        return array($r, null);
218
    }
219
220
    /**
221
     * 设置Referer防盗链
222
     *
223
     * @param $bucket     空间名
224
     * @param $mode     0: 表示关闭Referer(使用此选项将会忽略以下参数并将恢复默认值);
225
     * 1: 表示设置Referer白名单; 2:表示设置Referer黑名单
226
     * @param $norefer     0: 表示不允许空 Refer 访问; 1: 表示允许空 Refer 访问
227
     * @param $pattern      规则字符串, 当前允许格式分为三种: 一种为空主机头域名,
228
     * 比如 foo.com; 一种是泛域名,比如 *.bar.com; 一种是完全通配符,
229
     * 即一个 *; 多个规则之间用;隔开, 比如: foo.com;*.bar.com;sub.foo.com;*.sub.bar.com
230
     * @param $source_enabled  源站是否支持,默认为0只给CDN配置, 设置为1表示开启源站防盗链
231
     *
232
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
233
     */
234
    // public function referAntiLeech(){
235
236
    // }
237
238
    /**
239
     * 增加bucket生命规则
240
     *
241
     * @param $bucket     空间名
242
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,只能为
243
     * 字母、数字、下划线
244
     * @param $prefix     同一个 bucket 里面前缀不能重复
245
     * @param $delete_after_days      指定上传文件多少天后删除,指定为0表示不删除,
246
     * 大于0表示多少天后删除,需大于 to_line_after_days
247
     * @param $to_line_after_days  指定文件上传多少天后转低频存储。指定为0表示
248
     * 不转低频存储,小于0表示上传的文件立即变低频存储
249
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
250
     */
251
    public function bucketLifecycleRule(
252
        $bucket,
253
        $name,
254
        $prefix,
255
        $delete_after_days,
256
        $to_line_after_days
257
    ) {
258
        $path = '/rules/add';
259
        if ($bucket) {
260
            $params['bucket'] = $bucket;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
261
        }
262
        if ($name) {
263
            $params['name'] = $name;
0 ignored issues
show
Bug introduced by
The variable $params does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
264
        }
265
        if ($prefix) {
266
            $params['prefix'] = $prefix;
267
        }
268
        if ($delete_after_days) {
269
            $params['delete_after_days'] = $delete_after_days;
270
        }
271
        if ($to_line_after_days) {
272
            $params['to_line_after_days'] = $to_line_after_days;
273
        }
274
        $data = http_build_query($params);
275
        $info = $this->ucPost($path, $data);
276
        return $info;
277
    }
278
279
    /**
280
     * 更新bucket生命规则
281
     *
282
     * @param $bucket     空间名
283
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,只能为字母、
284
     * 数字、下划线
285
     * @param $prefix     同一个 bucket 里面前缀不能重复
286
     * @param $delete_after_days      指定上传文件多少天后删除,指定为0表示不删除,
287
     * 大于0表示多少天后删除,需大于 to_line_after_days
288
     * @param $to_line_after_days  指定文件上传多少天后转低频存储。指定为0表示不
289
     * 转低频存储,小于0表示上传的文件立即变低频存储
290
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
291
     */
292
    public function updateBucketLifecycleRule(
293
        $bucket,
294
        $name,
295
        $prefix,
296
        $delete_after_days,
297
        $to_line_after_days
298
    ) {
299
        $path = '/rules/update';
300
        if ($bucket) {
301
            $params['bucket'] = $bucket;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
302
        }
303
        if ($name) {
304
            $params['name'] = $name;
0 ignored issues
show
Bug introduced by
The variable $params does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
305
        }
306
        if ($prefix) {
307
            $params['prefix'] = $prefix;
308
        }
309
        if ($delete_after_days) {
310
            $params['delete_after_days'] = $delete_after_days;
311
        }
312
        if ($to_line_after_days) {
313
            $params['to_line_after_days'] = $to_line_after_days;
314
        }
315
        $data = http_build_query($params);
316
        $info = $this->ucPost($path, $data);
317
        return $info;
318
    }
319
320
    /**
321
     * 获取bucket生命规则
322
     *
323
     * @param $bucket     空间名
324
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
325
     */
326
    public function getBucketLifecycleRules($bucket)
327
    {
328
        $path = '/rules/get?bucket=' . $bucket;
329
        $info = $this->ucGet($path);
330
        return $info;
331
    }
332
333
    /**
334
     * 删除bucket生命规则
335
     *
336
     * @param $bucket     空间名
337
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,
338
     * 只能为字母、数字、下划线()
339
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
340
     */
341
    public function deleteBucketLifecycleRule($bucket, $name)
342
    {
343
        $path = '/rules/delete';
344
        if ($bucket) {
345
            $params['bucket'] = $bucket;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
346
        }
347
        if ($name) {
348
            $params['name'] = $name;
0 ignored issues
show
Bug introduced by
The variable $params does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
349
        }
350
        $data = http_build_query($params);
351
        $info = $this->ucPost($path, $data);
352
        return $info;
353
    }
354
355
    /**
356
     * 增加bucket事件通知规则
357
     *
358
     * @param $bucket     空间名
359
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,
360
     * 只能为字母、数字、下划线()
361
     * @param $prefix     同一个 bucket 里面前缀不能重复
362
     * @param $suffix      可选,文件配置的后缀
363
     * @param $event  事件类型,可以指定多个,包括 put,mkfile,delete,copy,move,append,
364
     * disable,enable,deleteMarkerCreate
365
     * @param $callbackURL 通知URL,可以指定多个,失败依次重试
366
     * @param $access_key 可选,设置的话会对通知请求用对应的ak、sk进行签名
367
     * @param $host 可选,通知请求的host
368
     *
369
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
370
     */
371
    public function putBucketEvent(
372
        $bucket,
373
        $name,
374
        $prefix,
375
        $suffix,
376
        $event,
377
        $callbackURL,
378
        $access_key = null,
379
        $host = null
380
    ) {
381
        $path = '/events/add';
382
        if ($bucket) {
383
            $params['bucket'] = $bucket;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
384
        }
385
        if ($name) {
386
            $params['name'] = $name;
0 ignored issues
show
Bug introduced by
The variable $params does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
387
        }
388
        if ($prefix) {
389
            $params['prefix'] = $prefix;
390
        }
391
        if ($suffix) {
392
            $params['suffix'] = $suffix;
393
        }
394
        if ($callbackURL) {
395
            $params['callbackURL'] = $callbackURL;
396
        }
397
        if ($access_key) {
398
            $params['access_key'] = $access_key;
399
        }
400
        if ($host) {
401
            $params['host'] = $host;
402
        }
403
        $data = http_build_query($params);
404
        if ($event) {
405
            $eventpath = "";
406
            foreach ($event as $key => $value) {
407
                $eventpath .= "&event=$value";
408
            }
409
            $data .= $eventpath;
410
        }
411
        $info = $this->ucPost($path, $data);
412
        return $info;
413
    }
414
415
    /**
416
     * 更新bucket事件通知规则
417
     *
418
     * @param $bucket     空间名
419
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,
420
     * 只能为字母、数字、下划线()
421
     * @param $prefix     同一个 bucket 里面前缀不能重复
422
     * @param $suffix      可选,文件配置的后缀
423
     * @param $event  事件类型,可以指定多个,包括 put,mkfile,delete,copy,move,append,disable,
424
     * enable,deleteMarkerCreate
425
     * @param $callbackURL 通知URL,可以指定多个,失败依次重试
426
     * @param $access_key 可选,设置的话会对通知请求用对应的ak、sk进行签名
427
     * @param $host 可选,通知请求的host
428
     *
429
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
430
     */
431
    public function updateBucketEvent(
432
        $bucket,
433
        $name,
434
        $prefix,
435
        $suffix,
436
        $event,
437
        $callbackURL,
438
        $access_key = null,
439
        $host = null
440
    ) {
441
        $path = '/events/update';
442
        if ($bucket) {
443
            $params['bucket'] = $bucket;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
444
        }
445
        if ($name) {
446
            $params['name'] = $name;
0 ignored issues
show
Bug introduced by
The variable $params does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
447
        }
448
        if ($prefix) {
449
            $params['prefix'] = $prefix;
450
        }
451
        if ($suffix) {
452
            $params['suffix'] = $suffix;
453
        }
454
        if ($event) {
455
            $params['event'] = $event;
456
        }
457
        if ($callbackURL) {
458
            $params['callbackURL'] = $callbackURL;
459
        }
460
        if ($access_key) {
461
            $params['access_key'] = $access_key;
462
        }
463
        if ($host) {
464
            $params['host'] = $host;
465
        }
466
        $data = http_build_query($params);
467
        if ($event) {
468
            $eventpath = "";
469
            foreach ($event as $key => $value) {
470
                $eventpath .= "&event=$value";
471
            }
472
            $data .= $eventpath;
473
        }
474
        $info = $this->ucPost($path, $data);
475
        return $info;
476
    }
477
478
    /**
479
     * 获取bucket事件通知规则
480
     *
481
     * @param $bucket     空间名
482
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
483
     */
484
    public function getBucketEvents($bucket)
485
    {
486
        $path = '/events/get?bucket=' . $bucket;
487
        $info = $this->ucGet($path);
488
        return $info;
489
    }
490
491
    /**
492
     * 删除bucket事件通知规则
493
     *
494
     * @param $bucket     空间名
495
     * @param $name     规则名称 bucket 内唯一,长度小于50,不能为空,
496
     * 只能为字母、数字、下划线
497
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
498
     */
499
    public function deleteBucketEvent($bucket, $name)
500
    {
501
        $path = '/events/delete';
502
        if ($bucket) {
503
            $params['bucket'] = $bucket;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
504
        }
505
        if ($name) {
506
            $params['name'] = $name;
0 ignored issues
show
Bug introduced by
The variable $params does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
507
        }
508
        $data = http_build_query($params);
509
        $info = $this->ucPost($path, $data);
510
        return $info;
511
    }
512
513
    /**
514
     * 设置bucket的跨域信息,最多允许设置10条跨域规则。
515
     * 对于同一个域名如果设置了多条规则,那么按顺序使用第一条匹配的规则去生成返回值。
516
     * 对于简单跨域请求,只匹配 Origin;
517
     * allowed_orgin: 允许的域名。必填;支持通配符*;*表示全部匹配;只有第一个*生效;
518
     * 需要设置"Scheme";大小写敏感。例如
519
     * 规则:http://*.abc.*.com 请求:"http://test.abc.test.com" 结果:不通过
520
     * 规则:"http://abc.com" 请求:"https://abc.com"/"abc.com" 结果:不通过
521
     * 规则:"abc.com" 请求:"http://abc.com" 结果:不通过
522
     * allowed_method: 允许的方法。必填;不支持通配符;大小写不敏感;
523
     * allowed_header: 允许的header。选填;支持通配符*,
524
     * 但只能是单独的*,表示允许全部header,其他*不生效;
525
     * 空则不允许任何header;大小写不敏感;
526
     * exposed_header: 暴露的header。选填;不支持通配符;
527
     * X-Log, X-Reqid是默认会暴露的两个header;
528
     * 其他的header如果没有设置,则不会暴露;大小写不敏感;
529
     * max_age: 结果可以缓存的时间。选填;空则不缓存;
530
     * allowed_credentials:该配置不支持设置,默认为true。
531
     * 备注:如果没有设置任何corsRules,那么默认允许所有的跨域请求
532
     */
533
    // public function putCorsRules(string $bucket, array $params)
534
    // {
535
    //     $path = '/corsRules/set/' . $bucket;
536
    //     $data = json_encode($params);
537
    //     $info = $this->ucPost($path, $data);
538
    //     return $info;
539
    // }
540
541
    /**
542
     * 获取bucket的跨域信息
543
     * $bucket 空间名
544
     */
545
    public function getCorsRules($bucket)
546
    {
547
        $path = '/corsRules/get/' . $bucket;
548
        $info = $this->ucGet($path);
549
        return $info;
550
    }
551
552
    /**
553
     * 设置回源规则
554
     * 使用该API设置源站优先级高于/image设置的源站,即IO优先读取source接口设置的源站配置,
555
     * 如果存在会忽略/image设置的源站
556
     * Bucket 空间名
557
     * Host(可选)回源Host
558
     * RetryCodes(可选),镜像回源时源站返回Code可以重试,最多指定3个,当前只支持4xx错误码重试
559
     * SourceQiniuAK,SourceQiniuSK(可选)如果存在将在回源时对URL进行签名,客户源站可以验证
560
     * 以保证请求来自Qiniu服务器
561
     * Expires(可选) 签名过期时间,如果不设置默认为1小时
562
     * Addr 回源地址,不可重复。
563
     * Weight 权重,范围限制1-100,不填默认为1,回源时会根据所有源的权重值进行源站选择,
564
     * 主备源会分开计算.
565
     * Backup 是否备用回源,回源优先尝试主源
566
     */
567
    // public function putBucktSourceConfig(array $params)
568
    // {
569
    //     $path = '/mirrorConfig/set';
570
    //     $data = json_encode($params);
571
    //     $info = $this->ucPostV2($path, $data);
572
    //     return $info;
573
    // }
574
575
    /**
576
     * 获取空间回源配置
577
     */
578
    public function getBucktSourceConfig(array $params)
579
    {
580
        $path = '/mirrorConfig/get';
581
        $data = json_encode($params);
582
        $info = $this->ucPostV2($path, $data);
583
        return $info;
584
    }
585
586
    /**
587
     * 开关原图保护
588
     * mode 为1表示开启原图保护,0表示关闭
589
     */
590
    public function putBucketAccessStyleMode($bucket, $mode)
591
    {
592
        $path = '/accessMode/' . $bucket . '/mode/' . $mode;
593
        $info = $this->ucPost($path, null);
594
        return $info;
595
    }
596
597
    /**
598
     * 设置私有属性
599
     * private为0表示公开,为1表示私有
600
     */
601
    public function putBucketAccessMode($bucket, $private)
602
    {
603
        $path = "/private?bucket=$bucket&private=$private";
604
        $info = $this->ucPost($path, null);
605
        return $info;
606
    }
607
608
    /**
609
     * 设置referer防盗链
610
     * bucket=<BucketName>: bucket 名
611
     * mode=<AntiLeechMode>:
612
     * 0: 表示关闭Referer(使用此选项将会忽略以下参数并将恢复默认值);
613
     * 1: 表示设置Referer白名单; 2: 表示设置Referer黑名单
614
     * norefer=<NoRefer>: 0: 表示不允许空 Refer 访问;
615
     * 1: 表示允许空 Refer 访问
616
     * pattern=<Pattern>: 规则字符串, 当前允许格式分为三种:
617
     * 一种为空主机头域名, 比如 foo.com;
618
     * 一种是泛域名, 比如 *.bar.com; 一种是完全通配符, 即一个 *;
619
     * 多个规则之间用;隔开, 比如: foo.com;*.bar.com;sub.foo.com;*.sub.bar.com
620
     * 空主机头域名可以是多级域名,比如 foo.bar.com。
621
     * 多个域名之间不允许夹带空白字符。
622
     * source_enabled=:1
623
     */
624
    public function putReferAntiLeech($bucket, $mode, $norefer, $pattern, $enabled = 1)
625
    {
626
        $path = "/referAntiLeech?bucket=$bucket&mode=$mode&norefer=$norefer&pattern=$pattern&source_enabled=$enabled";
627
        $info = $this->ucPost($path, null);
628
        return $info;
629
    }
630
631
    /**
632
     * 设置Bucket的maxAge
633
     * maxAge为0或者负数表示为默认值(31536000)
634
     */
635
    public function putBucketMaxAge($bucket, $maxAge)
636
    {
637
        $path = '/maxAge?bucket=' . $bucket . '&maxAge=' . $maxAge;
638
        $info = $this->ucPost($path, null);
639
        return $info;
640
    }
641
642
    /**
643
     * 设置配额
644
     * <bucket>: 空间名称,不支持授权空间
645
     * <size>: 空间存储量配额,参数传入0或不传表示不更改当前配置,传入-1表示取消限额,
646
     * 新创建的空间默认没有限额。
647
     * <count>: 空间文件数配额,参数含义同<size>
648
     */
649
    public function putBucketQuota($bucket, $size, $count)
650
    {
651
        $path = '/setbucketquota/' . $bucket . '/size/' . $size . '/count/' . $count;
652
        $info = $this->apiPost($path, null);
653
        return $info;
654
    }
655
656
    /**
657
     * 获取配额
658
     * bucket 空间名称
659
     */
660
    public function getBucketQuota($bucket)
661
    {
662
        $path = '/getbucketquota/' . $bucket;
663
        $info = $this->apiPost($path, null);
664
        return $info;
665
    }
666
667
    /**
668
     * 获取资源的元信息,但不返回文件内容
669
     *
670
     * @param $bucket     待获取信息资源所在的空间
671
     * @param $key        待获取资源的文件名
672
     *
673
     * @return array    包含文件信息的数组,类似:
674
*                                              [
675
*                                                  "hash" => "<Hash string>",
676
*                                                  "key" => "<Key string>",
677 6
*                                                  "fsize" => <file size>,
678
*                                                  "putTime" => "<file modify time>"
679 6
*                                                  "fileType" => <file type>
680 6
*                                              ]
681
     *
682
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/stat.html
683
     */
684
    public function stat($bucket, $key)
685
    {
686
        $path = '/stat/' . \Qiniu\entry($bucket, $key);
687
        return $this->rsGet($path);
688
    }
689
690
    /**
691
     * 删除指定资源
692 15
     *
693
     * @param $bucket     待删除资源所在的空间
694 15
     * @param $key        待删除资源的文件名
695 15
     *
696 15
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
697
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/delete.html
698
     */
699
    public function delete($bucket, $key)
700
    {
701
        $path = '/delete/' . \Qiniu\entry($bucket, $key);
702
        list(, $error) = $this->rsPost($path);
703
        return $error;
704
    }
705
706
707
    /**
708
     * 给资源进行重命名,本质为move操作。
709 3
     *
710
     * @param $bucket     待操作资源所在空间
711 3
     * @param $oldname    待操作资源文件名
712
     * @param $newname    目标资源文件名
713
     *
714
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
715
     */
716
    public function rename($bucket, $oldname, $newname)
717
    {
718
        return $this->move($bucket, $oldname, $bucket, $newname);
719
    }
720
721
    /**
722
     * 对资源进行复制。
723
     *
724
     * @param $from_bucket     待操作资源所在空间
725 15
     * @param $from_key        待操作资源文件名
726
     * @param $to_bucket       目标资源空间名
727 15
     * @param $to_key          目标资源文件名
728 15
     *
729 15
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
730 15
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/copy.html
731 3
     */
732 3
    public function copy($from_bucket, $from_key, $to_bucket, $to_key, $force = false)
733 15
    {
734 15
        $from = \Qiniu\entry($from_bucket, $from_key);
735
        $to = \Qiniu\entry($to_bucket, $to_key);
736
        $path = '/copy/' . $from . '/' . $to;
737
        if ($force === true) {
738
            $path .= '/force/true';
739
        }
740
        list(, $error) = $this->rsPost($path);
741
        return $error;
742
    }
743
744
    /**
745
     * 将资源从一个空间到另一个空间
746
     *
747
     * @param $from_bucket     待操作资源所在空间
748 3
     * @param $from_key        待操作资源文件名
749
     * @param $to_bucket       目标资源空间名
750 3
     * @param $to_key          目标资源文件名
751 3
     *
752 3
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
753 3
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/move.html
754
     */
755
    public function move($from_bucket, $from_key, $to_bucket, $to_key, $force = false)
756 3
    {
757 3
        $from = \Qiniu\entry($from_bucket, $from_key);
758
        $to = \Qiniu\entry($to_bucket, $to_key);
759
        $path = '/move/' . $from . '/' . $to;
760
        if ($force) {
761
            $path .= '/force/true';
762
        }
763
        list(, $error) = $this->rsPost($path);
764
        return $error;
765
    }
766
767
    /**
768
     * 主动修改指定资源的文件元信息
769
     *
770 3
     * @param $bucket     待操作资源所在空间
771
     * @param $key        待操作资源文件名
772 3
     * @param $mime       待操作文件目标mimeType
773 3
     *
774 3
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
775 3
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/chgm.html
776 3
     */
777
    public function changeMime($bucket, $key, $mime)
778
    {
779
        $resource = \Qiniu\entry($bucket, $key);
780
        $encode_mime = \Qiniu\base64_urlSafeEncode($mime);
781
        $path = '/chgm/' . $resource . '/mime/' . $encode_mime;
782
        list(, $error) = $this->rsPost($path);
783
        return $error;
784
    }
785
786
787
    /**
788
     * 修改指定资源的存储类型
789
     *
790
     * @param $bucket     待操作资源所在空间
791
     * @param $key        待操作资源文件名
792
     * @param $fileType       待操作文件目标文件类型
793
     *
794
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
795
     * @link  https://developer.qiniu.com/kodo/api/3710/modify-the-file-type
796
     */
797
    public function changeType($bucket, $key, $fileType)
798
    {
799
        $resource = \Qiniu\entry($bucket, $key);
800
        $path = '/chtype/' . $resource . '/type/' . $fileType;
801
        list(, $error) = $this->rsPost($path);
802
        return $error;
803
    }
804
805
    /**
806
     * 修改文件的存储状态,即禁用状态和启用状态间的的互相转换
807
     *
808
     * @param $bucket     待操作资源所在空间
809
     * @param $key        待操作资源文件名
810
     * @param $status       待操作文件目标文件类型
811
     *
812
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
813
     * @link  https://developer.qiniu.com/kodo/api/4173/modify-the-file-status
814
     */
815
    public function changeStatus($bucket, $key, $status)
816
    {
817
        $resource = \Qiniu\entry($bucket, $key);
818
        $path = '/chstatus/' . $resource . '/status/' . $status;
819
        list(, $error) = $this->rsPost($path);
820
        return $error;
821
    }
822
823
    /**
824
     * 从指定URL抓取资源,并将该资源存储到指定空间中
825
     *
826
     * @param $url        指定的URL
827
     * @param $bucket     目标资源空间
828
     * @param $key        目标资源文件名
829
     *
830
     * @return array    包含已拉取的文件信息。
831
     *                         成功时:  [
832
     *                                          [
833
     *                                              "hash" => "<Hash string>",
834
     *                                              "key" => "<Key string>"
835
     *                                          ],
836
     *                                          null
837
     *                                  ]
838 3
     *
839
     *                         失败时:  [
840
     *                                          null,
841 3
     *                                         Qiniu/Http/Error
842 3
     *                                  ]
843 3
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/fetch.html
844
     */
845 3
    public function fetch($url, $bucket, $key = null)
846 3
    {
847
848 3
        $resource = \Qiniu\base64_urlSafeEncode($url);
849 3
        $to = \Qiniu\entry($bucket, $key);
850
        $path = '/fetch/' . $resource . '/to/' . $to;
851
852
        $ak = $this->auth->getAccessKey();
853
        $ioHost = $this->config->getIovipHost($ak, $bucket);
854
855
        $url = $ioHost . $path;
856
        return $this->post($url, null);
857
    }
858
859
    /**
860
     * 从指定URL异步抓取资源,并将该资源存储到指定空间中
861 3
     *
862
     * @param $url                       需要抓取的url
863 3
     * @param $bucket                    所在区域的bucket
864 3
     * @param null $host 从指定url下载数据时使用的Host
865
     * @param null $key 文件存储的key
866 3
     * @param null $md5 文件md5
867 3
     * @param null $etag 文件etag
868
     * @param null $callbackurl 回调URL
869 3
     * @param null $callbackbody 回调Body
870 3
     * @param string $callbackbodytype 回调Body内容类型,默认为"application/x-www-form-urlencoded"
871 3
     * @param null $callbackhost 回调时使用的Host
872
     * @param int $file_type 存储文件类型 0:标准存储(默认),1:低频存储,2:归档存储
873
     * @param bool $ignore_same_key 如果空间中已经存在同名文件则放弃本次抓取
874
     * @return array
875
     * @link  https://developer.qiniu.com/kodo/api/4097/asynch-fetch
876
     */
877
    public function asynchFetch(
878
        $url,
879
        $bucket,
880
        $host = null,
881
        $key = null,
882
        $md5 = null,
883
        $etag = null,
884
        $callbackurl = null,
885
        $callbackbody = null,
886
        $callbackbodytype = 'application/x-www-form-urlencoded',
887
        $callbackhost = null,
888
        $file_type = 0,
889
        $ignore_same_key = false
890 12
    ) {
891
        $path = '/sisyphus/fetch';
892 12
893 12
        $params = array('url' => $url, 'bucket' => $bucket);
894
        \Qiniu\setWithoutEmpty($params, 'host', $host);
895
        \Qiniu\setWithoutEmpty($params, 'key', $key);
896
        \Qiniu\setWithoutEmpty($params, 'md5', $md5);
897
        \Qiniu\setWithoutEmpty($params, 'etag', $etag);
898
        \Qiniu\setWithoutEmpty($params, 'callbackurl', $callbackurl);
899
        \Qiniu\setWithoutEmpty($params, 'callbackbody', $callbackbody);
900
        \Qiniu\setWithoutEmpty($params, 'callbackbodytype', $callbackbodytype);
901
        \Qiniu\setWithoutEmpty($params, 'callbackhost', $callbackhost);
902
        \Qiniu\setWithoutEmpty($params, 'file_type', $file_type);
903
        \Qiniu\setWithoutEmpty($params, 'ignore_same_key', $ignore_same_key);
904
        $data = json_encode($params);
905
906 3
        $ak = $this->auth->getAccessKey();
907
        $apiHost = $this->config->getApiHost($ak, $bucket);
908 3
        $url = $apiHost . $path;
909 3
910 3
        return $this->postV2($url, $data);
911 3
    }
912
913
914 3
    /**
915
     * 查询异步第三方资源抓取任务状态
916 3
     *
917 3
     * @param $zone
918
     * @param $id
919
     * @return array
920 3
     * @link  https://developer.qiniu.com/kodo/api/4097/asynch-fetch
921
     */
922
    public function asynchFetchStatus($zone, $id)
923 33
    {
924
        $scheme = "http://";
925 33
926 33
        if ($this->config->useHTTPS === true) {
927
            $scheme = "https://";
928
        }
929 33
930
        $url = $scheme . "api-" . $zone . ".qiniu.com/sisyphus/fetch?id=" . $id;
931
932
        $response = $this->getV2($url);
933
934
        if (!$response->ok()) {
935
            print("statusCode: " . $response->statusCode);
936
            return array(null, new Error($url, $response));
937
        }
938
        return array($response->json(), null);
939
    }
940
941
942
    /**
943
     * 从镜像源站抓取资源到空间中,如果空间中已经存在,则覆盖该资源
944
     *
945
     * @param $bucket     待获取资源所在的空间
946
     * @param $key        代获取资源文件名
947
     *
948
     * @return mixed      成功返回NULL,失败返回对象Qiniu\Http\Error
949
     * @link  http://developer.qiniu.com/docs/v6/api/reference/rs/prefetch.html
950 27
     */
951
    public function prefetch($bucket, $key)
952 27
    {
953 27
        $resource = \Qiniu\entry($bucket, $key);
954
        $path = '/prefetch/' . $resource;
955
956
        $ak = $this->auth->getAccessKey();
957
        $ioHost = $this->config->getIovipHost($ak, $bucket);
958
959
        $url = $ioHost . $path;
960
        list(, $error) = $this->post($url, null);
961
        return $error;
962
    }
963
964
    /**
965
     * 在单次请求中进行多个资源管理操作
966
     *
967
     * @param $operations     资源管理操作数组
968
     *
969
     * @return array 每个资源的处理情况,结果类似:
970
     *              [
971
     *                   { "code" => <HttpCode int>, "data" => <Data> },
972
     *                   { "code" => <HttpCode int> },
973
     *                   { "code" => <HttpCode int> },
974
     *                   { "code" => <HttpCode int> },
975
     *                   { "code" => <HttpCode int>, "data" => { "error": "<ErrorMessage string>" } },
976
     *                   ...
977
     *               ]
978
     * @link http://developer.qiniu.com/docs/v6/api/reference/rs/batch.html
979
     */
980 9
    public function batch($operations)
981
    {
982 9
        $params = 'op=' . implode('&op=', $operations);
983 9
        return $this->rsPost('/batch', $params);
984
    }
985
986 12
    /**
987
     * 设置文件的生命周期
988 12
     *
989 12
     * @param $bucket 设置文件生命周期文件所在的空间
990 12
     * @param $key    设置文件生命周期文件的文件名
991 6
     * @param $days   设置该文件多少天后删除,当$days设置为0时表示取消该文件的生命周期
992
     *
993 12
     * @return Mixed
994
     * @link https://developer.qiniu.com/kodo/api/update-file-lifecycle
995
     */
996 33
    public function deleteAfterDays($bucket, $key, $days)
997
    {
998 33
        $entry = \Qiniu\entry($bucket, $key);
999 33
        $path = "/deleteAfterDays/$entry/$days";
1000 33
        list(, $error) = $this->rsPost($path);
1001 9
        return $error;
1002
    }
1003 30
1004 30
    private function getRsfHost()
1005
    {
1006
        $scheme = "http://";
1007
        if ($this->config->useHTTPS == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1008
            $scheme = "https://";
1009
        }
1010
        return $scheme . Config::RSF_HOST;
1011
    }
1012
1013
    private function getRsHost()
1014
    {
1015
        $scheme = "http://";
1016
        if ($this->config->useHTTPS == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1017
            $scheme = "https://";
1018
        }
1019
        return $scheme . Config::RS_HOST;
1020
    }
1021
1022
    private function getApiHost()
1023
    {
1024
        $scheme = "http://";
1025 3
        if ($this->config->useHTTPS == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1026
            $scheme = "https://";
1027 3
        }
1028
        return $scheme . Config::API_HOST;
1029
    }
1030
1031 3
    private function getUcHost()
1032
    {
1033 3
        $scheme = "http://";
1034
        if ($this->config->useHTTPS == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1035
            $scheme = "https://";
1036
        }
1037 6
        return $scheme . Config::UC_HOST;
1038
    }
1039 6
1040
    private function rsPost($path, $body = null)
1041
    {
1042
        $url = $this->getRsHost() . $path;
1043 3
        return $this->post($url, $body);
1044
    }
1045 3
1046
    private function apiPost($path, $body = null)
1047
    {
1048
        $url = $this->getApiHost() . $path;
1049 3
        return $this->post($url, $body);
1050
    }
1051 3
1052
    private function ucPost($path, $body = null)
1053
    {
1054
        $url = $this->getUcHost() . $path;
1055
        return $this->post($url, $body);
1056
    }
1057
1058
    private function ucGet($path)
1059
    {
1060
        $url = $this->getUcHost() . $path;
1061
        return $this->get($url);
1062
    }
1063
1064
    private function apiGet($path)
1065
    {
1066
        $url = $this->getApiHost() . $path;
1067
        return $this->get($url);
1068
    }
1069
1070
    private function rsGet($path)
1071
    {
1072
        $url = $this->getRsHost() . $path;
1073
        return $this->get($url);
1074
    }
1075
1076
    private function get($url)
1077
    {
1078
        $headers = $this->auth->authorization($url);
1079
        $ret = Client::get($url, $headers);
1080
        if (!$ret->ok()) {
1081 6
            return array(null, new Error($url, $ret));
1082
        }
1083 6
        return array($ret->json(), null);
1084 6
    }
1085 6
1086 6
    private function getV2($url)
1087 6
    {
1088
        $headers = $this->auth->authorizationV2($url, 'GET');
1089
        return Client::get($url, $headers);
1090 9
    }
1091
1092 9
    private function post($url, $body)
1093
    {
1094
        $headers = $this->auth->authorization($url, $body, 'application/x-www-form-urlencoded');
1095 9
        $ret = Client::post($url, $body, $headers);
1096 9
        if (!$ret->ok()) {
1097 9
            return array(null, new Error($url, $ret));
1098 9
        }
1099 9
        $r = ($ret->body === null) ? array() : $ret->json();
1100 9
        return array($r, null);
1101 9
    }
1102 9
1103 9
    private function ucPostV2($path, $body)
1104 9
    {
1105 9
        $url = $this->getUcHost() . $path;
1106
        return $this->postV2($url, $body);
1107
    }
1108
1109
    private function postV2($url, $body)
1110
    {
1111
        $headers = $this->auth->authorizationV2($url, 'POST', $body, 'application/json');
1112
        $headers["Content-Type"] = 'application/json';
1113
        $ret = Client::post($url, $body, $headers);
1114
        if (!$ret->ok()) {
1115
            return array(null, new Error($url, $ret));
1116
        }
1117
        $r = ($ret->body === null) ? array() : $ret->json();
1118
        return array($r, null);
1119
    }
1120
1121
    public static function buildBatchCopy($source_bucket, $key_pairs, $target_bucket, $force)
1122
    {
1123
        return self::twoKeyBatch('/copy', $source_bucket, $key_pairs, $target_bucket, $force);
1124
    }
1125
1126
1127
    public static function buildBatchRename($bucket, $key_pairs, $force)
1128
    {
1129
        return self::buildBatchMove($bucket, $key_pairs, $bucket, $force);
1130
    }
1131
1132
1133
    public static function buildBatchMove($source_bucket, $key_pairs, $target_bucket, $force)
1134
    {
1135
        return self::twoKeyBatch('/move', $source_bucket, $key_pairs, $target_bucket, $force);
1136
    }
1137
1138
1139
    public static function buildBatchDelete($bucket, $keys)
1140
    {
1141
        return self::oneKeyBatch('/delete', $bucket, $keys);
1142
    }
1143
1144
1145
    public static function buildBatchStat($bucket, $keys)
1146
    {
1147
        return self::oneKeyBatch('/stat', $bucket, $keys);
1148
    }
1149
1150
    public static function buildBatchDeleteAfterDays($bucket, $key_day_pairs)
1151
    {
1152
        $data = array();
1153
        foreach ($key_day_pairs as $key => $day) {
1154
            array_push($data, '/deleteAfterDays/' . \Qiniu\entry($bucket, $key) . '/' . $day);
1155
        }
1156
        return $data;
1157
    }
1158
1159
    public static function buildBatchChangeMime($bucket, $key_mime_pairs)
1160
    {
1161
        $data = array();
1162
        foreach ($key_mime_pairs as $key => $mime) {
1163
            array_push($data, '/chgm/' . \Qiniu\entry($bucket, $key) . '/mime/' . base64_encode($mime));
1164
        }
1165
        return $data;
1166
    }
1167
1168
    public static function buildBatchChangeType($bucket, $key_type_pairs)
1169
    {
1170
        $data = array();
1171
        foreach ($key_type_pairs as $key => $type) {
1172
            array_push($data, '/chtype/' . \Qiniu\entry($bucket, $key) . '/type/' . $type);
1173
        }
1174
        return $data;
1175
    }
1176
1177
    private static function oneKeyBatch($operation, $bucket, $keys)
1178
    {
1179
        $data = array();
1180
        foreach ($keys as $key) {
1181
            array_push($data, $operation . '/' . \Qiniu\entry($bucket, $key));
1182
        }
1183
        return $data;
1184
    }
1185
1186
    private static function twoKeyBatch($operation, $source_bucket, $key_pairs, $target_bucket, $force)
1187
    {
1188
        if ($target_bucket === null) {
1189
            $target_bucket = $source_bucket;
1190
        }
1191
        $data = array();
1192
        $forceOp = "false";
1193
        if ($force) {
1194
            $forceOp = "true";
1195
        }
1196
        foreach ($key_pairs as $from_key => $to_key) {
1197
            $from = \Qiniu\entry($source_bucket, $from_key);
1198
            $to = \Qiniu\entry($target_bucket, $to_key);
1199
            array_push($data, $operation . '/' . $from . '/' . $to . "/force/" . $forceOp);
1200
        }
1201
        return $data;
1202
    }
1203
}
1204