]> git.mxchange.org Git - friendica.git/blob - src/Network/HTTPRequest.php
Merge pull request #9440 from annando/one-click-follow
[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 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 = [], int &$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                         return CurlResult::createErrorCurl(substr($url, 0, 200));
80                 }
81
82                 $parts2     = [];
83                 $parts      = parse_url($url);
84                 $path_parts = explode('/', $parts['path'] ?? '');
85                 foreach ($path_parts as $part) {
86                         if (strlen($part) <> mb_strlen($part)) {
87                                 $parts2[] = rawurlencode($part);
88                         } else {
89                                 $parts2[] = $part;
90                         }
91                 }
92                 $parts['path'] = implode('/', $parts2);
93                 $url           = Network::unparseURL($parts);
94
95                 if (Network::isUrlBlocked($url)) {
96                         $this->logger->info('Domain is blocked.', ['url' => $url]);
97                         return CurlResult::createErrorCurl($url);
98                 }
99
100                 $ch = @curl_init($url);
101
102                 if (($redirects > 8) || (!$ch)) {
103                         return CurlResult::createErrorCurl($url);
104                 }
105
106                 @curl_setopt($ch, CURLOPT_HEADER, true);
107
108                 if (!empty($opts['cookiejar'])) {
109                         curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
110                         curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
111                 }
112
113                 // These settings aren't needed. We're following the location already.
114                 //      @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
115                 //      @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
116
117                 if (!empty($opts['accept_content'])) {
118                         curl_setopt(
119                                 $ch,
120                                 CURLOPT_HTTPHEADER,
121                                 ['Accept: ' . $opts['accept_content']]
122                         );
123                 }
124
125                 if (!empty($opts['header'])) {
126                         curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
127                 }
128
129                 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
130                 @curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
131
132                 $range = intval($this->config->get('system', 'curl_range_bytes', 0));
133
134                 if ($range > 0) {
135                         @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
136                 }
137
138                 // Without this setting it seems as if some webservers send compressed content
139                 // This seems to confuse curl so that it shows this uncompressed.
140                 /// @todo  We could possibly set this value to "gzip" or something similar
141                 curl_setopt($ch, CURLOPT_ENCODING, '');
142
143                 if (!empty($opts['headers'])) {
144                         $this->logger->notice('Wrong option \'headers\' used.');
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                 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
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                 $s         = @curl_exec($ch);
188                 $curl_info = @curl_getinfo($ch);
189
190                 // Special treatment for HTTP Code 416
191                 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
192                 if (($curl_info['http_code'] == 416) && ($range > 0)) {
193                         @curl_setopt($ch, CURLOPT_RANGE, '');
194                         $s         = @curl_exec($ch);
195                         $curl_info = @curl_getinfo($ch);
196                 }
197
198                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
199
200                 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
201                         $redirects++;
202                         $this->logger->notice('Curl redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
203                         @curl_close($ch);
204                         return $this->get($curlResponse->getRedirectUrl(), $opts, $redirects);
205                 }
206
207                 @curl_close($ch);
208
209                 $this->profiler->saveTimestamp($stamp1, 'network');
210
211                 return $curlResponse;
212         }
213
214         /**
215          * {@inheritDoc}
216          *
217          * @param int $redirects The recursion counter for internal use - default 0
218          *
219          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
220          */
221         public function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
222         {
223                 $stamp1 = microtime(true);
224
225                 if (Network::isUrlBlocked($url)) {
226                         $this->logger->info('Domain is blocked.' . ['url' => $url]);
227                         return CurlResult::createErrorCurl($url);
228                 }
229
230                 $ch = curl_init($url);
231
232                 if (($redirects > 8) || (!$ch)) {
233                         return CurlResult::createErrorCurl($url);
234                 }
235
236                 $this->logger->debug('Post_url: start.', ['url' => $url]);
237
238                 curl_setopt($ch, CURLOPT_HEADER, true);
239                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
240                 curl_setopt($ch, CURLOPT_POST, 1);
241                 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
242                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
243
244                 if ($this->config->get('system', 'ipv4_resolve', false)) {
245                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
246                 }
247
248                 @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
249
250                 if (intval($timeout)) {
251                         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
252                 } else {
253                         $curl_time = $this->config->get('system', 'curl_timeout', 60);
254                         curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
255                 }
256
257                 if (!empty($headers)) {
258                         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
259                 }
260
261                 $check_cert = $this->config->get('system', 'verifyssl');
262                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
263
264                 if ($check_cert) {
265                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
266                 }
267
268                 $proxy = $this->config->get('system', 'proxy');
269
270                 if (!empty($proxy)) {
271                         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
272                         curl_setopt($ch, CURLOPT_PROXY, $proxy);
273                         $proxyuser = $this->config->get('system', 'proxyuser');
274                         if (!empty($proxyuser)) {
275                                 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
276                         }
277                 }
278
279                 // don't let curl abort the entire application
280                 // if it throws any errors.
281
282                 $s = @curl_exec($ch);
283
284                 $curl_info = curl_getinfo($ch);
285
286                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
287
288                 if (!Network::isRedirectBlocked($url) && $curlResponse->isRedirectUrl()) {
289                         $redirects++;
290                         $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
291                         curl_close($ch);
292                         return $this->post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
293                 }
294
295                 curl_close($ch);
296
297                 $this->profiler->saveTimestamp($stamp1, 'network');
298
299                 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
300                 if ($curlResponse->getReturnCode() == 417) {
301                         $redirects++;
302
303                         if (empty($headers)) {
304                                 $headers = ['Expect:'];
305                         } else {
306                                 if (!in_array('Expect:', $headers)) {
307                                         array_push($headers, 'Expect:');
308                                 }
309                         }
310                         $this->logger->info('Server responds with 417, applying workaround', ['url' => $url]);
311                         return $this->post($url, $params, $headers, $redirects, $timeout);
312                 }
313
314                 $this->logger->debug('Post_url: End.', ['url' => $url]);
315
316                 return $curlResponse;
317         }
318
319         /**
320          * {@inheritDoc}
321          */
322         public function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
323         {
324                 if (Network::isUrlBlocked($url)) {
325                         $this->logger->info('Domain is blocked.', ['url' => $url]);
326                         return $url;
327                 }
328
329                 if (Network::isRedirectBlocked($url)) {
330                         $this->logger->info('Domain should not be redirected.', ['url' => $url]);
331                         return $url;
332                 }
333
334                 $url = Network::stripTrackingQueryParams($url);
335
336                 if ($depth > 10) {
337                         return $url;
338                 }
339
340                 $url = trim($url, "'");
341
342                 $stamp1 = microtime(true);
343
344                 $ch = curl_init();
345                 curl_setopt($ch, CURLOPT_URL, $url);
346                 curl_setopt($ch, CURLOPT_HEADER, 1);
347                 curl_setopt($ch, CURLOPT_NOBODY, 1);
348                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
349                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
350                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
351                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
352
353                 curl_exec($ch);
354                 $curl_info = @curl_getinfo($ch);
355                 $http_code = $curl_info['http_code'];
356                 curl_close($ch);
357
358                 $this->profiler->saveTimestamp($stamp1, "network");
359
360                 if ($http_code == 0) {
361                         return $url;
362                 }
363
364                 if (in_array($http_code, ['301', '302'])) {
365                         if (!empty($curl_info['redirect_url'])) {
366                                 return $this->finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
367                         } elseif (!empty($curl_info['location'])) {
368                                 return $this->finalUrl($curl_info['location'], ++$depth, $fetchbody);
369                         }
370                 }
371
372                 // Check for redirects in the meta elements of the body if there are no redirects in the header.
373                 if (!$fetchbody) {
374                         return $this->finalUrl($url, ++$depth, true);
375                 }
376
377                 // if the file is too large then exit
378                 if ($curl_info["download_content_length"] > 1000000) {
379                         return $url;
380                 }
381
382                 // if it isn't a HTML file then exit
383                 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
384                         return $url;
385                 }
386
387                 $stamp1 = microtime(true);
388
389                 $ch = curl_init();
390                 curl_setopt($ch, CURLOPT_URL, $url);
391                 curl_setopt($ch, CURLOPT_HEADER, 0);
392                 curl_setopt($ch, CURLOPT_NOBODY, 0);
393                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
394                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
395                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
396                 curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
397
398                 $body = curl_exec($ch);
399                 curl_close($ch);
400
401                 $this->profiler->saveTimestamp($stamp1, "network");
402
403                 if (trim($body) == "") {
404                         return $url;
405                 }
406
407                 // Check for redirect in meta elements
408                 $doc = new DOMDocument();
409                 @$doc->loadHTML($body);
410
411                 $xpath = new DomXPath($doc);
412
413                 $list = $xpath->query("//meta[@content]");
414                 foreach ($list as $node) {
415                         $attr = [];
416                         if ($node->attributes->length) {
417                                 foreach ($node->attributes as $attribute) {
418                                         $attr[$attribute->name] = $attribute->value;
419                                 }
420                         }
421
422                         if (@$attr["http-equiv"] == 'refresh') {
423                                 $path = $attr["content"];
424                                 $pathinfo = explode(";", $path);
425                                 foreach ($pathinfo as $value) {
426                                         if (substr(strtolower($value), 0, 4) == "url=") {
427                                                 return $this->finalUrl(substr($value, 4), ++$depth);
428                                         }
429                                 }
430                         }
431                 }
432
433                 return $url;
434         }
435
436         /**
437          * {@inheritDoc}
438          *
439          * @param int $redirects The recursion counter for internal use - default 0
440          *
441          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
442          */
443         public function fetch(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
444         {
445                 $ret = $this->fetchFull($url, $timeout, $accept_content, $cookiejar, $redirects);
446
447                 return $ret->getBody();
448         }
449
450         /**
451          * {@inheritDoc}
452          *
453          * @param int $redirects The recursion counter for internal use - default 0
454          *
455          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
456          */
457         public function fetchFull(string $url, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
458         {
459                 return $this->get(
460                         $url,
461                         [
462                                 'timeout'        => $timeout,
463                                 'accept_content' => $accept_content,
464                                 'cookiejar'      => $cookiejar
465                         ],
466                         $redirects
467                 );
468         }
469
470         /**
471          * {@inheritDoc}
472          */
473         public function getUserAgent()
474         {
475                 return
476                         FRIENDICA_PLATFORM . " '" .
477                         FRIENDICA_CODENAME . "' " .
478                         FRIENDICA_VERSION . '-' .
479                         DB_UPDATE_VERSION . '; ' .
480                         $this->baseUrl;
481         }
482 }