]> git.mxchange.org Git - friendica.git/blob - src/Network/HTTPRequest.php
Rename "fetchUrl" and "fetchUrlFull" to "fetch" and "fetchFull"
[friendica.git] / src / Network / HTTPRequest.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU APGL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Network;
23
24 use DOMDocument;
25 use DomXPath;
26 use Friendica\App;
27 use Friendica\Core\Config\IConfig;
28 use Friendica\Core\System;
29 use Friendica\Util\Network;
30 use Friendica\Util\Profiler;
31 use Psr\Log\LoggerInterface;
32
33 /**
34  * Performs HTTP requests to a given URL
35  */
36 class HTTPRequest
37 {
38         /** @var LoggerInterface */
39         private $logger;
40         /** @var Profiler */
41         private $profiler;
42         /** @var IConfig */
43         private $config;
44         /** @var string */
45         private $baseUrl;
46
47         public function __construct(LoggerInterface $logger, Profiler $profiler, IConfig $config, App\BaseURL $baseUrl)
48         {
49                 $this->logger   = $logger;
50                 $this->profiler = $profiler;
51                 $this->config   = $config;
52                 $this->baseUrl  = $baseUrl->get();
53         }
54
55         /**
56          * fetches an URL.
57          *
58          * @param string $url        URL to fetch
59          * @param bool   $binary     default false
60          *                           TRUE if asked to return binary results (file download)
61          * @param array  $opts       (optional parameters) assoziative array with:
62          *                           'accept_content' => supply Accept: header with 'accept_content' as the value
63          *                           'timeout' => int Timeout in seconds, default system config value or 60 seconds
64          *                           'http_auth' => username:password
65          *                           'novalidate' => do not validate SSL certs, default is to validate using our CA list
66          *                           'nobody' => only return the header
67          *                           'cookiejar' => path to cookie jar file
68          *                           'header' => header array
69          * @param int    $redirects  The recursion counter for internal use - default 0
70          *
71          * @return CurlResult
72          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
73          */
74         public function get(string $url, bool $binary = false, array $opts = [], int &$redirects = 0)
75         {
76                 $stamp1 = microtime(true);
77
78                 if (strlen($url) > 1000) {
79                         $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
80                         return CurlResult::createErrorCurl(substr($url, 0, 200));
81                 }
82
83                 $parts2     = [];
84                 $parts      = parse_url($url);
85                 $path_parts = explode('/', $parts['path'] ?? '');
86                 foreach ($path_parts as $part) {
87                         if (strlen($part) <> mb_strlen($part)) {
88                                 $parts2[] = rawurlencode($part);
89                         } else {
90                                 $parts2[] = $part;
91                         }
92                 }
93                 $parts['path'] = implode('/', $parts2);
94                 $url           = Network::unparseURL($parts);
95
96                 if (Network::isUrlBlocked($url)) {
97                         $this->logger->info('Domain is blocked.', ['url' => $url]);
98                         return CurlResult::createErrorCurl($url);
99                 }
100
101                 $ch = @curl_init($url);
102
103                 if (($redirects > 8) || (!$ch)) {
104                         return CurlResult::createErrorCurl($url);
105                 }
106
107                 @curl_setopt($ch, CURLOPT_HEADER, true);
108
109                 if (!empty($opts['cookiejar'])) {
110                         curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
111                         curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
112                 }
113
114                 // These settings aren't needed. We're following the location already.
115                 //      @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
116                 //      @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
117
118                 if (!empty($opts['accept_content'])) {
119                         curl_setopt(
120                                 $ch,
121                                 CURLOPT_HTTPHEADER,
122                                 ['Accept: ' . $opts['accept_content']]
123                         );
124                 }
125
126                 if (!empty($opts['header'])) {
127                         curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
128                 }
129
130                 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
131                 @curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
132
133                 $range = intval($this->config->get('system', 'curl_range_bytes', 0));
134
135                 if ($range > 0) {
136                         @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
137                 }
138
139                 // Without this setting it seems as if some webservers send compressed content
140                 // This seems to confuse curl so that it shows this uncompressed.
141                 /// @todo  We could possibly set this value to "gzip" or something similar
142                 curl_setopt($ch, CURLOPT_ENCODING, '');
143
144                 if (!empty($opts['headers'])) {
145                         @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
146                 }
147
148                 if (!empty($opts['nobody'])) {
149                         @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
150                 }
151
152                 if (!empty($opts['timeout'])) {
153                         @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
154                 } else {
155                         $curl_time = $this->config->get('system', 'curl_timeout', 60);
156                         @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
157                 }
158
159                 // by default we will allow self-signed certs
160                 // but you can override this
161
162                 $check_cert = $this->config->get('system', 'verifyssl');
163                 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
164
165                 if ($check_cert) {
166                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
167                 }
168
169                 $proxy = $this->config->get('system', 'proxy');
170
171                 if (!empty($proxy)) {
172                         @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
173                         @curl_setopt($ch, CURLOPT_PROXY, $proxy);
174                         $proxyuser = $this->config->get('system', 'proxyuser');
175
176                         if (!empty($proxyuser)) {
177                                 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
178                         }
179                 }
180
181                 if ($this->config->get('system', 'ipv4_resolve', false)) {
182                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
183                 }
184
185                 if ($binary) {
186                         @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
187                 }
188
189                 // don't let curl abort the entire application
190                 // if it throws any errors.
191
192                 $s         = @curl_exec($ch);
193                 $curl_info = @curl_getinfo($ch);
194
195                 // Special treatment for HTTP Code 416
196                 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
197                 if (($curl_info['http_code'] == 416) && ($range > 0)) {
198                         @curl_setopt($ch, CURLOPT_RANGE, '');
199                         $s         = @curl_exec($ch);
200                         $curl_info = @curl_getinfo($ch);
201                 }
202
203                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
204
205                 if ($curlResponse->isRedirectUrl()) {
206                         $redirects++;
207                         $this->logger->notice('Curl redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
208                         @curl_close($ch);
209                         return $this->get($curlResponse->getRedirectUrl(), $binary, $opts, $redirects);
210                 }
211
212                 @curl_close($ch);
213
214                 $this->profiler->saveTimestamp($stamp1, 'network', System::callstack());
215
216                 return $curlResponse;
217         }
218
219         /**
220          * Send POST request to $url
221          *
222          * @param string $url       URL to post
223          * @param mixed  $params    array of POST variables
224          * @param array  $headers   HTTP headers
225          * @param int    $redirects Recursion counter for internal use - default = 0
226          * @param int    $timeout   The timeout in seconds, default system config value or 60 seconds
227          *
228          * @return CurlResult The content
229          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230          */
231         public function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
232         {
233                 $stamp1 = microtime(true);
234
235                 if (Network::isUrlBlocked($url)) {
236                         $this->logger->info('Domain is blocked.' . ['url' => $url]);
237                         return CurlResult::createErrorCurl($url);
238                 }
239
240                 $ch = curl_init($url);
241
242                 if (($redirects > 8) || (!$ch)) {
243                         return CurlResult::createErrorCurl($url);
244                 }
245
246                 $this->logger->debug('Post_url: start.', ['url' => $url]);
247
248                 curl_setopt($ch, CURLOPT_HEADER, true);
249                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
250                 curl_setopt($ch, CURLOPT_POST, 1);
251                 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
252                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
253
254                 if ($this->config->get('system', 'ipv4_resolve', false)) {
255                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
256                 }
257
258                 if (intval($timeout)) {
259                         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
260                 } else {
261                         $curl_time = $this->config->get('system', 'curl_timeout', 60);
262                         curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
263                 }
264
265                 if (!empty($headers)) {
266                         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
267                 }
268
269                 $check_cert = $this->config->get('system', 'verifyssl');
270                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
271
272                 if ($check_cert) {
273                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
274                 }
275
276                 $proxy = $this->config->get('system', 'proxy');
277
278                 if (!empty($proxy)) {
279                         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
280                         curl_setopt($ch, CURLOPT_PROXY, $proxy);
281                         $proxyuser = $this->config->get('system', 'proxyuser');
282                         if (!empty($proxyuser)) {
283                                 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
284                         }
285                 }
286
287                 // don't let curl abort the entire application
288                 // if it throws any errors.
289
290                 $s = @curl_exec($ch);
291
292                 $curl_info = curl_getinfo($ch);
293
294                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
295
296                 if ($curlResponse->isRedirectUrl()) {
297                         $redirects++;
298                         $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
299                         curl_close($ch);
300                         return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
301                 }
302
303                 curl_close($ch);
304
305                 $this->profiler->saveTimestamp($stamp1, 'network', System::callstack());
306
307                 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
308                 if ($curlResponse->getReturnCode() == 417) {
309                         $redirects++;
310
311                         if (empty($headers)) {
312                                 $headers = ['Expect:'];
313                         } else {
314                                 if (!in_array('Expect:', $headers)) {
315                                         array_push($headers, 'Expect:');
316                                 }
317                         }
318                         $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
319                         return $this->post($url, $params, $headers, $redirects, $timeout);
320                 }
321
322                 $this->logger->debug('Post_url: End.', ['url' => $url]);
323
324                 return $curlResponse;
325         }
326
327         /**
328          * Returns the original URL of the provided URL
329          *
330          * This function strips tracking query params and follows redirections, either
331          * through HTTP code or meta refresh tags. Stops after 10 redirections.
332          *
333          * @todo  Remove the $fetchbody parameter that generates an extraneous HEAD request
334          *
335          * @see   ParseUrl::getSiteinfo
336          *
337          * @param string $url       A user-submitted URL
338          * @param int    $depth     The current redirection recursion level (internal)
339          * @param bool   $fetchbody Wether to fetch the body or not after the HEAD requests
340          * @return string A canonical URL
341          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
342          */
343         public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
344         {
345                 $url = Network::stripTrackingQueryParams($url);
346
347                 if ($depth > 10) {
348                         return $url;
349                 }
350
351                 $url = trim($url, "'");
352
353                 $stamp1 = microtime(true);
354
355                 $ch = curl_init();
356                 curl_setopt($ch, CURLOPT_URL, $url);
357                 curl_setopt($ch, CURLOPT_HEADER, 1);
358                 curl_setopt($ch, CURLOPT_NOBODY, 1);
359                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
360                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
361                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
362
363                 curl_exec($ch);
364                 $curl_info = @curl_getinfo($ch);
365                 $http_code = $curl_info['http_code'];
366                 curl_close($ch);
367
368                 $this->profiler->saveTimestamp($stamp1, "network", System::callstack());
369
370                 if ($http_code == 0) {
371                         return $url;
372                 }
373
374                 if (in_array($http_code, ['301', '302'])) {
375                         if (!empty($curl_info['redirect_url'])) {
376                                 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
377                         } elseif (!empty($curl_info['location'])) {
378                                 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
379                         }
380                 }
381
382                 // Check for redirects in the meta elements of the body if there are no redirects in the header.
383                 if (!$fetchbody) {
384                         return $this->finalUrl($url, ++$depth, true);
385                 }
386
387                 // if the file is too large then exit
388                 if ($curl_info["download_content_length"] > 1000000) {
389                         return $url;
390                 }
391
392                 // if it isn't a HTML file then exit
393                 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
394                         return $url;
395                 }
396
397                 $stamp1 = microtime(true);
398
399                 $ch = curl_init();
400                 curl_setopt($ch, CURLOPT_URL, $url);
401                 curl_setopt($ch, CURLOPT_HEADER, 0);
402                 curl_setopt($ch, CURLOPT_NOBODY, 0);
403                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
404                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
405                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
406
407                 $body = curl_exec($ch);
408                 curl_close($ch);
409
410                 $this->profiler->saveTimestamp($stamp1, "network", System::callstack());
411
412                 if (trim($body) == "") {
413                         return $url;
414                 }
415
416                 // Check for redirect in meta elements
417                 $doc = new DOMDocument();
418                 @$doc->loadHTML($body);
419
420                 $xpath = new DomXPath($doc);
421
422                 $list = $xpath->query("//meta[@content]");
423                 foreach ($list as $node) {
424                         $attr = [];
425                         if ($node->attributes->length) {
426                                 foreach ($node->attributes as $attribute) {
427                                         $attr[$attribute->name] = $attribute->value;
428                                 }
429                         }
430
431                         if (@$attr["http-equiv"] == 'refresh') {
432                                 $path = $attr["content"];
433                                 $pathinfo = explode(";", $path);
434                                 foreach ($pathinfo as $value) {
435                                         if (substr(strtolower($value), 0, 4) == "url=") {
436                                                 return $this->finalUrl(substr($value, 4), ++$depth);
437                                         }
438                                 }
439                         }
440                 }
441
442                 return $url;
443         }
444
445         /**
446          * Curl wrapper
447          *
448          * If binary flag is true, return binary results.
449          * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
450          * to preserve cookies from one request to the next.
451          *
452          * @param string $url             URL to fetch
453          * @param bool   $binary          default false
454          *                                TRUE if asked to return binary results (file download)
455          * @param int    $timeout         Timeout in seconds, default system config value or 60 seconds
456          * @param string $accept_content  supply Accept: header with 'accept_content' as the value
457          * @param string $cookiejar       Path to cookie jar file
458          * @param int    $redirects       The recursion counter for internal use - default 0
459          *
460          * @return string The fetched content
461          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
462          */
463         public function fetch(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
464         {
465                 $ret = $this->fetchFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
466
467                 return $ret->getBody();
468         }
469
470         /**
471          * Curl wrapper with array of return values.
472          *
473          * Inner workings and parameters are the same as @ref fetchUrl but returns an array with
474          * all the information collected during the fetch.
475          *
476          * @param string $url             URL to fetch
477          * @param bool   $binary          default false
478          *                                TRUE if asked to return binary results (file download)
479          * @param int    $timeout         Timeout in seconds, default system config value or 60 seconds
480          * @param string $accept_content  supply Accept: header with 'accept_content' as the value
481          * @param string $cookiejar       Path to cookie jar file
482          * @param int    $redirects       The recursion counter for internal use - default 0
483          *
484          * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
485          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
486          */
487         public function fetchFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
488         {
489                 return $this->get(
490                         $url,
491                         $binary,
492                         [
493                                 'timeout'        => $timeout,
494                                 'accept_content' => $accept_content,
495                                 'cookiejar'      => $cookiejar
496                         ],
497                         $redirects
498                 );
499         }
500
501         /**
502          * Returns the current UserAgent as a String
503          *
504          * @return string the UserAgent as a String
505          */
506         public function getUserAgent()
507         {
508                 return
509                         FRIENDICA_PLATFORM . " '" .
510                         FRIENDICA_CODENAME . "' " .
511                         FRIENDICA_VERSION . '-' .
512                         DB_UPDATE_VERSION . '; ' .
513                         $this->baseUrl;
514         }
515 }