3 * @copyright Copyright (C) 2010-2021, the Friendica project
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
32 class CurlResult implements IHTTPResult
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 IHTTPResult 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::debug('debug', ['info' => $this->info]);
173 if (!$this->isSuccess && $this->errorNumber == CURLE_OPERATION_TIMEDOUT) {
174 $this->isTimeout = true;
176 $this->isTimeout = false;
180 private function checkRedirect()
182 if (!array_key_exists('url', $this->info)) {
183 $this->redirectUrl = '';
185 $this->redirectUrl = $this->info['url'];
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 = [];
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);
201 $parts = parse_url($this->info['url'] ?? '');
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];
214 $this->redirectUrl = Network::unparseURL($redirect_parts);
216 $this->isRedirectUrl = true;
218 $this->isRedirectUrl = false;
222 private function checkInfo()
224 if (isset($this->info['content_type'])) {
225 $this->contentType = $this->info['content_type'];
227 $this->contentType = '';
232 public function getReturnCode()
234 return $this->returnCode;
238 public function getContentType()
240 return $this->contentType;
244 public function getHeader($header)
246 if (empty($header)) {
250 $header = strtolower(trim($header));
252 $headers = $this->getHeaderArray();
254 if (isset($headers[$header])) {
255 return $headers[$header];
262 public function getHeaders()
264 return $this->getHeaderArray();
268 public function inHeader(string $field)
270 $field = strtolower(trim($field));
272 $headers = $this->getHeaderArray();
274 return array_key_exists($field, $headers);
278 public function getHeaderArray()
280 if (!empty($this->header_fields)) {
281 return $this->header_fields;
284 $this->header_fields = [];
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;
298 return $this->header_fields;
302 public function isSuccess()
304 return $this->isSuccess;
308 public function getUrl()
314 public function getRedirectUrl()
316 return $this->redirectUrl;
320 public function getBody()
326 public function isRedirectUrl()
328 return $this->isRedirectUrl;
332 public function getErrorNumber()
334 return $this->errorNumber;
338 public function getError()
344 public function isTimeout()
346 return $this->isTimeout;