forked from fictive-kin/Resty.php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResty.php
More file actions
955 lines (795 loc) · 25.3 KB
/
Copy pathResty.php
File metadata and controls
955 lines (795 loc) · 25.3 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
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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
<?php
/**
* A simple PHP library for doing RESTful HTTP stuff. Does *not* require the curl extension.
* @link https://github.com/fictivekin/resty.php
*/
class Resty
{
/**
* The version of this lib
*/
const VERSION = '0.4.0';
const DEFAULT_TIMEOUT = 240;
const DEFAULT_MAX_REDIRECTS = 0;
/**
* @var bool enables debugging output
*/
protected $debug = false;
/**
* logging function (should be a Closure)
* @var Closure
*/
protected $logger = null;
/**
* @var bool whether or not to auto-parse the response body as JSON or XML
*/
protected $parse_body = true;
/**
* @var string
* @see Resty::getUserAgent()
*/
protected $user_agent = null;
/**
* @var string
*/
protected $base_url;
/**
* Stores the last request hash
* @var array
*/
protected $last_request;
/**
* Stores the last response hash
* @var array
*/
protected $last_response;
/**
* stores anon func callbacks (because you can't store them as obj props
* @var array
*/
protected $callbacks = array();
/**
* username for basic auth
* @var string
*/
protected $username;
/**
* password for basic auth
* @var string
*/
protected $password;
/**
* by default, silence the fopen warning if we can't open the stream
*/
protected $silence_fopen_warning = true;
/**
* by default, don't raise an exception if fopen() fails
* @var boolean
*/
protected $raise_fopen_exception = false;
/**
* by default, send X-HTTP-Method-Override header for PATCH requests.
* @var boolean
*/
protected $supports_patch = false;
/**
* content-types that will trigger JSON parsing of body
* @var array
*/
public static $JSON_TYPES = array(
'application/json',
'text/json',
'text/x-json',
);
/**
* content-types that will trigger XML parsing
* @var array
*/
public static $XML_TYPES = array(
'application/xml',
'text/xml',
'application/rss+xml',
'application/xhtml+xml',
'application/atom+xml',
'application/xslt+xml',
'application/mathml+xml',
);
/**
* Passed opts can include
* $opts['onRequestLog'] - an anonymous function that takes the Resty::last_request property as arg
* $opts['onResponseLog'] - an anonymous function that takes the Resty::last_response property as arg
* $opts['silence_fopen_warning'] - boolean: silence warnings from fopen when trying to open stream
* $opts['raise_fopen_exception'] - boolean: raise an exception from fopen if trying to open stream fails
* $opts['supports_patch'] - boolean: set to true if the REST end point you're connecting to supports PATCH. False will use the X-HTTP-Method-Override header.
*
* @see Resty::last_request
* @see Resty::last_response
* @see Resty::sendRequest()
* @param array $opts OPTIONAL array of options
*/
function __construct($opts=null) {
if (!empty($opts['onRequestLog']) && ($opts['onRequestLog'] instanceof Closure)) {
$this->callbacks['onRequestLog'] = $opts['onRequestLog'];
}
if (!empty($opts['onResponseLog']) && ($opts['onResponseLog'] instanceof Closure)) {
$this->callbacks['onResponseLog'] = $opts['onResponseLog'];
}
if (isset($opts['silence_fopen_warning'])) {
$this->silenceFopenWarning((bool)$opts['silence_fopen_warning']);
}
if (isset($opts['raise_fopen_exception'])) {
$this->raiseFopenException((bool)$opts['raise_fopen_exception']);
}
if (isset($opts['supports_patch'])) {
$this->supportsPatch((bool)$opts['supports_patch']);
}
}
/**
* retrieve the last request we sent
*
* valid keys are ['url', 'method', 'querydata', 'headers', 'options', 'opts']
*
* @param string $key just retrieve a given field from the hash
* @return mixed
*/
public function getLastRequest($key=null) {
if (!isset($key)) {
return $this->last_request;
}
return $this->last_request[$key];
}
/**
* retrieve the last response we got
*
* valid keys are ['meta', 'status', 'headers', 'body']
*
* @param string $key just retrieve a given field from the hash
* @return mixed
*/
public function getLastResponse($key=null) {
if (!isset($key)) {
return $this->last_response;
}
return $this->last_response[$key];
}
/**
* get a specific link (via the rel tag) from the last response
*
* @param string $rel
* @return stdClass with a link and type.
*/
public function getLink($rel) {
$linkObj = new stdClass();
$linkObj->link = '';
$linkObj->type = '';
if (isset($this->last_response['headers']['link'])) {
$links = is_array($this->last_response['headers']['link']) ? $this->last_response['headers']['link'] : array($this->last_response['headers']['link']);
foreach($links as $link) {
$matches = array();
if (preg_match('/(<)(.*)(>;rel="(.*)";)(.*)(;type=")(.*)/', $link, $matches)) {
if ($rel == $matches[4]) {
$linkObj->link = $matches[2];
$linkObj->type = $matches[7];
}
}
}
}
return $linkObj;
}
/**
* make a GET request
*
* @param string the URL. This will be appended to the base_url, if any set
* @param array $querydata hash of key/val pairs
* @param array $headers hash of key/val pairs
* @param array $options hash of key/val pairs ('timeout')
* @return array the response hash
* @see Resty::sendRequest()
*/
public function get($url, $querydata=null, $headers=null, $options=null) {
return $this->sendRequest($url, 'GET', $querydata, $headers, $options);
}
/**
* make a POST request
*
* @param string the URL. This will be appended to the base_url, if any set
* @param array $querydata hash of key/val pairs
* @param array $headers hash of key/val pairs
* @param array $options hash of key/val pairs ('timeout')
* @return array the response hash
* @see Resty::sendRequest()
*/
public function post($url, $querydata=null, $headers=null, $options=null) {
return $this->sendRequest($url, 'POST', $querydata, $headers, $options);
}
/**
* make a PUT request
*
* @param string the URL. This will be appended to the base_url, if any set
* @param array $querydata hash of key/val pairs
* @param array $headers hash of key/val pairs
* @param array $options hash of key/val pairs ('timeout')
* @return array the response hash
* @see Resty::sendRequest()
*/
public function put($url, $querydata=null, $headers=null, $options=null) {
return $this->sendRequest($url, 'PUT', $querydata, $headers, $options);
}
/**
* make a PATCH request
*
* @param string the URL. This will be appended to the base_url, if any set
* @param array $querydata hash of key/val pairs
* @param array $headers hash of key/val pairs
* @param array $options hash of key/val pairs ('timeout')
* @return array the response hash
* @see Resty::sendRequest()
*/
public function patch($url, $querydata=null, $headers=null, $options=null) {
return $this->sendRequest($url, 'PATCH', $querydata, $headers, $options);
}
/**
* make a DELETE request
*
* @param string the URL. This will be appended to the base_url, if any set
* @param array $querydata hash of key/val pairs
* @param array $headers hash of key/val pairs
* @param array $options hash of key/val pairs ('timeout')
* @return array the response hash
* @see Resty::sendRequest()
*/
public function delete($url, $querydata=null, $headers=null, $options=null) {
return $this->sendRequest($url, 'DELETE', $querydata, $headers, $options);
}
/**
* @param string $url
* @param array $files
* @param array $params
* @param array $headers
* @param array $options
*
* The $files array should be a set of key/val pairs, with the key being
* the field name, and the val the file path. ex:
* $files['avatar'] = '/path/to/file.jpg';
* $files['background'] = '/path/to/file2.jpg';
*
*/
public function postFiles($url, $files, $params=null, $headers=null, $options=null) {
$datastr = "";
$boundary = "---------------------".substr(md5(rand(0,32000)), 0, 10);
// build params
if (isset($params)) {
foreach($params as $key => $val) {
$datastr .= "--$boundary\n";
$datastr .= "Content-Disposition: form-data; name=\"".$key."\"\n\n".$val."\n";
}
}
$datastr .= "--$boundary\n";
// build files
foreach($files as $key => $file)
{
$filename = pathinfo($file, PATHINFO_BASENAME);
$content_type = $this->getMimeType($file);
$fileContents = file_get_contents($file);
$datastr .= "Content-Disposition: form-data; name=\"{$key}\"; filename=\"{$filename}\"\n";
$datastr .= "Content-Type: {$content_type}\n";
$datastr .= "Content-Transfer-Encoding: binary\n\n";
$datastr .= $fileContents."\n";
$datastr .= "--$boundary\n";
}
if (!isset($headers)) {
$headers = array();
}
$headers['Content-Type'] = 'multipart/form-data; boundary='.$boundary;
return $this->post($url, $datastr, $headers, $options);
}
/**
* @param string $url
* @param array $binary_data
* @param array $params
* @param array $headers
* @param array $options
*
* The $binary_data array should be a set of key/val pairs, with the key being
* the field name, and the val the binary data. ex:
* $files['avatar'] = <BINARY>;
* $files['background'] = <BINARY>;
*
* with that data, a multipart POST body is created, identical to a file
* upload, just without reading the data from a file
*
*/
public function postBinary($url, $binary_data, $params=null, $headers=null, $options=null) {
$datastr = "";
$boundary = "---------------------".substr(md5(rand(0,32000)), 0, 10);
// build params
if (isset($params)) {
foreach($params as $key => $val) {
$datastr .= "--$boundary\n";
$datastr .= "Content-Disposition: form-data; name=\"".$key."\"\n\n".$val."\n";
}
}
$datastr .= "--$boundary\n";
// build files
foreach($binary_data as $key => $bdata)
{
$filename = 'bdata';
$content_type = 'application/octet-stream';
$datastr .= "Content-Disposition: form-data; name=\"{$key}\"; filename=\"{$filename}\"\n";
$datastr .= "Content-Type: {$content_type}\n";
$datastr .= "Content-Transfer-Encoding: binary\n\n";
$datastr .= $bdata."\n";
$datastr .= "--$boundary\n";
}
if (!isset($headers)) {
$headers = array();
}
$headers['Content-Type'] = 'multipart/form-data; boundary='.$boundary;
return $this->post($url, $datastr, $headers, $options);
}
/**
* @see Resty::postFiles()
*
* Stole this from the Amazon S3 class:
*
* Copyright (c) 2008, Donovan Schönknecht. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Amazon S3 is a trademark of Amazon.com, Inc. or its affiliates.
*
*/
protected function getMimeType($filepath) {
if (extension_loaded('fileinfo') && isset($_ENV['MAGIC']) &&
($finfo = finfo_open(FILEINFO_MIME, $_ENV['MAGIC'])) !== false) {
if (($type = finfo_file($finfo, $filepath)) !== false) {
// Remove the charset and grab the last content-type
$type = explode(' ', str_replace('; charset=', ';charset=', $type));
$type = array_pop($type);
$type = explode(';', $type);
$type = trim(array_shift($type));
}
finfo_close($finfo);
// If anyone is still using mime_content_type()
} elseif (function_exists('mime_content_type')) {
$type = trim(mime_content_type($filepath));
}
if ($type !== false && strlen($type) > 0) { return $type; }
// Otherwise do it the old fashioned way
static $exts = array(
'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png',
'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'ico' => 'image/x-icon',
'swf' => 'application/x-shockwave-flash', 'pdf' => 'application/pdf',
'zip' => 'application/zip', 'gz' => 'application/x-gzip',
'tar' => 'application/x-tar', 'bz' => 'application/x-bzip',
'bz2' => 'application/x-bzip2', 'txt' => 'text/plain',
'asc' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html',
'css' => 'text/css', 'js' => 'text/javascript',
'xml' => 'text/xml', 'xsl' => 'application/xsl+xml',
'ogg' => 'application/ogg', 'mp3' => 'audio/mpeg', 'wav' => 'audio/x-wav',
'avi' => 'video/x-msvideo', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg',
'mov' => 'video/quicktime', 'flv' => 'video/x-flv', 'php' => 'text/x-php'
);
$ext = strtolower(pathInfo($filepath, PATHINFO_EXTENSION));
return isset($exts[$ext]) ? $exts[$ext] : 'application/octet-stream';
}
/**
* bc wrapper
*/
public function enableDebugging($state=false) {
$this->debug($state);
}
/**
* enable or disable debugging. If no arg passed, just returns current state
* @param bool $state=null if not passed, state not changed
* @return boolean the current state
*/
public function debug($state=null) {
if (isset($state)) {
$this->debug = (bool)$state;
}
return $this->debug;
}
/**
* raise an exception from fopen if trying to open stream fails
* @param boolean $state=null optional, set the state
* @return boolean the current state
*/
public function raiseFopenException($state=null) {
if (isset($state)) {
$this->raise_fopen_exception = (bool)$state;
}
return $this->raise_fopen_exception;
}
/**
* silence warnings from fopen when trying to open stream
* @param boolean $state=null optional, set the state
* @return boolean the current state
*/
public function silenceFopenWarning($state=null) {
if (isset($state)) {
$this->silence_fopen_warning = (bool)$state;
}
return $this->silence_fopen_warning;
}
/**
* configure whether or not the REST endpoint supports the HTTP PATCH method. If set
* to false, the X-HTTP-Method-Override header will be sent using HTTP POST.
* @param boolean $state=null optional, set the state
* @return boolean the current state
*/
public function supportsPatch($state=null) {
if (isset($state)) {
$this->supports_patch = (bool)$state;
}
return $this->supports_patch;
}
/**
* sets an alternate logging method
* @param Closure $logger
*/
public function setLogger(Closure $logger) {
$this->logger = $logger;
}
/**
* enable or disable automatic parsing of body. default is true
* @param bool $state default TRUE
*/
public function parseBody($state=true) {
$state = (bool)$state;
$this->parse_body = $state;
}
/**
* Sets the base URL for all subsequent requests
* @param string $base_url
*/
public function setBaseURL($base_url) {
$this->base_url = $base_url;
}
/**
* retrieves the current Resty::$base_url
* @return string
*/
public function getBaseURL() {
return $this->base_url;
}
/**
* Sets the user-agent
* @param string $user_agent
*/
public function setUserAgent($user_agent) {
$this->user_agent = $user_agent;
}
/**
* Gets the current user agent. if Resty::$user_agent is not set, uses a default
* @return string
*/
public function getUserAgent() {
if (empty($this->user_agent)) {
$this->user_agent = 'Resty ' . static::VERSION;
}
return $this->user_agent;
}
/**
* Sets credentials for http basic auth
* @param string $username
* @param string $password
*/
public function setCredentials($username, $password) {
$this->username = $username;
$this->password = $password;
}
/**
* removes current credentials
*/
public function clearCredentials() {
$this->username = null;
$this->password = null;
}
/**
* takes a set of key/val pairs and builds an array of raw header strings
*
* @param string $headers
* @return void
* @author Ed Finkler
*/
protected function buildHeadersArray($headers) {
$str_headers = array();
foreach ($headers as $key => $value) {
$str_headers[] = "{$key}: {$value}";
}
return $str_headers;
}
/**
* Extracts the headers of a response from the stream's meta data
* @param array $meta
* @return array
*/
protected function metaToHeaders($meta) {
$headers = array();
if (!isset($meta['wrapper_data'])) {
return $headers;
}
foreach ($meta['wrapper_data'] as $value) {
if (strpos($value, 'HTTP') !== 0) {
preg_match("|^([^:]+):\s?(.+)$|", $value, $matches);
if (is_array($matches) && isset($matches[2])) {
$header_key = trim($matches[1]);
$header_value = trim($matches[2], " \t\n\r\0\x0B\"");
if (isset($headers[$header_key])) {
if (is_array($headers[$header_key])) {
$headers[$header_key][] = $header_value;
} else {
$previous_entry = $headers[$header_key];
$headers[$header_key] = array($previous_entry, $header_value);
}
} else {
$headers[$header_key] = $header_value;
}
}
}
}
return $headers;
}
/**
* extracts the status code from the stream meta data
* @param array $meta
* @return integer
*/
protected function getStatusCode($meta) {
$matches = array();
// We need last http status
$statusHeader = NULL;
foreach(array_reverse($meta['wrapper_data']) as $header)
{
if (strpos($header, 'HTTP') === 0)
{
$statusHeader = $header;
break;
}
}
$status = 0;
preg_match("|\s(\d\d\d)\s?|", $statusHeader, $matches);
if (is_array($matches) && isset($matches[1])) {
$status = (int)trim($matches[1]);
}
return $status;
}
/**
* Sends the HTTP request and retrieves/parses the response
*
* @param string $url
* @param string $method
* @param array $querydata OPTIONAL
* @param array $headers OPTIONAL
* @param array $options OPTIONAL
* @return array
* @author Ed Finkler
*/
public function sendRequest($url, $method='GET', $querydata=null, $headers=null, $options=null) {
$resp = array();
if ($this->base_url) {
$url = $this->base_url.$url;
}
// we need to supply a default content-type
if (!isset($headers['Content-Type'])) {
$headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
// by default, pass the header "Connection: close"
if (!isset($headers['Connection'])) {
$headers['Connection'] = 'close';
}
// if we have a username and password, use it
if (isset($this->username) && isset($this->password) && !isset($headers['Authorization'])) {
$this->log("{$this->username}:{$this->password}");
$headers['Authorization'] = 'Basic '.base64_encode("{$this->username}:{$this->password}");
}
// if PATCH isn't supported, include it as header option.
if ($method == 'PATCH' && !$this->supports_patch) {
$headers['X-HTTP-Method-Override'] = $method;
$method = 'POST';
}
// default timeout
$timeout = isset($options['timeout']) ? $options['timeout'] : static::DEFAULT_TIMEOUT;
// default max_redirects
$max_redirects = isset($options['max_redirects']) ? $options['max_redirects'] : static::DEFAULT_MAX_REDIRECTS;
$content = null;
// if querydata is a string, just pass it as-is
if (isset($querydata) && is_string($querydata)) {
$content = $querydata;
// else if it's an array, make an http query
} elseif (isset($querydata) && is_array($querydata)) {
$content = http_build_query($querydata);
}
// create an array of header strings from the hash
$headerarr = isset($headers) ? $this->buildHeadersArray($headers) : array();
// GET and DELETE should use the URL to pass data
$urlcontent = ('GET' === $method || 'DELETE' === $method);
// if this is a GET or DELETE and we have some $content, append to URL
if ($urlcontent && isset($content)) {
$url .= '?'.$content;
}
$opts = array(
'http'=>array(
'timeout'=>$timeout,
'method'=>$method,
'content'=> (!$urlcontent) ? $content : null,
'user_agent'=>$this->getUserAgent(),
'header'=>$headerarr,
'ignore_errors'=>1,
'max_redirects'=>$max_redirects
)
);
$this->log('URL =================');
$this->log($url);
$this->log('METHOD =================');
$this->log($method);
$this->log('QUERYDATA =================');
$this->log($querydata);
$this->log('HEADERS =================');
$this->log($headers);
$this->log('OPTIONS =================');
$this->log($options);
$this->log('OPTS =================');
$this->log($opts);
$this->last_request = compact('url', 'method', 'querydata', 'headers', 'options', 'opts');
// call custom req log callback
if (!empty($this->callbacks['onRequestLog'])) {
$this->callbacks['onRequestLog']($this->last_request);
}
$resp_data = $this->makeStreamRequest($url, $opts);
$resp['meta'] = $resp_data['meta'];
$resp['body'] = $resp_data['body'];
$resp['error'] = $resp_data['error'];
$resp['error_msg'] = $resp_data['error_msg'];
$resp['status'] = $this->getStatusCode($resp['meta']);
$resp['headers'] = $this->metaToHeaders($resp['meta']);
$this->log($resp);
$this->log("Processing response body...");
$resp = $this->processResponseBody($resp);
$this->log($resp['body']);
$this->last_response = $resp;
// call custom resp log callback
if (!empty($this->callbacks['onResponseLog'])) {
$this->callbacks['onResponseLog']($this->last_response);
}
return $resp;
}
/**
* opens an http stream, sends the request, and returns result
* @param [type] $url [description]
* @param [type] $opts [description]
* @return [type] [description]
*/
protected function makeStreamRequest($url, $opts) {
$resp_data = array(
'meta' => null,
'body' => null,
'error' => true,
'error_msg' => null,
);
$context = stream_context_create($opts);
$this->log("Sending...");
$start_time = microtime(true);
$this->log("Opening stream...");
if ($this->silence_fopen_warning) {
$stream = @fopen($url, 'r', false, $context);
} else {
$stream = fopen($url, 'r', false, $context);
}
if (!$stream) {
$req_time = static::calc_time_passed($start_time);
$opts_json = !empty($opts) ? json_encode($opts) : 'null';
$msg = "Stream open failed for '{$url}'; req_time: {$req_time}; opts: {$opts_json}";
$this->log($msg);
if ($this->raise_fopen_exception) {
throw new Exception($msg);
} else {
$resp_data['error'] = true;
$resp_data['error_msg'] = $msg;
}
} else {
$this->log("Getting metadata...");
$resp_data['meta'] = stream_get_meta_data($stream);
$this->log("Getting response...");
$resp_data['body'] = stream_get_contents($stream);
$this->log("Closing stream...");
fclose($stream);
}
if ($this->debug) {
$req_time = static::calc_time_passed($start_time);
$this->log(sprintf("Request time for \"%s %s\": %f", $opts['http']['method'], $url, $req_time));
}
return $resp_data;
}
/**
* If we get back something that claims to be XML or JSON, parse it as such and assign to $resp['body']
*
* @param string $resp
* @return string|object
* @see Resty::$JSON_TYPES
* @see Resty::$XML_TYPES
*/
protected function processResponseBody($resp) {
if ($this->parse_body === true) {
$header_content_type = isset($resp['headers']['Content-Type']) ? $resp['headers']['Content-Type'] : null;
// If redirected, we use last Content-Type
if (is_array($header_content_type))
{
$header_content_type = end($header_content_type);
}
$content_type = preg_split('/[;\s]+/', $header_content_type);
$content_type = $content_type[0];
if (in_array($content_type, static::$JSON_TYPES) || strpos($content_type,'+json') !== false) {
$this->log("Response body is JSON");
$resp['body_raw'] = $resp['body'];
$resp['body'] = json_decode($resp['body']);
return $resp;
} elseif (in_array($content_type, static::$XML_TYPES) || strpos($content_type,'+xml') !== false) {
$this->log("Response body is XML");
$resp['body_raw'] = $resp['body'];
$resp['body'] = new \SimpleXMLElement($resp['body']);
return $resp;
}
}
$this->log("Response body not parsed");
return $resp;
}
/**
* calculate time passed in microtime
* @param float $start_time should be result of microtime(true)
* @return float the diff between passed microtime and current microtime
*/
protected static function calc_time_passed($start_time) {
$stop_time = microtime(true);
$req_time = $stop_time - $start_time;
return $req_time;
}
protected function log($msg) {
if (!$this->debug) { return; }
if (is_callable($this->logger)) {
$logger = $this->logger;
return $logger($msg);
}
return $this->default_logger($msg);
}
/**
* logging helper
*
* @param mixed $msg
*/
protected function default_logger($msg) {
$line = date(\DateTime::RFC822) . " :: ";
if (is_string($msg)) {
$line .= "{$msg}\n";
} else {
ob_start();
var_dump($msg);
$line = ob_get_clean();
$line .= "\n";
}
if (PHP_SAPI !== 'cli') {
$line = "<pre>$line</pre>\n";
}
return error_log($line);
}
}