MediaApi::upload()   B
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 25
Code Lines 13

Duplication

Lines 25
Ratio 100 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 25
loc 25
rs 8.5806
cc 4
eloc 13
nc 3
nop 2
1
<?php
2
3
namespace Wechat\API;
4
5
use Wechat\Api;
6
7
/**
8
 * 媒体文件相关接口.
9
 *
10
 * @author Tian.
11
 */
12
class MediaApi extends BaseApi
13
{
14
    /**
15
     * 上传临时媒体文件.   $file 为  /logo/img.jpeg 服务器上图片路径
16
     *
17
     * @author Tian
18
     *
19
     * @date   2015-10-10
20
     *
21
     * @param string $file 文件路径
22
     * @param string $type 文件类型
23
     *
24
     * @return bool|array 接口返回结果
25
     */
26 View Code Duplication
    public function upload($file, $type)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
27
    {
28
        if (!$file || !$type) {
29
            $this->setError('参数缺失');
30
31
            return false;
32
        }
33
34
        if (!file_exists($file)) {
35
            $this->setError('文件路径不正确');
36
37
            return false;
38
        }
39
40
        $data          = [];
41
        $data['media'] = '@' . realpath($file);
42
43
        Api::setPostQueryStr('type', $type);
44
45
        $node = 'upload';
46
47
        $res = $this->_post($node, $data, false);
48
49
        return $res;
50
    }
51
52
    /**
53
     * 上传临时媒体文件.
54
     *
55
     * @author Tian
56
     *
57
     * @date   2015-08-02
58
     *
59
     * @param string $file 文件  为 form 表单的 $_FILES['xxx'];
60
     * @param string $type 文件类型
61
     *
62
     * @return bool|array 接口返回结果
63
     */
64
    public function uploadFrom($file, $type = 'image')
65
    {
66
        if (!$file || !$type) {
67
            $this->setError('参数缺失');
68
69
            return false;
70
        }
71
72
        $this->setPostQueryStr('type', $type);
73
74
        $name        = 'media'; // 设置上传文件键名 固定为media
75
        $filename    = $file['name']; // 设置上传文件名
76
        $filetype    = $file['type'];
77
        $filecontent = file_get_contents($file['tmp_name']); // 读取临时文件里 上传文件的信息
78
        $key         = "name=\"{$name}\"; filename=\"{$filename}\"\r\nContent-Type: {$filetype}\r\n"; // curl设置上传文件的一种方法.
79
80
        $param       = [];
81
        $param[$key] = $filecontent;
82
83
        $node = 'upload';
84
85
        $res = $this->_post($node, $param, false);
86
87
        return $res;
88
    }
89
90
    /**
91
     * 上传临时媒体文件. $url 为 http://itse.cc/img.jpeg
92
     *
93
     * @param        $url
94
     * @param string $type
95
     *
96
     * @return array|bool
97
     */
98
    public function uploadCurl($url, $type = 'image')
99
    {
100
        if (!$url || !$type) {
101
            $this->setError('参数缺失');
102
103
            return false;
104
        }
105
106
        $rest = self::curl_get($url);
107
108
        $file_tail = explode("/", $rest['type']);
109
110
        /* 判断是不是阿里云服务器 */
111 View Code Duplication
        if ($rest['header']['Server'] == 'AliyunOSS') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
112
            $imgType      = substr($url, strrpos($url, '.') + 1);
113
            $file_type    = $type . '/' . $imgType;
114
            $file_tail[1] = $imgType;
115
        } else {
116
            $file_type = $rest['type'];
117
        }
118
119
        $this->setPostQueryStr('type', $type);
120
121
        $name      = 'media'; // 设置上传文件键名 固定为media
122
        $file_name = md5(uniqid(rand(1000, 9999))) . '.' . $file_tail[1]; // 设置上传文件名
123
        $key       = "name=\"{$name}\"; filename=\"{$file_name}\"\r\nContent-Type: {$file_type}\r\n"; // curl设置上传文件的一种方法.
124
125
        $param       = [];
126
        $param[$key] = $rest['content'];
127
128
        $node = 'upload';
129
130
        $res = $this->_post($node, $param, false);
131
132
        return $res;
133
    }
134
135
    /**
136
     * 根据mediaID获取媒体文件.
137
     *
138
     * @author Tian
139
     *
140
     * @date   2015-10-10
141
     *
142
     * @param string $mediaId 由上传接口获取的媒体文件
143
     *
144
     * @return array 如果成功则返回 content是由base64编码过的文件内容 解码后为正常的文件内容.
145
     */
146
    public function get($mediaId)
147
    {
148
        $node     = 'get';
149
        $queryStr = ['media_id' => $mediaId];
150
151
        $res = $this->_get($node, $queryStr);
152
153
        return $res;
154
    }
155
156
    /**
157
     * 上传图文消息内的图片.
158
     *
159
     * @param  string $file 媒体文件路径 图片仅支持jpg/png格式,大小必须在1MB以下
160
     *
161
     * @return string.  获取地址  http://mmbiz.qpic.cn/mmbiz/NdxGKqW8jE9GbAqUEPdSgSvbUbProSmE8NbUFwIYnp0Duibs611ZsCLza6b2dS8Ex3CO5dtv0u1HP9QY32djCxA/0
0 ignored issues
show
Documentation introduced by
The doc-type string. could not be parsed: Unknown type name "string." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
162
     */
163 View Code Duplication
    public function uploadimg($file)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
164
    {
165
        if (!$file) {
166
            $this->setError('参数缺失');
167
168
            return false;
169
        }
170
171
        if (!file_exists($file)) {
172
            $this->setError('文件路径不正确');
173
174
            return false;
175
        }
176
177
        $data          = [];
178
        $data['media'] = '@' . realpath($file);
179
180
        $node = 'uploadimg';
181
182
        $res = $this->_post($node, $data, false);
183
184
        return $res;
185
    }
186
187
    /**
188
     * 上传图文消息内的视频.
189
     *
190
     * @param string $media_id    媒体Id
191
     * @param string $title       标题
192
     * @param string $description 描述
193
     *
194
     * @return bool|array.  "type":"video","media_id":"IhdaAQXuvJtGzwwc0abfXnzeezfO0NgPK6AQYShD8RQYMTtfzbLdBIQkQziv2XJc","created_at":1398848981
0 ignored issues
show
Documentation introduced by
The doc-type bool|array. could not be parsed: Unknown type name "array." at position 5. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
195
     */
196
    public function uploadvideo($media_id, $title, $description)
197
    {
198
        if (empty($media_id)) {
199
            $this->setError('参数缺失');
200
201
            return false;
202
        }
203
204
        $queryStr                = [];
205
        $queryStr['media_id']    = $media_id;
206
        $queryStr['title']       = $title;
207
        $queryStr['description'] = $description;
208
209
        $res = $this->_post('uploadvideo', $queryStr);
210
211
        return $res;
212
    }
213
214
    /**
215
     * 上传图文消息素材【订阅号与服务号认证后均可用】
216
     *
217
     * @param array $articles 图文消息,一个图文消息支持1到8条图文
218
     *
219
     * string $articles ->thumb_media_id          图文消息缩略图的media_id,可以在基础支持-上传多媒体文件接口中获得
220
     * string $articles ->author                  图文消息的作者
221
     * string $articles ->title                   图文消息的标题
222
     * utl    $articles ->content_source_url      在图文消息页面点击“阅读原文”后的页面
223
     * html   $articles ->content                 图文消息页面的内容,支持HTML标签。具备微信支付权限的公众号,可以使用a标签,其他公众号不能使用
224
     * string $articles ->digest                  图文消息的描述
225
     * int    $articles ->show_cover_pic          是否显示封面,1为显示,0为不显示
226
     *
227
     * @return bool|array
228
     */
229
    public function uploadnews($articles = [])
230
    {
231
        if (empty($articles) || !is_array($articles)) {
232
            $this->setError('参数缺失');
233
234
            return false;
235
        }
236
237
        $queryStr             = [];
238
        $queryStr['articles'] = $articles;
239
240
        $res = $this->_post('uploadnews', $queryStr);
241
242
        return $res;
243
    }
244
245
    /**
246
     * 上传卡券logo图片. $file 为 /logo/img.jpeg
247
     *
248
     * @param  string $file 媒体文件路径 图片仅支持jpg/png格式,大小必须在1MB以下
249
     *
250
     * @return string.  获取地址  http://mmbiz.qpic.cn/mmbiz/NdxGKqW8jE9GbAqUEPdSgSvbUbProSmE8NbUFwIYnp0Duibs611ZsCLza6b2dS8Ex3CO5dtv0u1HP9QY32djCxA/0
0 ignored issues
show
Documentation introduced by
The doc-type string. could not be parsed: Unknown type name "string." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
251
     */
252 View Code Duplication
    public function cardUploadimg($file)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
253
    {
254
        if (!$file) {
255
            $this->setError('参数缺失');
256
257
            return false;
258
        }
259
260
        if (!file_exists($file)) {
261
            $this->setError('文件路径不正确');
262
263
            return false;
264
        }
265
266
        $data           = [];
267
        $data['buffer'] = '@' . realpath($file);
268
269
        $node = 'uploadimg';
270
271
        $res = $this->_post($node, $data, false);
272
273
        return $res;
274
    }
275
276
    /**
277
     * 上传卡券logo图片. $file为 $_FILES['xxx'];
278
     *
279
     * @param  string $file 文件
280
     *
281
     * @return string.  获取地址  http://mmbiz.qpic.cn/mmbiz/NdxGKqW8jE9GbAqUEPdSgSvbUbProSmE8NbUFwIYnp0Duibs611ZsCLza6b2dS8Ex3CO5dtv0u1HP9QY32djCxA/0
0 ignored issues
show
Documentation introduced by
The doc-type string. could not be parsed: Unknown type name "string." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
282
     */
283
    public function cardUpload_img($file)
284
    {
285
        if (!$file) {
286
            $this->setError('参数缺失');
287
288
            return false;
289
        }
290
291
        $node = 'uploadimg';
292
293
        $name        = 'media'; // 设置上传文件键名 固定为media
294
        $filename    = $file['name']; // 设置上传文件名
295
        $filetype    = $file['type'];
296
        $filecontent = file_get_contents($file['tmp_name']); // 读取临时文件里 上传文件的信息
297
        $key         = "name=\"{$name}\"; filename=\"{$filename}\"\r\nContent-Type: {$filetype}\r\n"; // curl设置上传文件的一种方法.
298
299
        $param       = [];
300
        $param[$key] = $filecontent;
301
302
        $res = $this->_post($node, $param, false);
303
304
        return $res;
305
    }
306
307
    /**
308
     * 上传卡券logo图片. $url 为 http://itse.cc/img.jpeg
309
     *
310
     * @param $url
311
     *
312
     * @return array|bool
313
     */
314
    function curlCardUpload_img($url)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
315
    {
316
        $node = 'uploadimg';
317
318
        $rest      = self::curl_get($url);
319
        $file_tail = explode("/", $rest['type']);
320
321
        /* 判断是不是阿里云服务器 */
322 View Code Duplication
        if ($rest['header']['Server'] == 'AliyunOSS') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
323
            $imgType      = substr($url, strrpos($url, '.') + 1);
324
            $file_type    = 'image/' . $imgType;
325
            $file_tail[1] = $imgType;
326
        } else {
327
            $file_type = $rest['type'];
328
        }
329
330
        $name      = 'media';
331
        $file_name = md5(uniqid(rand(1000, 9999))) . '.' . $file_tail[1]; // 设置上传文件名
332
        $imgSize   = $rest['size'];
333
        //1M = 1048576字节 微信允许上传的最大文件
334
        if ($imgSize >= 1048576) {
335
            $this->setError('文件过大');
336
337
            return false;
338
        }
339
        // 读取临时文件里 上传文件的信息
340
        $key = "name=\"{$name}\"; filename=\"{$file_name}\"\r\nContent-Type: {$file_type}\r\n";
341
342
        $param       = [];
343
        $param[$key] = $rest['content'];
344
345
        $res = $this->_post($node, $param, false);
346
347
        return $res;
348
    }
349
350
    /**
351
     * curl 抓取图片 + 头信息
352
     *
353
     * @param $url
354
     *
355
     * @return array
356
     */
357
    private static function curl_get($url)
358
    {
359
        $ch = curl_init();
360
        curl_setopt($ch, CURLOPT_URL, $url);
361
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
362
        curl_setopt($ch, CURLOPT_HEADER, true);
363
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
364
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
365
366
        $res      = curl_exec($ch);
367
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
368
        curl_close($ch);
369
370
        $header = '';
371
        $body   = $res;
372
373
        if ($httpcode == 200) {
374
            list($header, $body) = explode("\r\n\r\n", $res, 2);
375
            $header = Api::http_parse_headers($header);
376
        }
377
378
        $apiReturnData            = [];
379
        $apiReturnData['type']    = $header['Content-Type'];
380
        $apiReturnData['size']    = $header['Content-Length'];
381
        $apiReturnData['header']  = $header;
382
        $apiReturnData['content'] = $body;
383
384
        return $apiReturnData;
385
    }
386
}
387