]> git.mxchange.org Git - friendica.git/blob - src/Network/HTTPRequest.php
Merge pull request #10283 from very-ape/fix-message-button
[friendica.git] / src / Network / HTTPRequest.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
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 implements IHTTPRequest
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         /** {@inheritDoc}
56          *
57          * @throws HTTPException\InternalServerErrorException
58          */
59         public function head(string $url, array $opts = [])
60         {
61                 $opts['nobody'] = true;
62
63                 return $this->get($url, $opts);
64         }
65
66         /**
67          * {@inheritDoc}
68          *
69          * @param int $redirects The recursion counter for internal use - default 0
70          *
71          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
72          */
73         public function get(string $url, array $opts = [], &$redirects = 0)
74         {
75                 $stamp1 = microtime(true);
76
77                 if (strlen($url) > 1000) {
78                         $this->logger->debug('URL is longer than 1000 characters.', ['url' => $url, 'callstack' => System::callstack(20)]);
79                         $this->profiler->saveTimestamp($stamp1, 'network');
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                         $this->profiler->saveTimestamp($stamp1, 'network');
99                         return CurlResult::createErrorCurl($url);
100                 }
101
102                 $ch = @curl_init($url);
103
104                 if (($redirects > 8) || (!$ch)) {
105                         $this->profiler->saveTimestamp($stamp1, 'network');
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->getUserAgent());
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                         $this->logger->notice('Wrong option \'headers\' used.');
148                         @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
149                 }
150
151                 if (!empty($opts['nobody'])) {
152                         @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
153                 }
154
155                 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
156
157                 if (!empty($opts['timeout'])) {
158                         @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
159                 } else {
160                         $curl_time = $this->config->get('system', 'curl_timeout', 60);
161                         @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
162                 }
163
164                 // by default we will allow self-signed certs
165                 // but you can override this
166
167                 $check_cert = $this->config->get('system', 'verifyssl');
168                 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
169
170                 if ($check_cert) {
171                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
172                 }
173
174                 $proxy = $this->config->get('system', 'proxy');
175
176                 if (!empty($proxy)) {
177                         @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
178                         @curl_setopt($ch, CURLOPT_PROXY, $proxy);
179                         $proxyuser = $this->config->get('system', 'proxyuser');
180
181                         if (!empty($proxyuser)) {
182                                 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
183                         }
184                 }
185
186                 if ($this->config->get('system', 'ipv4_resolve', false)) {
187                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
188                 }
189
190                 $s         = @curl_exec($ch);
191                 $curl_info = @curl_getinfo($ch);
192
193                 // Special treatment for HTTP Code 416
194                 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
195                 if (($curl_info['http_code'] == 416) && ($range > 0)) {
196                         @curl_setopt($ch, CURLOPT_RANGE, '');
197                         $s         = @curl_exec($ch);
198                         $curl_info = @curl_getinfo($ch);
199                 }
200
201                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
202
203                 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
204                         $redirects++;
205                         $this->logger->notice('Curl redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
206                         @curl_close($ch);
207                         $this->profiler->saveTimestamp($stamp1, 'network');
208                         return $this->get($curlResponse->getRedirectUrl(), $opts, $redirects);
209                 }
210
211                 @curl_close($ch);
212
213                 $this->profiler->saveTimestamp($stamp1, 'network');
214
215                 return $curlResponse;
216         }
217
218         /**
219          * {@inheritDoc}
220          *
221          * @param int $redirects The recursion counter for internal use - default 0
222          *
223          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
224          */
225         public function post(string $url, $params, array $headers = [], int $timeout = 0, &$redirects = 0)
226         {
227                 $stamp1 = microtime(true);
228
229                 if (Network::isUrlBlocked($url)) {
230                         $this->logger->info('Domain is blocked.' . ['url' => $url]);
231                         $this->profiler->saveTimestamp($stamp1, 'network');
232                         return CurlResult::createErrorCurl($url);
233                 }
234
235                 $ch = curl_init($url);
236
237                 if (($redirects > 8) || (!$ch)) {
238                         $this->profiler->saveTimestamp($stamp1, 'network');
239                         return CurlResult::createErrorCurl($url);
240                 }
241
242                 $this->logger->debug('Post_url: start.', ['url' => $url]);
243
244                 curl_setopt($ch, CURLOPT_HEADER, true);
245                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
246                 curl_setopt($ch, CURLOPT_POST, 1);
247                 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
248                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
249
250                 if ($this->config->get('system', 'ipv4_resolve', false)) {
251                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
252                 }
253
254                 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
255
256                 if (intval($timeout)) {
257                         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
258                 } else {
259                         $curl_time = $this->config->get('system', 'curl_timeout', 60);
260                         curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
261                 }
262
263                 if (!empty($headers)) {
264                         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
265                 }
266
267                 $check_cert = $this->config->get('system', 'verifyssl');
268                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
269
270                 if ($check_cert) {
271                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
272                 }
273
274                 $proxy = $this->config->get('system', 'proxy');
275
276                 if (!empty($proxy)) {
277                         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
278                         curl_setopt($ch, CURLOPT_PROXY, $proxy);
279                         $proxyuser = $this->config->get('system', 'proxyuser');
280                         if (!empty($proxyuser)) {
281                                 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
282                         }
283                 }
284
285                 // don't let curl abort the entire application
286                 // if it throws any errors.
287
288                 $s = @curl_exec($ch);
289
290                 $curl_info = curl_getinfo($ch);
291
292                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
293
294                 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
295                         $redirects++;
296                         $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
297                         curl_close($ch);
298                         $this->profiler->saveTimestamp($stamp1, 'network');
299                         return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
300                 }
301
302                 curl_close($ch);
303
304                 $this->profiler->saveTimestamp($stamp1, 'network');
305
306                 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
307                 if ($curlResponse->getReturnCode() == 417) {
308                         $redirects++;
309
310                         if (empty($headers)) {
311                                 $headers = ['Expect:'];
312                         } else {
313                                 if (!in_array('Expect:', $headers)) {
314                                         array_push($headers, 'Expect:');
315                                 }
316                         }
317                         $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
318                         return $this->post($url, $params, $headers, $redirects, $timeout);
319                 }
320
321                 $this->logger->debug('Post_url: End.', ['url' => $url]);
322
323                 return $curlResponse;
324         }
325
326         /**
327          * {@inheritDoc}
328          */
329         public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
330         {
331                 if (Network::isUrlBlocked($url)) {
332                         $this->logger->info('Domain is blocked.', ['url' => $url]);
333                         return $url;
334                 }
335
336                 if (Network::isRedirectBlocked($url)) {
337                         $this->logger->info('Domain should not be redirected.', ['url' => $url]);
338                         return $url;
339                 }
340
341                 $url = Network::stripTrackingQueryParams($url);
342
343                 if ($depth > 10) {
344                         return $url;
345                 }
346
347                 $url = trim($url, "'");
348
349                 $stamp1 = microtime(true);
350
351                 $ch = curl_init();
352                 curl_setopt($ch, CURLOPT_URL, $url);
353                 curl_setopt($ch, CURLOPT_HEADER, 1);
354                 curl_setopt($ch, CURLOPT_NOBODY, 1);
355                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
356                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
357                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
358                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
359
360                 curl_exec($ch);
361                 $curl_info = @curl_getinfo($ch);
362                 $http_code = $curl_info['http_code'];
363                 curl_close($ch);
364
365                 $this->profiler->saveTimestamp($stamp1, "network");
366
367                 if ($http_code == 0) {
368                         return $url;
369                 }
370
371                 if (in_array($http_code, ['301', '302'])) {
372                         if (!empty($curl_info['redirect_url'])) {
373                                 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
374                         } elseif (!empty($curl_info['location'])) {
375                                 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
376                         }
377                 }
378
379                 // Check for redirects in the meta elements of the body if there are no redirects in the header.
380                 if (!$fetchbody) {
381                         return $this->finalUrl($url, ++$depth, true);
382                 }
383
384                 // if the file is too large then exit
385                 if ($curl_info["download_content_length"] > 1000000) {
386                         return $url;
387                 }
388
389                 // if it isn't a HTML file then exit
390                 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
391                         return $url;
392                 }
393
394                 $stamp1 = microtime(true);
395
396                 $ch = curl_init();
397                 curl_setopt($ch, CURLOPT_URL, $url);
398                 curl_setopt($ch, CURLOPT_HEADER, 0);
399                 curl_setopt($ch, CURLOPT_NOBODY, 0);
400                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
401                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
402                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
403                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
404
405                 $body = curl_exec($ch);
406                 curl_close($ch);
407
408                 $this->profiler->saveTimestamp($stamp1, "network");
409
410                 if (trim($body) == "") {
411                         return $url;
412                 }
413
414                 // Check for redirect in meta elements
415                 $doc = new DOMDocument();
416                 @$doc->loadHTML($body);
417
418                 $xpath = new DomXPath($doc);
419
420                 $list = $xpath->query("//meta[@content]");
421                 foreach ($list as $node) {
422                         $attr = [];
423                         if ($node->attributes->length) {
424                                 foreach ($node->attributes as $attribute) {
425                                         $attr[$attribute->name] = $attribute->value;
426                                 }
427                         }
428
429                         if (@$attr["http-equiv"] == 'refresh') {
430                                 $path = $attr["content"];
431                                 $pathinfo = explode(";", $path);
432                                 foreach ($pathinfo as $value) {
433                                         if (substr(strtolower($value), 0, 4) == "url=") {
434                                                 return $this->finalUrl(substr($value, 4), ++$depth);
435                                         }
436                                 }
437                         }
438                 }
439
440                 return $url;
441         }
442
443         /**
444          * {@inheritDoc}
445          *
446          * @param int $redirects The recursion counter for internal use - default 0
447          *
448          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
449          */
450         public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '', &$redirects = 0)
451         {
452                 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar, $redirects);
453
454                 return $ret->getBody();
455         }
456
457         /**
458          * {@inheritDoc}
459          *
460          * @param int $redirects The recursion counter for internal use - default 0
461          *
462          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
463          */
464         public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '', &$redirects = 0)
465         {
466                 return $this->get(
467                         $url,
468                         [
469                                 'timeout'        => $timeout,
470                                 'accept_content' => $accept_content,
471                                 'cookiejar'      => $cookiejar
472                         ],
473                         $redirects
474                 );
475         }
476
477         /**
478          * {@inheritDoc}
479          */
480         public function getUserAgent()
481         {
482                 return
483                         FRIENDICA_PLATFORM . " '" .
484                         FRIENDICA_CODENAME . "' " .
485                         FRIENDICA_VERSION . '-' .
486                         DB_UPDATE_VERSION . '; ' .
487                         $this->baseUrl;
488         }
489 }