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