-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathCurl.php
More file actions
327 lines (294 loc) · 9.35 KB
/
Curl.php
File metadata and controls
327 lines (294 loc) · 9.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
<?php
/**
* @file
* PublisherAPI cURL HTTP client integration class.
*/
namespace ChapterThree\AppleNewsAPI\PublisherAPI;
/**
* PublisherAPI cURL HTTP client.
*
* @package ChapterThree\AppleNewsAPI\PublisherAPI\Curl
* @subpackage ChapterThree\AppleNewsAPI\PublisherAPI\Base
*/
class Curl extends Base {
/** @var (const) CRLF */
const EOL = "\r\n";
/** @var (string) Multipat data boundary unique string. */
private $boundary;
/**
* Initialize variables needed in the communication with the API.
*
* @param (string) $key API Key.
* @param (string) $secret API Secret Key.
* @param (string) $endpoint API endpoint URL.
*/
public function __construct($key, $secret, $endpoint) {
parent::__construct($key, $secret, $endpoint);
$this->boundary = md5(uniqid() . microtime());
}
/**
* Setup HTTP client to make requests.
*/
public function setHTTPClient() {
// Use PHP Curl Class
// @see https://github.com/php-curl-class/php-curl-class
$this->client = new \Curl\Curl;
}
/**
* Set HTTP headers.
*
* @param (array) $headers Associative array [header field name => value].
*/
protected function setHeaders(Array $headers = []) {
foreach ($headers as $property => $value) {
$this->client->setHeader($property, $value);
}
}
/**
* Remove specified header names from HTTP request.
*
* @param (array) $headers Associative array [header1, header2, ..., headerN].
*/
protected function unsetHeaders(Array $headers = []) {
foreach ($headers as $property) {
$this->client->unsetHeader($property);
}
}
/**
* Create HTTP request.
*
* @param (array|string) $data Raw content of the request or associative array to pass to endpoints.
*
* @return (object) HTTP Response object.
*/
protected function request($data) {
try {
if ($this->method == 'delete') {
$response = $this->client->{$this->method}($this->path(), [], $data);
}
else {
$response = $this->client->{$this->method}($this->path(), $data);
}
$this->client->close();
}
catch (\Exception $e) {
// Throw an expection if something goes wrong.
$this->triggerError($e->getMessage());
}
return $this->response($response);
}
/**
* Preprocess HTTP response.
*
* @param (object) $response Structured object.
*
* @return (object) HTTP Response object.
*/
protected function response($response) {
// Check for HTTP response error codes.
if ($this->client->error) {
$this->onErrorResponse(
$this->client->errorCode,
$this->client->errorMessage,
$response
);
}
else {
$this->onSuccessfulResponse($response);
}
return $response;
}
/**
* Create GET request to a specified endpoint.
*
* @param (string) $path API endpoint path.
* @param (string) $path_args Endpoint path arguments to replace tokens in the path.
* @param (string) $data Raw content of the request or associative array to pass to endpoints.
*
* @return object Preprocessed structured object.
*/
public function get($path, Array $path_args = [], Array $data = []) {
parent::get($path, $path_args, $data);
$this->setHeaders(
[
'Authorization' => $this->auth()
]
);
return $this->request($data);
}
/**
* Create DELETE request to a specified endpoint.
*
* @param (string) $path API endpoint path.
* @param (string) $path_args Endpoint path arguments to replace tokens in the path.
* @param (string) $data Raw content of the request or associative array to pass to endpoints.
*
* @return object Preprocessed structured object and returns 204 No Content on success, with no response body.
*/
public function delete($path, Array $path_args = [], Array $data = []) {
parent::delete($path, $path_args, $data);
$this->setHeaders(
[
'Authorization' => $this->auth()
]
);
$this->unsetHeaders(
[
'Content-Type'
]
);
return $this->request($data);
}
/**
* Create POST request to a specified endpoint.
*
* @param (string) $path API endpoint path.
* @param (array) $path_args Endpoint path arguments to replace tokens in the
* path.
* @param (array) $data Associative array to pass to endpoints, with keys:
* - json - JSON string.
* - files - Array of file paths keyed on URL used to reference file in json.
* - metadata - Associative array of metadata.
*
* @return object Preprocessed structured object.
*/
public function post($path, Array $path_args, Array $data = []) {
parent::post($path, $path_args, $data);
// JSON string to be posted to PublisherAPI instead of article.json file.
$json = !empty($data['json']) ? $data['json'] : '';
// Article assests (article.json, images, fonts etc...).
$files = !empty($data['files']) ? $data['files'] : [];
// Raw HTTP contents of the POST request.
$multiparts = [];
// Make sure you don't submit article.json if you passing json
// as a parameter to Post method.
if (!empty($json)) {
$multiparts[] = $this->multipartPart(
[
'name' => 'article',
'filename' => 'article.json',
'mimetype' => 'application/json',
'size' => strlen($json)
],
'application/json',
$json
);
}
// Article metadata.
if (!empty($data['metadata'])) {
$multiparts[] = $this->multipartPart(
[
'name' => 'metadata'
],
'application/json',
$data['metadata']
);
}
// Process each file and generate multipart form data.
foreach ($files as $url => $path) {
// Load file information.
$info = $this->getFileInformation($path);
$multiparts[] = $this->multipartPart(
[
'filename' => pathinfo($url, PATHINFO_BASENAME),
'name' => pathinfo($url, PATHINFO_FILENAME),
'size' => $info['size'],
],
($info['extension'] == 'json') ? 'application/json' : $info['mimetype'],
$info['contents']
);
}
// Set content type and boundary token.
$content_type = sprintf('multipart/form-data; boundary=%s', $this->boundary);
// Put together all the multipart data.
$contents = $this->multipartFinalize($multiparts);
// String to add to generate Authorization hash.
$string = $content_type . $contents;
// Make sure no USERAGENET in headers.
$this->client->setOpt(CURLOPT_USERAGENT, NULL);
$this->SetHeaders(
[
'Accept' => 'application/json',
'Content-Type' => $content_type,
'Content-Length' => strlen($contents),
'Authorization' => $this->auth($string)
]
);
// Set to use TLS 1.2
$this->client->setOpt(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
// Send POST request.
return $this->request($contents);
}
/**
* Get file information and its contents to upload.
*
* @param (string) $path Path to a file included in the POST request.
*
* @return (array) Associative array. The array contains information about a file.
*/
protected function getFileInformation($path) {
$file = pathinfo($path);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimetype = finfo_file($finfo, $path);
// Check if mimetype is supported.
if (!in_array($mimetype, $this->valid_mimes)) {
if ($mimetype == 'text/plain') {
$mimetype = 'application/octet-stream';
}
else {
$this->triggerError('Unsupported mime type: ' . $mimetype);
}
}
$contents = file_get_contents($path);
return [
'name' => str_replace(' ', '-', $file['filename']),
'filename' => $file['basename'],
'extension' => $file['extension'],
'mimetype' => $mimetype,
'contents' => $contents,
'size' => strlen($contents)
];
}
/**
* Generate individual multipart data parts.
*
* @param (array) $attributes Associative array with information about each file (mimetype, filename, size).
* @param (string) $mimetype Multipart mime type.
* @param (string) $contents Contents of the multipart content chunk.
*
* @return (string) Raw HTTP multipart chunk formatted according to the RFC.
*
* @see https://www.ietf.org/rfc/rfc2388.txt
*/
protected function multipartPart(Array $attributes, $mimetype = null, $contents = null) {
$multipart = '';
$headers = [];
foreach ($attributes as $name => $value) {
$headers[] = $name . '=' . $value;
}
// Generate multipart data and contents.
$multipart .= '--' . $this->boundary . static::EOL;
$multipart .= 'Content-Type: ' . $mimetype . static::EOL;
$multipart .= 'Content-Disposition: form-data; ' . join('; ', $headers) . static::EOL;
$multipart .= static::EOL . $contents . static::EOL;
return $multipart;
}
/**
* Finalize multipart data.
*
* @param (array) $multiparts Multipart data with its headers.
*
* @return (string) Raw HTTP multipart data formatted according to the RFC.
*
* @see https://www.ietf.org/rfc/rfc2388.txt
*/
protected function multipartFinalize(Array $multiparts = []) {
$contents = '';
foreach ($multiparts as $multipart) {
$contents .= $multipart;
}
$contents .= '--' . $this->boundary . '--';
$contents .= static::EOL;
return $contents;
}
}