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