]> git.mxchange.org Git - friendica.git/blob - src/Network/HTTPRequest.php
Introduce HTPPRequest DI call and constructor
[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 Friendica\App;
25 use Friendica\Core\Config\IConfig;
26 use Friendica\Core\Logger;
27 use Friendica\Core\System;
28 use Friendica\DI;
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
37 {
38         /** @var LoggerInterface */
39         private $logger;
40         /** @var Profiler */
41         private $profiler;
42         /** @var IConfig */
43         private $config;
44         /** @var string */
45         private $userAgent;
46
47         public function __construct(LoggerInterface $logger, Profiler $profiler, IConfig $config, App $a)
48         {
49                 $this->logger    = $logger;
50                 $this->profiler  = $profiler;
51                 $this->config    = $config;
52                 $this->userAgent = $a->getUserAgent();
53         }
54
55         /**
56          * fetches an URL.
57          *
58          * @param string $url        URL to fetch
59          * @param bool   $binary     default false
60          *                           TRUE if asked to return binary results (file download)
61          * @param array  $opts       (optional parameters) assoziative array with:
62          *                           'accept_content' => supply Accept: header with 'accept_content' as the value
63          *                           'timeout' => int Timeout in seconds, default system config value or 60 seconds
64          *                           'http_auth' => username:password
65          *                           'novalidate' => do not validate SSL certs, default is to validate using our CA list
66          *                           'nobody' => only return the header
67          *                           'cookiejar' => path to cookie jar file
68          *                           'header' => header array
69          * @param int    $redirects  The recursion counter for internal use - default 0
70          *
71          * @return CurlResult
72          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
73          */
74         public static function curl(string $url, bool $binary = false, array $opts = [], int &$redirects = 0)
75         {
76                 $stamp1 = microtime(true);
77
78                 if (strlen($url) > 1000) {
79                         Logger::log('URL is longer than 1000 characters. Callstack: ' . System::callstack(20), Logger::DEBUG);
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                         Logger::log('domain of ' . $url . ' is blocked', Logger::DATA);
98                         return CurlResult::createErrorCurl($url);
99                 }
100
101                 $ch = @curl_init($url);
102
103                 if (($redirects > 8) || (!$ch)) {
104                         return CurlResult::createErrorCurl($url);
105                 }
106
107                 @curl_setopt($ch, CURLOPT_HEADER, true);
108
109                 if (!empty($opts['cookiejar'])) {
110                         curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
111                         curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
112                 }
113
114                 // These settings aren't needed. We're following the location already.
115                 //      @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
116                 //      @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
117
118                 if (!empty($opts['accept_content'])) {
119                         curl_setopt(
120                                 $ch,
121                                 CURLOPT_HTTPHEADER,
122                                 ['Accept: ' . $opts['accept_content']]
123                         );
124                 }
125
126                 if (!empty($opts['header'])) {
127                         curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
128                 }
129
130                 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
131                 @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
132
133                 $range = intval(DI::config()->get('system', 'curl_range_bytes', 0));
134
135                 if ($range > 0) {
136                         @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
137                 }
138
139                 // Without this setting it seems as if some webservers send compressed content
140                 // This seems to confuse curl so that it shows this uncompressed.
141                 /// @todo  We could possibly set this value to "gzip" or something similar
142                 curl_setopt($ch, CURLOPT_ENCODING, '');
143
144                 if (!empty($opts['headers'])) {
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                 if (!empty($opts['timeout'])) {
153                         @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
154                 } else {
155                         $curl_time = DI::config()->get('system', 'curl_timeout', 60);
156                         @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
157                 }
158
159                 // by default we will allow self-signed certs
160                 // but you can override this
161
162                 $check_cert = DI::config()->get('system', 'verifyssl');
163                 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
164
165                 if ($check_cert) {
166                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
167                 }
168
169                 $proxy = DI::config()->get('system', 'proxy');
170
171                 if (strlen($proxy)) {
172                         @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
173                         @curl_setopt($ch, CURLOPT_PROXY, $proxy);
174                         $proxyuser = @DI::config()->get('system', 'proxyuser');
175
176                         if (strlen($proxyuser)) {
177                                 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
178                         }
179                 }
180
181                 if (DI::config()->get('system', 'ipv4_resolve', false)) {
182                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
183                 }
184
185                 if ($binary) {
186                         @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
187                 }
188
189                 // don't let curl abort the entire application
190                 // if it throws any errors.
191
192                 $s         = @curl_exec($ch);
193                 $curl_info = @curl_getinfo($ch);
194
195                 // Special treatment for HTTP Code 416
196                 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
197                 if (($curl_info['http_code'] == 416) && ($range > 0)) {
198                         @curl_setopt($ch, CURLOPT_RANGE, '');
199                         $s         = @curl_exec($ch);
200                         $curl_info = @curl_getinfo($ch);
201                 }
202
203                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
204
205                 if ($curlResponse->isRedirectUrl()) {
206                         $redirects++;
207                         Logger::log('curl: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
208                         @curl_close($ch);
209                         return self::curl($curlResponse->getRedirectUrl(), $binary, $opts, $redirects);
210                 }
211
212                 @curl_close($ch);
213
214                 DI::profiler()->saveTimestamp($stamp1, 'network', System::callstack());
215
216                 return $curlResponse;
217         }
218
219         /**
220          * Send POST request to $url
221          *
222          * @param string $url       URL to post
223          * @param mixed  $params    array of POST variables
224          * @param array  $headers   HTTP headers
225          * @param int    $redirects Recursion counter for internal use - default = 0
226          * @param int    $timeout   The timeout in seconds, default system config value or 60 seconds
227          *
228          * @return CurlResult The content
229          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230          */
231         public static function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
232         {
233                 $stamp1 = microtime(true);
234
235                 if (Network::isUrlBlocked($url)) {
236                         Logger::log('post_url: domain of ' . $url . ' is blocked', Logger::DATA);
237                         return CurlResult::createErrorCurl($url);
238                 }
239
240                 $a  = DI::app();
241                 $ch = curl_init($url);
242
243                 if (($redirects > 8) || (!$ch)) {
244                         return CurlResult::createErrorCurl($url);
245                 }
246
247                 Logger::log('post_url: start ' . $url, Logger::DATA);
248
249                 curl_setopt($ch, CURLOPT_HEADER, true);
250                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
251                 curl_setopt($ch, CURLOPT_POST, 1);
252                 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
253                 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
254
255                 if (DI::config()->get('system', 'ipv4_resolve', false)) {
256                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
257                 }
258
259                 if (intval($timeout)) {
260                         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
261                 } else {
262                         $curl_time = DI::config()->get('system', 'curl_timeout', 60);
263                         curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
264                 }
265
266                 if (!empty($headers)) {
267                         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
268                 }
269
270                 $check_cert = DI::config()->get('system', 'verifyssl');
271                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
272
273                 if ($check_cert) {
274                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
275                 }
276
277                 $proxy = DI::config()->get('system', 'proxy');
278
279                 if (strlen($proxy)) {
280                         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
281                         curl_setopt($ch, CURLOPT_PROXY, $proxy);
282                         $proxyuser = DI::config()->get('system', 'proxyuser');
283                         if (strlen($proxyuser)) {
284                                 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
285                         }
286                 }
287
288                 // don't let curl abort the entire application
289                 // if it throws any errors.
290
291                 $s = @curl_exec($ch);
292
293                 $curl_info = curl_getinfo($ch);
294
295                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
296
297                 if ($curlResponse->isRedirectUrl()) {
298                         $redirects++;
299                         Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
300                         curl_close($ch);
301                         return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
302                 }
303
304                 curl_close($ch);
305
306                 DI::profiler()->saveTimestamp($stamp1, 'network', System::callstack());
307
308                 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
309                 if ($curlResponse->getReturnCode() == 417) {
310                         $redirects++;
311
312                         if (empty($headers)) {
313                                 $headers = ['Expect:'];
314                         } else {
315                                 if (!in_array('Expect:', $headers)) {
316                                         array_push($headers, 'Expect:');
317                                 }
318                         }
319                         Logger::info('Server responds with 417, applying workaround', ['url' => $url]);
320                         return self::post($url, $params, $headers, $redirects, $timeout);
321                 }
322
323                 Logger::log('post_url: end ' . $url, Logger::DATA);
324
325                 return $curlResponse;
326         }
327
328         /**
329          * Curl wrapper
330          *
331          * If binary flag is true, return binary results.
332          * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
333          * to preserve cookies from one request to the next.
334          *
335          * @param string $url             URL to fetch
336          * @param bool   $binary          default false
337          *                                TRUE if asked to return binary results (file download)
338          * @param int    $timeout         Timeout in seconds, default system config value or 60 seconds
339          * @param string $accept_content  supply Accept: header with 'accept_content' as the value
340          * @param string $cookiejar       Path to cookie jar file
341          * @param int    $redirects       The recursion counter for internal use - default 0
342          *
343          * @return string The fetched content
344          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
345          */
346         public static function fetchUrl(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
347         {
348                 $ret = self::fetchUrlFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
349
350                 return $ret->getBody();
351         }
352
353         /**
354          * Curl wrapper with array of return values.
355          *
356          * Inner workings and parameters are the same as @ref fetchUrl but returns an array with
357          * all the information collected during the fetch.
358          *
359          * @param string $url             URL to fetch
360          * @param bool   $binary          default false
361          *                                TRUE if asked to return binary results (file download)
362          * @param int    $timeout         Timeout in seconds, default system config value or 60 seconds
363          * @param string $accept_content  supply Accept: header with 'accept_content' as the value
364          * @param string $cookiejar       Path to cookie jar file
365          * @param int    $redirects       The recursion counter for internal use - default 0
366          *
367          * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
368          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
369          */
370         public static function fetchUrlFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
371         {
372                 return self::curl(
373                         $url,
374                         $binary,
375                         [
376                                 'timeout'        => $timeout,
377                                 'accept_content' => $accept_content,
378                                 'cookiejar'      => $cookiejar
379                         ],
380                         $redirects
381                 );
382         }
383 }