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