3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Network;
24 use Friendica\Core\Logger;
25 use Friendica\Core\System;
26 use Friendica\Network\HTTPException\InternalServerErrorException;
27 use Friendica\Util\Network;
30 * A content class for Curl call results
35 * @var int HTTP return code or 0 if timeout or failure
40 * @var string the content type of the Curl call
45 * @var string the HTTP headers of the Curl call
50 * @var array the HTTP headers of the Curl call
52 private $header_fields;
55 * @var boolean true (if HTTP 2xx result) or false
60 * @var string the URL which was called
65 * @var string in case of redirect, content was finally retrieved from this URL
70 * @var string fetched content
75 * @var array some informations about the fetched data
80 * @var boolean true if the URL has a redirect
82 private $isRedirectUrl;
85 * @var boolean true if the curl request timed out
90 * @var int the error number or 0 (zero) if no error
95 * @var string the error message or '' (the empty string) if no
100 * Creates an errored CURL response
102 * @param string $url optional URL
104 * @return CurlResult a CURL with error response
105 * @throws InternalServerErrorException
107 public static function createErrorCurl($url = '')
109 return new CurlResult($url, '', ['http_code' => 0]);
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
120 * @throws InternalServerErrorException when HTTP code of the CURL response is missing
122 public function __construct($url, $result, $info, $errorNumber = 0, $error = '')
124 if (!array_key_exists('http_code', $info)) {
125 throw new InternalServerErrorException('CURL response doesn\'t contains a response HTTP code');
128 $this->returnCode = $info['http_code'];
131 $this->errorNumber = $errorNumber;
132 $this->error = $error;
134 Logger::debug('construct', ['url' => $url, 'returncode' => $this->returnCode, 'result' => $result]);
136 $this->parseBodyHeader($result);
137 $this->checkSuccess();
138 $this->checkRedirect();
142 private function parseBodyHeader($result)
144 // Pull out multiple headers, e.g. proxy and continuation headers
145 // allow for HTTP/2.x without fixing code
149 while (preg_match('/^HTTP\/.+? \d+/', $base)) {
150 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
152 $base = substr($base, strlen($chunk));
155 $this->body = substr($result, strlen($header));
156 $this->header = $header;
157 $this->header_fields = []; // Is filled on demand
160 private function checkSuccess()
162 $this->isSuccess = ($this->returnCode >= 200 && $this->returnCode <= 299) || $this->errorNumber == 0;
164 // Everything higher or equal 400 is not a success
165 if ($this->returnCode >= 400) {
166 $this->isSuccess = false;
169 if (!$this->isSuccess) {
170 Logger::notice('http error', ['url' => $this->url, 'code' => $this->returnCode, 'error' => $this->error, 'callstack' => System::callstack(20)]);
171 Logger::debug('debug', ['info' => $this->info]);
174 if (!$this->isSuccess && $this->errorNumber == CURLE_OPERATION_TIMEDOUT) {
175 $this->isTimeout = true;
177 $this->isTimeout = false;
181 private function checkRedirect()
183 if (!array_key_exists('url', $this->info)) {
184 $this->redirectUrl = '';
186 $this->redirectUrl = $this->info['url'];
189 if ($this->returnCode == 301 || $this->returnCode == 302 || $this->returnCode == 303 || $this->returnCode== 307) {
190 $redirect_parts = parse_url($this->info['redirect_url'] ?? '');
191 if (empty($redirect_parts)) {
192 $redirect_parts = [];
195 if (preg_match('/(Location:|URI:)(.*?)\n/i', $this->header, $matches)) {
196 $redirect_parts2 = parse_url(trim(array_pop($matches)));
197 if (!empty($redirect_parts2)) {
198 $redirect_parts = array_merge($redirect_parts, $redirect_parts2);
202 $parts = parse_url($this->info['url'] ?? '');
207 /// @todo Checking the corresponding RFC which parts of a redirect can be ommitted.
208 $components = ['scheme', 'host', 'path', 'query', 'fragment'];
209 foreach ($components as $component) {
210 if (empty($redirect_parts[$component]) && !empty($parts[$component])) {
211 $redirect_parts[$component] = $parts[$component];
215 $this->redirectUrl = Network::unparseURL($redirect_parts);
217 $this->isRedirectUrl = true;
219 $this->isRedirectUrl = false;
223 private function checkInfo()
225 if (isset($this->info['content_type'])) {
226 $this->contentType = $this->info['content_type'];
228 $this->contentType = '';
235 * @return string The Curl Code
237 public function getReturnCode()
239 return $this->returnCode;
243 * Returns the Curl Content Type
245 * @return string the Curl Content Type
247 public function getContentType()
249 return $this->contentType;
253 * Returns the Curl headers
255 * @param string $field optional header field. Return all fields if empty
257 * @return string the Curl headers or the specified content of the header variable
259 public function getHeader(string $field = '')
262 return $this->header;
265 $field = strtolower(trim($field));
267 $headers = $this->getHeaderArray();
269 if (isset($headers[$field])) {
270 return $headers[$field];
277 * Check if a specified header exists
279 * @param string $field header field
281 * @return boolean "true" if header exists
283 public function inHeader(string $field)
285 $field = strtolower(trim($field));
287 $headers = $this->getHeaderArray();
289 return array_key_exists($field, $headers);
293 * Returns the Curl headers as an associated array
295 * @return array associated header array
297 public function getHeaderArray()
299 if (!empty($this->header_fields)) {
300 return $this->header_fields;
303 $this->header_fields = [];
305 $lines = explode("\n", trim($this->header));
306 foreach ($lines as $line) {
307 $parts = explode(':', $line);
308 $headerfield = strtolower(trim(array_shift($parts)));
309 $headerdata = trim(implode(':', $parts));
310 $this->header_fields[$headerfield] = $headerdata;
313 return $this->header_fields;
319 public function isSuccess()
321 return $this->isSuccess;
327 public function getUrl()
335 public function getRedirectUrl()
337 return $this->redirectUrl;
343 public function getBody()
351 public function getInfo()
359 public function isRedirectUrl()
361 return $this->isRedirectUrl;
367 public function getErrorNumber()
369 return $this->errorNumber;
375 public function getError()
383 public function isTimeout()
385 return $this->isTimeout;