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