]> git.mxchange.org Git - friendica.git/blob - src/Network/HTTPRequest.php
Make "HTTPRequest::post" dynamic
[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\Util\Network;
29 use Friendica\Util\Profiler;
30 use Psr\Log\LoggerInterface;
31
32 /**
33  * Performs HTTP requests to a given URL
34  */
35 class HTTPRequest
36 {
37         /** @var LoggerInterface */
38         private $logger;
39         /** @var Profiler */
40         private $profiler;
41         /** @var IConfig */
42         private $config;
43         /** @var string */
44         private $userAgent;
45
46         public function __construct(LoggerInterface $logger, Profiler $profiler, IConfig $config, App $a)
47         {
48                 $this->logger    = $logger;
49                 $this->profiler  = $profiler;
50                 $this->config    = $config;
51                 $this->userAgent = $a->getUserAgent();
52         }
53
54         /**
55          * fetches an URL.
56          *
57          * @param string $url        URL to fetch
58          * @param bool   $binary     default false
59          *                           TRUE if asked to return binary results (file download)
60          * @param array  $opts       (optional parameters) assoziative array with:
61          *                           'accept_content' => supply Accept: header with 'accept_content' as the value
62          *                           'timeout' => int Timeout in seconds, default system config value or 60 seconds
63          *                           'http_auth' => username:password
64          *                           'novalidate' => do not validate SSL certs, default is to validate using our CA list
65          *                           'nobody' => only return the header
66          *                           'cookiejar' => path to cookie jar file
67          *                           'header' => header array
68          * @param int    $redirects  The recursion counter for internal use - default 0
69          *
70          * @return CurlResult
71          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
72          */
73         public function curl(string $url, bool $binary = false, 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->userAgent);
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                 if (!empty($opts['timeout'])) {
152                         @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
153                 } else {
154                         $curl_time = $this->config->get('system', 'curl_timeout', 60);
155                         @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
156                 }
157
158                 // by default we will allow self-signed certs
159                 // but you can override this
160
161                 $check_cert = $this->config->get('system', 'verifyssl');
162                 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
163
164                 if ($check_cert) {
165                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
166                 }
167
168                 $proxy = $this->config->get('system', 'proxy');
169
170                 if (!empty($proxy)) {
171                         @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
172                         @curl_setopt($ch, CURLOPT_PROXY, $proxy);
173                         $proxyuser = $this->config->get('system', 'proxyuser');
174
175                         if (!empty($proxyuser)) {
176                                 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
177                         }
178                 }
179
180                 if ($this->config->get('system', 'ipv4_resolve', false)) {
181                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
182                 }
183
184                 if ($binary) {
185                         @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
186                 }
187
188                 // don't let curl abort the entire application
189                 // if it throws any errors.
190
191                 $s         = @curl_exec($ch);
192                 $curl_info = @curl_getinfo($ch);
193
194                 // Special treatment for HTTP Code 416
195                 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
196                 if (($curl_info['http_code'] == 416) && ($range > 0)) {
197                         @curl_setopt($ch, CURLOPT_RANGE, '');
198                         $s         = @curl_exec($ch);
199                         $curl_info = @curl_getinfo($ch);
200                 }
201
202                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
203
204                 if ($curlResponse->isRedirectUrl()) {
205                         $redirects++;
206                         $this->logger->notice('Curl redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
207                         @curl_close($ch);
208                         return self::curl($curlResponse->getRedirectUrl(), $binary, $opts, $redirects);
209                 }
210
211                 @curl_close($ch);
212
213                 $this->profiler->saveTimestamp($stamp1, 'network', System::callstack());
214
215                 return $curlResponse;
216         }
217
218         /**
219          * Send POST request to $url
220          *
221          * @param string $url       URL to post
222          * @param mixed  $params    array of POST variables
223          * @param array  $headers   HTTP headers
224          * @param int    $redirects Recursion counter for internal use - default = 0
225          * @param int    $timeout   The timeout in seconds, default system config value or 60 seconds
226          *
227          * @return CurlResult The content
228          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
229          */
230         public function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
231         {
232                 $stamp1 = microtime(true);
233
234                 if (Network::isUrlBlocked($url)) {
235                         $this->logger->info('Domain is blocked.'. ['url' => $url]);
236                         return CurlResult::createErrorCurl($url);
237                 }
238
239                 $ch = curl_init($url);
240
241                 if (($redirects > 8) || (!$ch)) {
242                         return CurlResult::createErrorCurl($url);
243                 }
244
245                 $this->logger->debug('Post_url: start.', ['url' => $url]);
246
247                 curl_setopt($ch, CURLOPT_HEADER, true);
248                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
249                 curl_setopt($ch, CURLOPT_POST, 1);
250                 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
251                 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
252
253                 if ($this->config->get('system', 'ipv4_resolve', false)) {
254                         curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
255                 }
256
257                 if (intval($timeout)) {
258                         curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
259                 } else {
260                         $curl_time = $this->config->get('system', 'curl_timeout', 60);
261                         curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
262                 }
263
264                 if (!empty($headers)) {
265                         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
266                 }
267
268                 $check_cert = $this->config->get('system', 'verifyssl');
269                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
270
271                 if ($check_cert) {
272                         @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
273                 }
274
275                 $proxy = $this->config->get('system', 'proxy');
276
277                 if (!empty($proxy)) {
278                         curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
279                         curl_setopt($ch, CURLOPT_PROXY, $proxy);
280                         $proxyuser = $this->config->get('system', 'proxyuser');
281                         if (!empty($proxyuser)) {
282                                 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
283                         }
284                 }
285
286                 // don't let curl abort the entire application
287                 // if it throws any errors.
288
289                 $s = @curl_exec($ch);
290
291                 $curl_info = curl_getinfo($ch);
292
293                 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
294
295                 if ($curlResponse->isRedirectUrl()) {
296                         $redirects++;
297                         $this->logger->info('Post redirect.', ['url' => $url, 'to' => $curlResponse->getRedirectUrl()]);
298                         curl_close($ch);
299                         return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
300                 }
301
302                 curl_close($ch);
303
304                 $this->profiler->saveTimestamp($stamp1, 'network', System::callstack());
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                         Logger::info('Server responds with 417, applying workaround', ['url' => $url]);
318                         return self::post($url, $params, $headers, $redirects, $timeout);
319                 }
320
321                 Logger::log('post_url: end ' . $url, Logger::DATA);
322
323                 return $curlResponse;
324         }
325
326         /**
327          * Curl wrapper
328          *
329          * If binary flag is true, return binary results.
330          * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
331          * to preserve cookies from one request to the next.
332          *
333          * @param string $url             URL to fetch
334          * @param bool   $binary          default false
335          *                                TRUE if asked to return binary results (file download)
336          * @param int    $timeout         Timeout in seconds, default system config value or 60 seconds
337          * @param string $accept_content  supply Accept: header with 'accept_content' as the value
338          * @param string $cookiejar       Path to cookie jar file
339          * @param int    $redirects       The recursion counter for internal use - default 0
340          *
341          * @return string The fetched content
342          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
343          */
344         public static function fetchUrl(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
345         {
346                 $ret = self::fetchUrlFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
347
348                 return $ret->getBody();
349         }
350
351         /**
352          * Curl wrapper with array of return values.
353          *
354          * Inner workings and parameters are the same as @ref fetchUrl but returns an array with
355          * all the information collected during the fetch.
356          *
357          * @param string $url             URL to fetch
358          * @param bool   $binary          default false
359          *                                TRUE if asked to return binary results (file download)
360          * @param int    $timeout         Timeout in seconds, default system config value or 60 seconds
361          * @param string $accept_content  supply Accept: header with 'accept_content' as the value
362          * @param string $cookiejar       Path to cookie jar file
363          * @param int    $redirects       The recursion counter for internal use - default 0
364          *
365          * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
366          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
367          */
368         public static function fetchUrlFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
369         {
370                 return self::curl(
371                         $url,
372                         $binary,
373                         [
374                                 'timeout'        => $timeout,
375                                 'accept_content' => $accept_content,
376                                 'cookiejar'      => $cookiejar
377                         ],
378                         $redirects
379                 );
380         }
381 }