/
WireHttp.php
1990 lines (1778 loc) · 59.5 KB
/
WireHttp.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
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
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php namespace ProcessWire;
/**
* ProcessWire HTTP tools
*
* Provides capability for sending POST/GET requests to URLs
*
* #pw-summary WireHttp enables you to send HTTP requests to URLs, download files, and more.
* #pw-var $http
* #pw-instantiate $http = new WireHttp();
* #pw-body =
* ~~~~~
* // Get the contents of a URL
* $response = $http->get("http://domain.com/path/");
* if($response !== false) {
* echo "Successful response: " . $sanitizer->entities($response);
* } else {
* echo "HTTP request failed: " . $http->getError();
* }
* ~~~~~
* #pw-body
*
* Thanks to @horst for his assistance with several methods in this class.
*
* ProcessWire 3.x, Copyright 2022 by Ryan Cramer
* https://processwire.com
*
* @method bool|string send($url, $data = array(), $method = 'POST', array $options = array())
* @method int sendFile($filename, array $options = array(), array $headers = array())
* @method string download($fromURL, $toFile, array $options = array())
*
*
*/
class WireHttp extends Wire {
const debug = false;
/**
* Default timeout seconds for send() methods: GET, POST, etc.
*
* #pw-internal
*
*/
const defaultTimeout = 4.5;
/**
* Default timeout seconds for download() methods.
*
* #pw-internal
*
*/
const defaultDownloadTimeout = 50;
/**
* Default content-type header for POST requests
*
*/
const defaultPostContentType = 'application/x-www-form-urlencoded; charset=utf-8';
/**
* Default value for request $headers, when reset
*
*/
protected $defaultHeaders = array(
'charset' => 'utf-8',
);
/**
* Schemes we are allowed to use
*
*/
protected $allowSchemes = array('http', 'https');
/**
* HTTP methods we are allowed to use
*
*/
protected $allowHttpMethods = array('GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'PATCH');
/**
* Headers to include in the request
*
*/
protected $headers = array();
/**
* HTTP codes
*
* @var array
*
*/
protected $httpCodes = array(
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing (WebDAV; RFC 2518)',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status (WebDAV; RFC 4918)',
208 => 'Already Reported (WebDAV; RFC 5842)',
226 => 'IM Used (RFC 3229)',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => 'Switch Proxy',
307 => 'Temporary Redirect',
308 => 'Permanent Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
419 => 'Authentication Timeout (not in RFC 2616)',
420 => 'Enhance Your Calm ',
422 => 'Unprocessable Entity (WebDAV; RFC 4918)',
423 => 'Locked (WebDAV; RFC 4918)',
424 => 'Failed Dependency (WebDAV; RFC 4918)',
426 => 'Upgrade Required',
428 => 'Precondition Required (RFC 6585)',
429 => 'Too Many Requests (RFC 6585)',
431 => 'Request Header Fields Too Large (RFC 6585)',
440 => 'Login Timeout (Microsoft)',
444 => 'No Response (Nginx)',
449 => 'Retry With (Microsoft)',
450 => 'Blocked by Windows Parental Controls (Microsoft)',
451 => 'Unavailable For Legal Reasons (Internet draft)',
494 => 'Request Header Too Large (Nginx)',
495 => 'Cert Error (Nginx)',
496 => 'No Cert (Nginx)',
497 => 'HTTP to HTTPS (Nginx)',
498 => 'Token expired/invalid (Esri)',
499 => 'Client Closed Request (Nginx)',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates (RFC 2295)',
507 => 'Insufficient Storage (WebDAV; RFC 4918)',
508 => 'Loop Detected (WebDAV; RFC 5842)',
509 => 'Bandwidth Limit Exceeded (Apache bw/limited extension)[25]',
510 => 'Not Extended (RFC 2774)',
511 => 'Network Authentication Required (RFC 6585)',
520 => 'Origin Error (Cloudflare)',
521 => 'Web server is down (Cloudflare)',
522 => 'Connection timed out (Cloudflare)',
523 => 'Proxy Declined Request (Cloudflare)',
524 => 'A timeout occurred (Cloudflare)',
598 => 'Network read timeout error (Unknown)',
599 => 'Network connect timeout error (Unknown)',
);
/**
* Seconds till timing out on a connection
*
* @var float|null Contains a float value when set, or a NULL when not set (indicating default should be used)
*
*/
protected $timeout = null;
/**
* Last HTTP code
*
* @var int
*
*/
protected $httpCode = 0;
/**
* Last HTTP code text
*
* @var int
*
*/
protected $httpCodeText = '';
/**
* Data to send in the request
*
*/
protected $data = array();
/**
* Raw data, when data is not an array
*
*/
protected $rawData = null;
/**
* Last response header
*
*/
protected $responseHeader = array();
/**
* Last response headers parsed into key => value properties
*
* Note that keys are always lowercase
*
*/
protected $responseHeaders = array();
/**
* Last response headers parsed into key => value properties, where value is always array
*
* Note that keys are always lowercase
*
*/
protected $responseHeaderArrays = array();
/**
* Cookies to set for next curl get/post request
*
* @var array
*
*/
protected $setCookies = array();
/**
* Error messages
*
*/
protected $error = array();
/**
* Whether the system supports CURL
*
* @var bool
*
*/
protected $hasCURL = false;
/**
* Whether the system supports fopen of URLs
*
* @var bool
*
*/
protected $hasFopen = false;
/**
* Last type used for send (fopen, socket, curl)
*
* @var string
*
*/
protected $lastSendType = '';
/**
* Options to pass to $sanitizer->url('url', $options) in WireHttp::validateURL() method
*
* Can be modified with the setValidateURLOptions() method.
*
* @var array
*
*/
protected $validateURLOptions = array(
'allowRelative' => false,
'requireScheme' => true,
'stripQuotes' => false,
'encodeSpace' => true,
'throw' => true,
);
/**
* Construct/initialize
*
*/
public function __construct() {
$this->hasCURL = function_exists('curl_init') && !ini_get('safe_mode'); // && !ini_get('open_basedir');
$this->hasFopen = ini_get('allow_url_fopen');
$this->resetRequest();
$this->resetResponse();
}
/**
* Send a POST request to a URL
*
* ~~~~~
* $http = new WireHttp();
* $response = $http->post("http://domain.com/path/", [
* 'foo' => 'bar',
* ]);
* if($response !== false) {
* echo "Successful response: " . $sanitizer->entities($response);
* } else {
* echo "HTTP request failed: " . $http->getError();
* }
* ~~~~~
*
* #pw-group-HTTP-requests
*
* @param string $url URL to post to (including http:// or https://)
* @param mixed $data Associative array of data to send (if not already set before), or raw data to send.
* @param array $options Optional options to modify default behavior, see the send() method for details.
* @return bool|string False on failure or string of contents received on success.
* @see WireHttp::send(), WireHttp::get(), WireHttp::head()
*
*/
public function post($url, $data = array(), array $options = array()) {
if(!isset($this->headers['content-type'])) $this->setHeader('content-type', self::defaultPostContentType);
return $this->send($url, $data, 'POST', $options);
}
/**
* Send a GET request to URL
*
* ~~~~~
* $http = new WireHttp();
* $response = $http->get("http://domain.com/path/", [
* 'foo' => 'bar',
* ]);
* if($response !== false) {
* echo "Successful response: " . $sanitizer->entities($response);
* } else {
* echo "HTTP request failed: " . $http->getError();
* }
* ~~~~~
*
* #pw-group-HTTP-requests
*
* @param string $url URL to send request to (including http:// or https://)
* @param mixed $data Array of data to send (if not already set before) or raw data to send.
* @param array $options Optional options to modify default behavior, see the send() method for details.
* @return bool|string False on failure or string of contents received on success.
* @see WireHttp::send(), WireHttp::post(), WireHttp::head(), WireHttp::getJSON()
*
*/
public function get($url, $data = array(), array $options = array()) {
return $this->send($url, $data, 'GET', $options);
}
/**
* Send to a URL that responds with JSON (using GET request) and return the resulting array or object.
*
* #pw-group-HTTP-requests
*
* @param string $url URL to send request to (including http:// or https://)
* @param bool $assoc Default is to return an array (specified by TRUE). If you want an object instead, specify FALSE.
* @param mixed $data Array of data to send (if not already set before) or raw data to send
* @param array $options Optional options to modify default behavior, see the send() method for details.
* @return bool|array|object False on failure or an array or object on success.
* @see WireHttp::send(), WireHttp::get()
*
*/
public function getJSON($url, $assoc = true, $data = array(), array $options = array()) {
return json_decode($this->get($url, $data, $options), $assoc);
}
/**
* Send to a URL using a HEAD request
*
* #pw-group-HTTP-requests
*
* @param string $url URL to request (including http:// or https://)
* @param mixed $data Array of data to send (if not already set before) or raw data to send
* @param array $options Optional options to modify default behavior, see the send() method for details.
* @return bool|array False on failure or Array with ResponseHeaders on success.
* @see WireHttp::send(), WireHttp::post(), WireHttp::get()
*
*/
public function head($url, $data = array(), array $options = array()) {
$this->send($url, $data, 'HEAD', $options);
$responseHeaders = $this->getResponseHeaders();
return is_array($responseHeaders) ? $responseHeaders : false;
}
/**
* Send to a URL using a HEAD request and return the status code
*
* #pw-group-HTTP-requests
*
* @param string $url URL to request (including http:// or https://)
* @param mixed $data Array of data to send (if not already set before) or raw data
* @param bool $textMode When true function will return a string rather than integer, see the statusText() method.
* @param array $options Optional options to modify default behavior, see the send() method for details.
* @return bool|integer|string False on failure or integer or string of status code (200|404|etc) on success.
* @see WireHttp::send(), WireHttp::statusText()
*
*/
public function status($url, $data = array(), $textMode = false, array $options = array()) {
$this->send($url, $data, 'HEAD', $options);
return $this->getHttpCode($textMode);
}
/**
* Send to a URL using HEAD and return the status code and text like "200 OK"
*
* #pw-group-HTTP-requests
*
* @param string $url URL to request (including http:// or https://)
* @param mixed $data Array of data to send (if not already set before) or raw data
* @param array $options Optional options to modify default behavior, see the send() method for details.
* @return bool|string False on failure or string of status code + text on success.
* Example: "200 OK', "302 Found", "404 Not Found"
* @see WireHttp::send(), WireHttp::status()
*
*/
public function statusText($url, $data = array(), array $options = array()) {
return $this->status($url, $data, true, $options);
}
/**
* Send the given $data array to a URL using given method (i.e. POST, GET, PUT, DELETE, etc.)
*
* This method handles the implementation for the get/post/head/etc. methods. It is preferable to use one
* of those dedicated request methods rather than this one.
*
* #pw-group-HTTP-requests
*
* @param string $url URL to send to (including http:// or https://).
* @param array $data Array of data to send (if not already set before).
* @param string $method Method to use (either POST, GET, PUT, DELETE or others as needed).
* @param array|string $options Options to modify behavior. (This argument added in 3.0.124):
* - `use` (string|array): What types(s) to use, one of 'fopen', 'curl', 'socket' to allow only
* that type. Or in 3.0.192+ this may be an array of types to attempt them in order.
* Default in 3.0.192+ is [ 'curl', 'fopen', 'socket' ]. In prior versions default is 'auto'
* which attempts: fopen, curl, then socket.
* @return bool|string False on failure or string of contents received on success.
*
*/
public function ___send($url, $data = array(), $method = 'POST', array $options = array()) {
$options = $this->sendOptions($url, $options);
$url = $this->validateURL($url, false);
$result = false;
$error = array();
if(empty($url)) return false;
$this->resetResponse();
if(!empty($data)) $this->setData($data);
if(!isset($this->headers['user-agent'])) $this->setHeader('user-agent', $this->getUserAgent());
if(!in_array(strtoupper($method), $this->allowHttpMethods)) $method = 'POST';
foreach($options['use'] as $use) {
$use = strtolower($use);
if($use === 'curl' && !$options['allowCURL']) {
$error[] = 'CURL is not available';
} else if($use === 'curl') {
$result = $this->sendCURL($url, $method, $options);
} else if($use === 'fopen' && !$options['allowFopen']) {
$error[] = 'fopen is not available';
} else if($use === 'fopen') {
$result = $this->sendFopen($url, $method, $options);
} else if($use === 'socket') {
$result = $this->sendSocket($options['_url'], $method);
} else {
$error[] = "unrecognized type: $use";
}
if($result !== false) break;
}
if($result === false && count($error) && count($options['use']) < 3) {
// populate type errors only if request failed and specific options requested
$this->error = array_merge($this->error, $error);
}
return $result;
}
/**
* Prepare options for send method(s)
*
* @param string $url
* @param array $options
* @return array
*
*/
protected function sendOptions($url, array $options) {
$defaults = array(
'use' => array('curl', 'fopen', 'socket'),
'proxy' => '',
'_url' => $url, // original unmodified URL
'allowFopen' => true,
'allowCURL' => true,
// Options specific to fopen:
// -----------------------------------------------------------
/*
'fopen' => array(
'http' => array(
'method' => '',
'timeout' => 0,
'content' => '',
'header' => '',
'proxy' => '',
),
)
*/
// Options specific to CURL:
// -----------------------------------------------------------
/*
'curl' => array(
'http' => array(
'proxy' => '',
),
'setopt' => array(
CURLOPT_OPTION => 'option value',
),
),
'curl_setopt' => array(
// recognized alias of options[curl][setopt]
CURLOPT_OPTION => 'option value',
),
*/
// http option recognized by some types for legacy purposes
// -----------------------------------------------------------
/*
'http' => array(
'proxy' => '',
),
*/
// Legacy options that have been replaced
// -----------------------------------------------------------
// 'fallback' => true, // 'auto', 'socket' or 'curl'
// 'timeout' => 30,
);
// if legacy 'fallback' option used then migrate it to 'use' option
if(!empty($options['fallback']) && is_string($options['fallback'])) {
if(empty($options['use']) || $options['use'] === 'auto') {
// duplicate behavior in versions prior to 3.0.192
$options['use'] = array('fopen', $options['fallback']);
}
}
$options = array_merge($defaults, $options);
if($options['use'] === 'auto') $options['use'] = $defaults['use']; // auto forces default
if(!is_array($options['use'])) $options['use'] = array($options['use']);
if(empty($options['use'])) $options['use'] = $defaults['use'];
$allowFopen = $this->hasFopen;
if($allowFopen && stripos($url, 'https://') === 0 && !extension_loaded('openssl')) $allowFopen = false;
$options['allowFopen'] = $allowFopen;
$allowCURL = $this->hasCURL && (version_compare(PHP_VERSION, '5.5') >= 0 || $options['use'] === 'curl'); // #849
$options['allowCURL'] = $allowCURL;
return $options;
}
/**
* Send using fopen
*
* @param string $url
* @param string $method
* @param array $options Options specific to fopen should be specified in [ 'fopen' => [ ... ] ]
*
* @return bool|string
*
*/
protected function sendFopen($url, $method = 'POST', array $options = array()) {
$this->resetResponse();
$this->lastSendType = 'fopen';
if(!empty($this->data)) {
$content = http_build_query($this->data);
if(($method === 'GET' || $method === 'HEAD') && strlen($content)) {
$url .= (strpos($url, '?') === false ? '?' : '&') . $content;
$content = '';
}
} else if(!empty($this->rawData)) {
$content = $this->rawData;
} else {
$content = '';
}
$this->setHeader('content-length', strlen($content));
$header = '';
foreach($this->headers as $key => $value) {
$header .= "$key: $value\r\n";
}
$header .= "Connection: close\r\n";
$http = array(
'method' => $method,
'timeout' => $this->getTimeout(),
'content' => $content,
'header' => $header,
);
if(!empty($options['proxy'])) $http['proxy'] = $options['proxy'];
// merge fopen http options array if present, as well as any other options specified to fopen stream_context_create
if(isset($options['fopen']) && !empty($options['fopen']['http'])) {
// allow adding on to http option
$http = array_merge($options['fopen']['http'], $http);
} else if(!empty($options['http']) && is_array($options['http'])) {
// if http array specified outside fopen index
$http = array_merge($options['http'], $http);
}
$fopenOptions = array('http' => $http);
if(isset($options['fopen'])) $fopenOptions = array_merge($options['fopen'], $fopenOptions);
set_error_handler(array($this, '_errorHandler'));
$context = stream_context_create($fopenOptions);
$fp = fopen($url, 'rb', false, $context);
restore_error_handler();
if(isset($http_response_header)) $this->setResponseHeader($http_response_header);
if($fp) {
$result = @stream_get_contents($fp);
} else {
$code = $this->getHttpCode();
if($code && $code >= 400 && isset($this->httpCodes[$code])) {
// known http error code, no need to fallback to sockets
$result = false;
} else if($code && $code >= 200 && $code < 300) {
// PR #1281: known http success status code, no need to fallback to sockets
$result = true;
} else {
$result = false;
}
}
return $result;
}
/**
* Send using CURL
*
* @param string $url
* @param string $method
* @param array $options
* @return bool|string
*
*/
protected function sendCURL($url, $method = 'POST', $options = array()) {
$this->resetResponse();
$this->lastSendType = 'curl';
$timeout = isset($options['timeout']) ? (float) $options['timeout'] : $this->getTimeout();
$postMethods = array('POST', 'PUT', 'DELETE', 'PATCH'); // methods for CURLOPT_POSTFIELDS
$isPost = in_array($method, $postMethods);
$contentType = isset($this->headers['content-type']) ? $this->headers['content-type'] : '';
$proxy = '';
if(!empty($options['proxy'])) {
$proxy = $options['proxy'];
} else if(isset($options['curl']) && !empty($options['curl']['http']['proxy'])) {
$proxy = $options['curl']['http']['proxy'];
} else if(isset($options['http']) && !empty($options['http']['proxy'])) {
$proxy = $options['http']['proxy'];
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERAGENT, $this->getUserAgent());
if(!ini_get('open_basedir')) curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
if(version_compare(PHP_VERSION, '5.6') >= 0) {
// CURLOPT_SAFE_UPLOAD value is default true (setopt not necessary)
// and PHP 7+ removes this option
} else if(version_compare(PHP_VERSION, '5.5') >= 0) {
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
} else {
// not reachable: version blocked before sendCURL call
}
if(count($this->headers)) {
if($isPost && !empty($this->data) && $contentType === self::defaultPostContentType) {
// CURL does not work w/default POST content-type when sending POST variables array
$this->headers['content-type'] = 'multipart/form-data; charset=utf-8';
}
$headers = array();
foreach($this->headers as $name => $value) {
$headers[] = "$name: $value";
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
if($method === 'POST') {
curl_setopt($curl, CURLOPT_POST, true);
} else if($method === 'GET') {
curl_setopt($curl, CURLOPT_HTTPGET, true);
} else if($method === 'HEAD') {
curl_setopt($curl, CURLOPT_NOBODY, true);
} else {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
}
// note: CURLOPT_PUT removed because it also requires CURLOPT_INFILE and CURLOPT_INFILESIZE.
if($proxy) curl_setopt($curl, CURLOPT_PROXY, $proxy);
if(!empty($this->data)) {
if($isPost) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data);
} else {
$content = http_build_query($this->data);
if(strlen($content)) $url .= (strpos($url, '?') === false ? '?' : '&') . $content;
}
} else if(!empty($this->rawData)) {
if($isPost) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $this->rawData);
} else {
throw new WireException("Raw data option with CURL not supported for $method");
}
}
// called by CURL for each header and populates the $responseHeaders var
$responseHeaders = array();
curl_setopt($curl, CURLOPT_HEADERFUNCTION, function($curl, $header) use(&$responseHeaders) {
if($curl) { /* ignore */ }
$length = strlen($header);
$header = explode(':', $header, 2);
if(count($header) < 2) return $length; // ignore invalid headers
$name = strtolower(trim($header[0]));
$value = trim($header[1]);
if(!array_key_exists($name, $responseHeaders)) {
$responseHeaders[$name] = array($value);
} else {
$responseHeaders[$name][] = $value;
}
return $length;
});
curl_setopt($curl, CURLOPT_URL, $url);
$cookie = empty($options['cookie']) ? $this->setCookies : $options['cookie'];
if(!empty($cookie)) {
if(is_array($cookie)) $cookie = http_build_query($cookie, '', '; ', PHP_QUERY_RFC3986);
if(is_string($cookie) && !empty($cookie)) curl_setopt($curl, CURLOPT_COOKIE, $cookie);
}
// custom CURL options provided in $options array
if(!empty($options['curl']) && !empty($options['curl']['setopt'])) {
$setopts = $options['curl']['setopt'];
} else if(!empty($options['curl_setopt'])) {
$setopts = $options['curl_setopt'];
} else {
$setopts = null;
}
if(is_array($setopts)) {
foreach($setopts as $opt => $optVal) {
curl_setopt($curl, $opt, $optVal);
}
}
$result = curl_exec($curl);
if($result === false) {
$this->error[] = curl_error($curl);
$this->httpCode = 0;
} else {
$this->setResponseHeaderValues($responseHeaders);
$this->httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
}
curl_close($curl);
return $result;
}
/**
* Alternate method of sending when allow_url_fopen isn't allowed
*
* @param string $url
* @param string $method
* @param array $options Optional settings:
* - timeout: number of seconds to timeout
* @return bool|string
*
*/
protected function sendSocket($url, $method = 'POST', $options = array()) {
static $level = 0; // recursion level
$this->resetResponse();
$this->lastSendType = 'socket';
$timeout = isset($options['timeout']) ? (float) $options['timeout'] : $this->getTimeout();
if(!in_array(strtoupper($method), $this->allowHttpMethods)) $method = 'POST';
$info = parse_url($url);
$host = $info['host'];
$path = empty($info['path']) ? '/' : $info['path'];
$query = empty($info['query']) ? '' : '?' . $info['query'];
if($info['scheme'] == 'https') {
$port = 443;
$scheme = 'ssl://';
} else {
$port = empty($info['port']) ? 80 : $info['port'];
$scheme = '';
}
if(!empty($this->data)) {
$content = http_build_query($this->data);
if($method === 'GET' && strlen($content)) {
$query .= (strpos($query, '?') === false ? '?' : '&') . $content;
$content = '';
}
} else if(!empty($this->rawData)) {
$content = $this->rawData;
} else {
$content = '';
}
$this->setHeader('content-length', strlen($content));
$proto = $this->wire()->config->serverProtocol;
$request = "$method $path$query $proto\r\nHost: $host\r\n";
foreach($this->headers as $key => $value) {
$request .= "$key: $value\r\n";
}
$request .= "Connection: close\r\n";
$response = '';
$errno = '';
$errstr = '';
set_error_handler(array($this, '_errorHandler'));
if(false !== ($fs = fsockopen($scheme . $host, $port, $errno, $errstr, $timeout))) {
fwrite($fs, "$request\r\n$content");
while(!feof($fs)) {
// get 1 tcp-ip packet per iteration
$response .= fgets($fs, 1160);
}
fclose($fs);
}
restore_error_handler();
if(strlen($errstr)) $this->error[] = $errno . ': ' . $errstr;
// skip past the headers in the response, so that it is consistent with
// the results returned by the regular send() method
$pos = strpos($response, "\r\n\r\n");
$this->setResponseHeader(explode("\r\n", substr($response, 0, $pos)));
$response = substr($response, $pos+4);
// if response resulted in a redirect, follow it
if($this->httpCode == 301 || $this->httpCode == 302) {
// follow redirects
$location = $this->getResponseHeader('location');
if(!empty($location) && ++$level <= 5) {
if(strpos($location, '://') === false && preg_match('{(https?://[^/]+)}i', $url, $matches)) {
// if location is relative, convert to absolute
$location = $matches[1] . '/' . ltrim($location, '/');
}
return $this->sendSocket($location, $method);
}
}
return $response;
}
/**
* Download a file from a URL and save it locally
*
* First it will attempt to use CURL. If that fails, it will try `fopen()`,
* unless you specify the `use` option in `$options`.
*
* #pw-group-files
*
* @param string $fromURL URL of file you want to download.
* @param string $toFile Filename you want to save it to (including full path).
* @param array $options Optional aptions array for PHP's stream_context_create(), plus these optional options:
* - `use` or `useMethod` (string): Specify "curl", "fopen" or "socket" to force a specific method (default=auto-detect).
* - `timeout` (float): Number of seconds till timeout.
* @return string Filename that was downloaded (including full path).
* @throws WireException All error conditions throw exceptions.
* @todo update the use option to support array like the send() method
*
*/
public function ___download($fromURL, $toFile, array $options = array()) {
$fromURL = $this->validateURL($fromURL, true);
$http = stripos($fromURL, 'http://') === 0;
$https = stripos($fromURL, 'https://') === 0;
$allowMethods = array('curl', 'fopen', 'socket');
$triedMethods = array();
if(!$http && !$https) {
throw new WireException($this->_('Download URLs must begin with http:// or https://'));
}
if(!isset($options['timeout'])) {
if(is_null($this->timeout)) {
$options['timeout'] = self::defaultDownloadTimeout;
} else {
$options['timeout'] = $this->timeout;
}
}
// the 'use' option can also be specified as a 'useMethod' option
if(isset($options['useMethod']) && !isset($options['use'])) {
$options['use'] = $options['useMethod'];
}
if(isset($options['use'])) {
$useMethod = $options['use'];
unset($options['use']);
if(!in_array($useMethod, $allowMethods)) throw new WireException("Unrecognized useMethod: $useMethod");
if($useMethod == 'curl' && !$this->hasCURL) throw new WireException("System does not support CURL");
if($useMethod == 'fopen' && !$this->hasFopen) throw new WireException("System does not support fopen");
} else {
if($this->hasCURL) $useMethod = 'curl';
else if($this->hasFopen) $useMethod = 'fopen';
else $useMethod = 'socket';
}
if(($fp = fopen($toFile, 'wb')) === false) {
throw new WireException($this->_('fopen error for filename:') . ' ' . $toFile);
}
// CURL
if($useMethod == 'curl') {
$triedMethods[] = 'curl';
$result = $this->downloadCURL($fromURL, $fp, $options);
if($result === false && !$this->httpCode) {
$useMethod = $this->hasFopen ? 'fopen' : 'socket';
}
}
// FOPEN
if($useMethod == 'fopen') {
$triedMethods[] = 'fopen';
if($https && !extension_loaded('openssl')) {
// WireHttp::download-OpenSSL extension required but not available, fallback to socket
$useMethod = 'socket';
} else {
$result = $this->downloadFopen($fromURL, $fp, $options);
if($result === false && !$this->httpCode) $useMethod = 'socket';
}
}
// SOCKET
if($useMethod == 'socket') {
$triedMethods[] = 'socket';
$this->downloadSocket($fromURL, $fp, $options);
}
fclose($fp);
$methods = implode(", ", $triedMethods);
if(count($this->error) || ($this->httpCode >= 400 && isset($this->httpCodes[$this->httpCode]))) {
$this->wire('files')->unlink($toFile);
$error = $this->_('File could not be downloaded') . ' ' . htmlentities("($fromURL) ") . $this->getError() . " (tried: $methods)";
throw new WireException($error);
} else {
$bytes = filesize($toFile);
$this->message("Downloaded " . htmlentities($fromURL) . " => $toFile (using: $methods) [$bytes bytes]", Notice::debug);
}
$this->wire('files')->chmod($toFile);
return $toFile;
}
/**
* Download file using CURL
*
* @param string $fromURL
* @param resource $fp Open file pointer
* @param array $options
* @return bool True if successful false if not
*
*/
protected function downloadCURL($fromURL, $fp, array $options) {
$this->resetResponse();