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