]> git.mxchange.org Git - friendica.git/blob - src/Network/CurlResult.php
Some more "q" calls and deprecated logging replaced
[friendica.git] / src / Network / CurlResult.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL 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\Network\HTTPException\InternalServerErrorException;
27 use Friendica\Util\Network;
28
29 /**
30  * A content class for Curl call results
31  */
32 class CurlResult implements IHTTPResult
33 {
34         /**
35          * @var int HTTP return code or 0 if timeout or failure
36          */
37         private $returnCode;
38
39         /**
40          * @var string the content type of the Curl call
41          */
42         private $contentType;
43
44         /**
45          * @var string the HTTP headers of the Curl call
46          */
47         private $header;
48
49         /**
50          * @var array the HTTP headers of the Curl call
51          */
52         private $header_fields;
53
54         /**
55          * @var boolean true (if HTTP 2xx result) or false
56          */
57         private $isSuccess;
58
59         /**
60          * @var string the URL which was called
61          */
62         private $url;
63
64         /**
65          * @var string in case of redirect, content was finally retrieved from this URL
66          */
67         private $redirectUrl;
68
69         /**
70          * @var string fetched content
71          */
72         private $body;
73
74         /**
75          * @var array some informations about the fetched data
76          */
77         private $info;
78
79         /**
80          * @var boolean true if the URL has a redirect
81          */
82         private $isRedirectUrl;
83
84         /**
85          * @var boolean true if the curl request timed out
86          */
87         private $isTimeout;
88
89         /**
90          * @var int the error number or 0 (zero) if no error
91          */
92         private $errorNumber;
93
94         /**
95          * @var string the error message or '' (the empty string) if no
96          */
97         private $error;
98
99         /**
100          * Creates an errored CURL response
101          *
102          * @param string $url optional URL
103          *
104          * @return IHTTPResult a CURL with error response
105          * @throws InternalServerErrorException
106          */
107         public static function createErrorCurl($url = '')
108         {
109                 return new CurlResult($url, '', ['http_code' => 0]);
110         }
111
112         /**
113          * Curl constructor.
114          * @param string $url the URL which was called
115          * @param string $result the result of the curl execution
116          * @param array $info an additional info array
117          * @param int $errorNumber the error number or 0 (zero) if no error
118          * @param string $error the error message or '' (the empty string) if no
119          *
120          * @throws InternalServerErrorException when HTTP code of the CURL response is missing
121          */
122         public function __construct($url, $result, $info, $errorNumber = 0, $error = '')
123         {
124                 if (!array_key_exists('http_code', $info)) {
125                         throw new InternalServerErrorException('CURL response doesn\'t contains a response HTTP code');
126                 }
127
128                 $this->returnCode = $info['http_code'];
129                 $this->url = $url;
130                 $this->info = $info;
131                 $this->errorNumber = $errorNumber;
132                 $this->error = $error;
133
134                 Logger::debug('construct', ['url' => $url, 'returncode' => $this->returnCode, 'result' => $result]);
135
136                 $this->parseBodyHeader($result);
137                 $this->checkSuccess();
138                 $this->checkRedirect();
139                 $this->checkInfo();
140         }
141
142         private function parseBodyHeader($result)
143         {
144                 // Pull out multiple headers, e.g. proxy and continuation headers
145                 // allow for HTTP/2.x without fixing code
146
147                 $header = '';
148                 $base = $result;
149                 while (preg_match('/^HTTP\/.+? \d+/', $base)) {
150                         $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
151                         $header .= $chunk;
152                         $base = substr($base, strlen($chunk));
153                 }
154
155                 $this->body = substr($result, strlen($header));
156                 $this->header = $header;
157                 $this->header_fields = []; // Is filled on demand
158         }
159
160         private function checkSuccess()
161         {
162                 $this->isSuccess = ($this->returnCode >= 200 && $this->returnCode <= 299) || $this->errorNumber == 0;
163
164                 // Everything higher or equal 400 is not a success
165                 if ($this->returnCode >= 400) {
166                         $this->isSuccess = false;
167                 }
168
169                 if (!$this->isSuccess) {
170                         Logger::debug('debug', ['info' => $this->info]);
171                 }
172
173                 if (!$this->isSuccess && $this->errorNumber == CURLE_OPERATION_TIMEDOUT) {
174                         $this->isTimeout = true;
175                 } else {
176                         $this->isTimeout = false;
177                 }
178         }
179
180         private function checkRedirect()
181         {
182                 if (!array_key_exists('url', $this->info)) {
183                         $this->redirectUrl = '';
184                 } else {
185                         $this->redirectUrl = $this->info['url'];
186                 }
187
188                 if ($this->returnCode == 301 || $this->returnCode == 302 || $this->returnCode == 303 || $this->returnCode== 307) {
189                         $redirect_parts = parse_url($this->info['redirect_url'] ?? '');
190                         if (empty($redirect_parts)) {
191                                 $redirect_parts = [];
192                         }
193
194                         if (preg_match('/(Location:|URI:)(.*?)\n/i', $this->header, $matches)) {
195                                 $redirect_parts2 = parse_url(trim(array_pop($matches)));
196                                 if (!empty($redirect_parts2)) {
197                                         $redirect_parts = array_merge($redirect_parts, $redirect_parts2);
198                                 }
199                         }
200
201                         $parts = parse_url($this->info['url'] ?? '');
202                         if (empty($parts)) {
203                                 $parts = [];
204                         }
205
206                         /// @todo Checking the corresponding RFC which parts of a redirect can be ommitted.
207                         $components = ['scheme', 'host', 'path', 'query', 'fragment'];
208                         foreach ($components as $component) {
209                                 if (empty($redirect_parts[$component]) && !empty($parts[$component])) {
210                                         $redirect_parts[$component] = $parts[$component];
211                                 }
212                         }
213
214                         $this->redirectUrl = Network::unparseURL($redirect_parts);
215
216                         $this->isRedirectUrl = true;
217                 } else {
218                         $this->isRedirectUrl = false;
219                 }
220         }
221
222         private function checkInfo()
223         {
224                 if (isset($this->info['content_type'])) {
225                         $this->contentType = $this->info['content_type'];
226                 } else {
227                         $this->contentType = '';
228                 }
229         }
230
231         /** {@inheritDoc} */
232         public function getReturnCode()
233         {
234                 return $this->returnCode;
235         }
236
237         /** {@inheritDoc} */
238         public function getContentType()
239         {
240                 return $this->contentType;
241         }
242
243         /** {@inheritDoc} */
244         public function getHeader($header)
245         {
246                 if (empty($header)) {
247                         return [];
248                 }
249
250                 $header = strtolower(trim($header));
251
252                 $headers = $this->getHeaderArray();
253
254                 if (isset($headers[$header])) {
255                         return $headers[$header];
256                 }
257
258                 return [];
259         }
260
261         /** {@inheritDoc} */
262         public function getHeaders()
263         {
264                 return $this->getHeaderArray();
265         }
266
267         /** {@inheritDoc} */
268         public function inHeader(string $field)
269         {
270                 $field = strtolower(trim($field));
271
272                 $headers = $this->getHeaderArray();
273
274                 return array_key_exists($field, $headers);
275         }
276
277         /** {@inheritDoc} */
278         public function getHeaderArray()
279         {
280                 if (!empty($this->header_fields)) {
281                         return $this->header_fields;
282                 }
283
284                 $this->header_fields = [];
285
286                 $lines = explode("\n", trim($this->header));
287                 foreach ($lines as $line) {
288                         $parts = explode(':', $line);
289                         $headerfield = strtolower(trim(array_shift($parts)));
290                         $headerdata = trim(implode(':', $parts));
291                         if (empty($this->header_fields[$headerfield])) {
292                                 $this->header_fields[$headerfield] = [$headerdata];
293                         } elseif (!in_array($headerdata, $this->header_fields[$headerfield])) {
294                                 $this->header_fields[$headerfield][] = $headerdata;
295                         }
296                 }
297
298                 return $this->header_fields;
299         }
300
301         /** {@inheritDoc} */
302         public function isSuccess()
303         {
304                 return $this->isSuccess;
305         }
306
307         /** {@inheritDoc} */
308         public function getUrl()
309         {
310                 return $this->url;
311         }
312
313         /** {@inheritDoc} */
314         public function getRedirectUrl()
315         {
316                 return $this->redirectUrl;
317         }
318
319         /** {@inheritDoc} */
320         public function getBody()
321         {
322                 return $this->body;
323         }
324
325         /** {@inheritDoc} */
326         public function isRedirectUrl()
327         {
328                 return $this->isRedirectUrl;
329         }
330
331         /** {@inheritDoc} */
332         public function getErrorNumber()
333         {
334                 return $this->errorNumber;
335         }
336
337         /** {@inheritDoc} */
338         public function getError()
339         {
340                 return $this->error;
341         }
342
343         /** {@inheritDoc} */
344         public function isTimeout()
345         {
346                 return $this->isTimeout;
347         }
348 }