-
Notifications
You must be signed in to change notification settings - Fork 82
/
Request.php
837 lines (756 loc) · 21.7 KB
/
Request.php
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
<?php
namespace InstagramAPI;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request as HttpRequest;
use GuzzleHttp\Psr7\Stream;
use function GuzzleHttp\Psr7\stream_for;
use InstagramAPI\Exception\InstagramException;
use InstagramAPI\Exception\LoginRequiredException;
use Psr\Http\Message\ResponseInterface as HttpResponseInterface;
use Psr\Http\Message\StreamInterface;
/**
* Bridge between Instagram Client calls, the object mapper & response objects.
*/
class Request
{
/**
* The Instagram class instance we belong to.
*
* @var \InstagramAPI\Instagram
*/
protected $_parent;
/**
* Which API version to use for this request.
*
* @var int
*/
protected $_apiVersion;
/**
* Endpoint URL (absolute or relative) for this request.
*
* @var string
*/
protected $_url;
/**
* An array of query params.
*
* @var array
*/
protected $_params;
/**
* An array of POST params.
*
* @var array
*/
protected $_posts;
/**
* An array of POST params keys to exclude from signed body.
*
* @var string[]
*/
protected $_excludeSigned;
/**
* Raw request body.
*
* @var StreamInterface
*/
protected $_body;
/**
* An array of files to upload.
*
* @var array
*/
protected $_files;
/**
* An array of HTTP headers to add to the request.
*
* @var string[]
*/
protected $_headers;
/**
* Whether to add the default headers.
*
* @var bool
*/
protected $_defaultHeaders;
/**
* Whether this API call needs authorization.
*
* On by default since most calls require authorization.
*
* @var bool
*/
protected $_needsAuth;
/**
* Whether this API call needs signing of the POST data.
*
* On by default since most calls require it.
*
* @var bool
*/
protected $_signedPost;
/**
* Whether this API call needs signing of the GET params.
*
* Off by default.
*
* @var bool
*/
protected $_signedGet;
/**
* Whether this API endpoint responds with multiple JSON objects.
*
* Off by default.
*
* @var bool
*/
protected $_isMultiResponse;
/**
* Whether this API call needs gz-compressing of the POST data.
*
* Off by default
*
* @var bool
*/
protected $_isBodyCompressed;
/**
* Opened file handles.
*
* @var resource[]
*/
protected $_handles;
/**
* Extra Guzzle options for this request.
*
* @var array
*/
protected $_guzzleOptions;
/**
* Cached HTTP response object.
*
* @var HttpResponseInterface
*/
protected $_httpResponse;
/**
* Constructor.
*
* @param Instagram $parent
* @param string $url
*/
public function __construct(
\InstagramAPI\Instagram $parent,
$url)
{
$this->_parent = $parent;
$this->_url = $url;
// Set defaults.
$this->_apiVersion = 1;
$this->_headers = [];
$this->_params = [];
$this->_posts = [];
$this->_files = [];
$this->_handles = [];
$this->_guzzleOptions = [];
$this->_needsAuth = true;
$this->_signedPost = true;
$this->_signedGet = false;
$this->_isMultiResponse = false;
$this->_isBodyCompressed = false;
$this->_excludeSigned = [];
$this->_defaultHeaders = true;
}
/**
* Destructor.
*/
public function __destruct()
{
// Ensure that all opened handles are closed.
$this->_closeHandles();
}
/**
* Set API version to use.
*
* @param int $apiVersion
*
* @throws \InvalidArgumentException In case of unsupported API version.
*
* @return self
*/
public function setVersion(
$apiVersion)
{
if (!array_key_exists($apiVersion, Constants::API_URLS)) {
throw new \InvalidArgumentException(sprintf('"%d" is not a supported API version.', $apiVersion));
}
$this->_apiVersion = $apiVersion;
return $this;
}
/**
* Add query param to request, overwriting any previous value.
*
* @param string $key
* @param mixed $value
*
* @return self
*/
public function addParam(
$key,
$value)
{
if ($value === true) {
$value = 'true';
} elseif ($value === false) {
$value = 'false';
}
$this->_params[$key] = $value;
return $this;
}
/**
* Add POST param to request, overwriting any previous value.
*
* @param string $key
* @param mixed $value
*
* @return self
*/
public function addPost(
$key,
$value)
{
if ($value === true) {
$value = 'true';
} elseif ($value === false) {
$value = 'false';
}
$this->_posts[$key] = $value;
return $this;
}
/**
* Add unsigned POST param to request, overwriting any previous value.
*
* This adds a POST value and marks it as "never sign it", even if this
* is a signed request. Instagram sometimes needs a few unsigned values.
*
* @param string $key
* @param mixed $value
*
* @return self
*/
public function addUnsignedPost(
$key,
$value)
{
$this->addPost($key, $value);
$this->_excludeSigned[] = $key;
return $this;
}
/**
* Add an on-disk file to a POST request, which causes this to become a multipart form request.
*
* @param string $key Form field name.
* @param string $filepath Path to a file.
* @param string|null $filename Filename to use in Content-Disposition header.
* @param array $headers An associative array of headers.
*
* @throws \InvalidArgumentException
*
* @return self
*/
public function addFile(
$key,
$filepath,
$filename = null,
array $headers = [])
{
// Validate
if (!is_file($filepath)) {
throw new \InvalidArgumentException(sprintf('File "%s" does not exist.', $filepath));
}
if (!is_readable($filepath)) {
throw new \InvalidArgumentException(sprintf('File "%s" is not readable.', $filepath));
}
// Inherit value from $filepath, if not supplied.
if ($filename === null) {
$filename = $filepath;
}
$filename = basename($filename);
// Default headers.
$headers = $headers + [
'Content-Type' => 'application/octet-stream',
'Content-Transfer-Encoding' => 'binary',
];
$this->_files[$key] = [
'filepath' => $filepath,
'filename' => $filename,
'headers' => $headers,
];
return $this;
}
/**
* Add raw file data to a POST request, which causes this to become a multipart form request.
*
* @param string $key Form field name.
* @param string $data File data.
* @param string|null $filename Filename to use in Content-Disposition header.
* @param array $headers An associative array of headers.
*
* @return self
*/
public function addFileData(
$key,
$data,
$filename,
array $headers = [])
{
$filename = basename($filename);
// Default headers.
$headers = $headers + [
'Content-Type' => 'application/octet-stream',
'Content-Transfer-Encoding' => 'binary',
];
$this->_files[$key] = [
'contents' => $data,
'filename' => $filename,
'headers' => $headers,
];
return $this;
}
/**
* Add custom header to request, overwriting any previous or default value.
*
* The custom value will even take precedence over the default headers!
*
* WARNING: If this is called multiple times with the same header "key"
* name, it will only keep the LATEST value given for that specific header.
* It will NOT keep any of its older values, since you can only have ONE
* value per header! If you want multiple values in headers that support
* it, you must manually format them properly and send us the final string,
* usually by separating the value string entries with a semicolon.
*
* @param string $key
* @param string $value
*
* @return self
*/
public function addHeader(
$key,
$value)
{
$this->_headers[$key] = $value;
return $this;
}
/**
* Add headers used by most API requests.
*
* @return self
*/
protected function _addDefaultHeaders()
{
if ($this->_defaultHeaders) {
$this->_headers['X-IG-App-ID'] = Constants::FACEBOOK_ANALYTICS_APPLICATION_ID;
$this->_headers['X-IG-Capabilities'] = Constants::X_IG_Capabilities;
$this->_headers['X-IG-Connection-Type'] = Constants::X_IG_Connection_Type;
$this->_headers['X-IG-Connection-Speed'] = mt_rand(1000, 3700).'kbps';
// TODO: IMPLEMENT PROPER CALCULATION OF THESE HEADERS.
$this->_headers['X-IG-Bandwidth-Speed-KBPS'] = '-1.000';
$this->_headers['X-IG-Bandwidth-TotalBytes-B'] = '0';
$this->_headers['X-IG-Bandwidth-TotalTime-MS'] = '0';
}
return $this;
}
/**
* Set the "add default headers" flag.
*
* @param bool $flag
*
* @return self
*/
public function setAddDefaultHeaders(
$flag)
{
$this->_defaultHeaders = $flag;
return $this;
}
/**
* Set the extra Guzzle options for this request.
*
* @param array $guzzleOptions Extra Guzzle options for this request.
*
* @return self
*/
public function setGuzzleOptions(
array $guzzleOptions)
{
$this->_guzzleOptions = $guzzleOptions;
return $this;
}
/**
* Set raw request body.
*
* @param StreamInterface $stream
*
* @return self
*/
public function setBody(
StreamInterface $stream)
{
$this->_body = $stream;
return $this;
}
/**
* Set authorized request flag.
*
* @param bool $needsAuth
*
* @return self
*/
public function setNeedsAuth(
$needsAuth)
{
$this->_needsAuth = $needsAuth;
return $this;
}
/**
* Set signed request data flag.
*
* @param bool $signedPost
*
* @return self
*/
public function setSignedPost(
$signedPost = true)
{
$this->_signedPost = $signedPost;
return $this;
}
/**
* Set signed request params flag.
*
* @param bool $signedGet
*
* @return self
*/
public function setSignedGet(
$signedGet = false)
{
$this->_signedGet = $signedGet;
return $this;
}
/**
* Set the "this API endpoint responds with multiple JSON objects" flag.
*
* @param bool $flag
*
* @return self
*/
public function setIsMultiResponse(
$flag = false)
{
$this->_isMultiResponse = $flag;
return $this;
}
/**
* Set gz-compressed request params flag.
*
* @param bool $isBodyCompressed
*
* @return self
*/
public function setIsBodyCompressed(
$isBodyCompressed = false)
{
$this->_isBodyCompressed = $isBodyCompressed;
if ($isBodyCompressed === true) {
$this->_headers['Content-Encoding'] = 'gzip';
} elseif (isset($this->_headers['Content-Encoding']) && $this->_headers['Content-Encoding'] === 'gzip') {
unset($this->_headers['Content-Encoding']);
}
return $this;
}
/**
* Get a Stream for the given file.
*
* @param array $file
*
* @throws \InvalidArgumentException
* @throws \RuntimeException
*
* @return StreamInterface
*/
protected function _getStreamForFile(
array $file)
{
if (isset($file['contents'])) {
$result = stream_for($file['contents']); // Throws.
} elseif (isset($file['filepath'])) {
$handle = fopen($file['filepath'], 'rb');
if ($handle === false) {
throw new \RuntimeException(sprintf('Could not open file "%s" for reading.', $file['filepath']));
}
$this->_handles[] = $handle;
$result = stream_for($handle); // Throws.
} else {
throw new \InvalidArgumentException('No data for stream creation.');
}
return $result;
}
/**
* Convert the request's data into its HTTP POST multipart body contents.
*
* @throws \InvalidArgumentException
* @throws \RuntimeException
*
* @return MultipartStream
*/
protected function _getMultipartBody()
{
// Here is a tricky part: all form data (including files) must be ordered by hash code.
// So we are creating an index for building POST data.
$index = Utils::reorderByHashCode(array_merge($this->_posts, $this->_files));
// Build multipart elements using created index.
$elements = [];
foreach ($index as $key => $value) {
if (!isset($this->_files[$key])) {
$element = [
'name' => $key,
'contents' => $value,
];
} else {
$file = $this->_files[$key];
$element = [
'name' => $key,
'contents' => $this->_getStreamForFile($file), // Throws.
'filename' => isset($file['filename']) ? $file['filename'] : null,
'headers' => isset($file['headers']) ? $file['headers'] : [],
];
}
$elements[] = $element;
}
return new MultipartStream( // Throws.
$elements,
Utils::generateMultipartBoundary()
);
}
/**
* Close opened file handles.
*/
protected function _closeHandles()
{
if (!is_array($this->_handles) || !count($this->_handles)) {
return;
}
foreach ($this->_handles as $handle) {
Utils::safe_fclose($handle);
}
$this->_resetHandles();
}
/**
* Reset opened handles array.
*/
protected function _resetHandles()
{
$this->_handles = [];
}
/**
* Convert the request's data into its HTTP POST urlencoded body contents.
*
* @throws \InvalidArgumentException
*
* @return Stream
*/
protected function _getUrlencodedBody()
{
$this->_headers['Content-Type'] = Constants::CONTENT_TYPE;
return stream_for( // Throws.
http_build_query(Utils::reorderByHashCode($this->_posts))
);
}
/**
* Convert the request's data into its HTTP POST body contents.
*
* @throws \InvalidArgumentException
* @throws \RuntimeException
*
* @return StreamInterface|null The body stream if POST request; otherwise NULL if GET request.
*/
protected function _getRequestBody()
{
// Check and return raw body stream if set.
if ($this->_body !== null) {
if ($this->_isBodyCompressed) {
return stream_for(zlib_encode((string) $this->_body, ZLIB_ENCODING_GZIP));
}
return $this->_body;
}
// We have no POST data and no files.
if (!count($this->_posts) && !count($this->_files)) {
return;
}
// Sign POST data if needed.
if ($this->_signedPost) {
$this->_posts = Signatures::signData($this->_posts, $this->_excludeSigned);
}
// Switch between multipart (at least one file) or urlencoded body.
if (!count($this->_files)) {
$result = $this->_getUrlencodedBody(); // Throws.
} else {
$result = $this->_getMultipartBody(); // Throws.
}
if ($this->_isBodyCompressed) {
return stream_for(zlib_encode((string) $result, ZLIB_ENCODING_GZIP));
}
return $result;
}
/**
* Build HTTP request object.
*
* @throws \InvalidArgumentException
* @throws \RuntimeException
*
* @return HttpRequest
*/
protected function _buildHttpRequest()
{
$endpoint = $this->_url;
// Determine the URI to use (it's either relative to API, or a full URI).
if (strncmp($endpoint, 'http:', 5) !== 0 && strncmp($endpoint, 'https:', 6) !== 0) {
$endpoint = Constants::API_URLS[$this->_apiVersion].$endpoint;
}
// Check signed request params flag.
if ($this->_signedGet) {
$this->_params = Signatures::signData($this->_params);
}
// Generate the final endpoint URL, by adding any custom query params.
if (count($this->_params)) {
$endpoint = $endpoint
.(strpos($endpoint, '?') === false ? '?' : '&')
.http_build_query(Utils::reorderByHashCode($this->_params));
}
// Add default headers (if enabled).
$this->_addDefaultHeaders();
/** @var StreamInterface|null $postData The POST body stream; is NULL if GET request instead. */
$postData = $this->_getRequestBody(); // Throws.
// Determine request method.
$method = $postData !== null ? 'POST' : 'GET';
// Build HTTP request object.
return new HttpRequest( // Throws (they didn't document that properly).
$method,
$endpoint,
$this->_headers,
$postData
);
}
/**
* Helper which throws an error if not logged in.
*
* Remember to ALWAYS call this function at the top of any API request that
* requires the user to be logged in!
*
* @throws LoginRequiredException
*/
protected function _throwIfNotLoggedIn()
{
// Check the cached login state. May not reflect what will happen on the
// server. But it's the best we can check without trying the actual request!
if (!$this->_parent->isMaybeLoggedIn) {
throw new LoginRequiredException('User not logged in. Please call login() and then try again.');
}
}
/**
* Perform the request and get its raw HTTP response.
*
* @throws \InvalidArgumentException
* @throws \RuntimeException
* @throws InstagramException
*
* @return HttpResponseInterface
*/
public function getHttpResponse()
{
// Prevent request from sending multiple times.
if ($this->_httpResponse === null) {
if ($this->_needsAuth) {
// Throw if this requires authentication and we're not logged in.
$this->_throwIfNotLoggedIn();
}
$this->_resetHandles();
try {
$this->_httpResponse = $this->_parent->client->api( // Throws.
$this->_buildHttpRequest(), // Throws.
$this->_guzzleOptions
);
} finally {
$this->_closeHandles();
}
}
return $this->_httpResponse;
}
/**
* Return the raw HTTP response body.
*
* @throws \InvalidArgumentException
* @throws \RuntimeException
* @throws InstagramException
*
* @return string
*/
public function getRawResponse()
{
$httpResponse = $this->getHttpResponse(); // Throws.
$body = (string) $httpResponse->getBody();
// Handle API endpoints that respond with multiple JSON objects.
// NOTE: We simply merge all JSON objects into a single object. This
// text replacement of "}\r\n{" is safe, because the actual JSON data
// objects never contain literal newline characters (http://json.org).
// And if we get any duplicate properties, then PHP will simply select
// the latest value for that property (ex: a:1,a:2 is treated as a:2).
if ($this->_isMultiResponse) {
$body = str_replace("}\r\n{", ',', $body);
}
return $body;
}
/**
* Return safely JSON-decoded HTTP response.
*
* This uses a special decoder which handles 64-bit numbers correctly.
*
* @param bool $assoc When FALSE, decode to object instead of associative array.
*
* @throws \InvalidArgumentException
* @throws \RuntimeException
* @throws InstagramException
*
* @return mixed
*/
public function getDecodedResponse(
$assoc = true)
{
// Important: Special JSON decoder.
return Client::api_body_decode(
$this->getRawResponse(), // Throws.
$assoc
);
}
/**
* Perform the request and map its response data to the provided object.
*
* @param Response $responseObject An instance of a class object whose properties to fill with the response.
*
* @throws \InvalidArgumentException
* @throws \RuntimeException
* @throws InstagramException
*
* @return Response The provided responseObject with all JSON properties filled.
*/
public function getResponse(
Response $responseObject)
{
// Check for API response success and put its response in the object.
$this->_parent->client->mapServerResponse( // Throws.
$responseObject,
$this->getRawResponse(), // Throws.
$this->getHttpResponse() // Throws.
);
return $responseObject;
}
}