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\Network\HTTPException\InternalServerErrorException;
26 use Friendica\Util\Network;
29 * A content class for Curl call results
34 * @var int HTTP return code or 0 if timeout or failure
39 * @var string the content type of the Curl call
44 * @var string the HTTP headers of the Curl call
49 * @var array the HTTP headers of the Curl call
51 private $header_fields;
54 * @var boolean true (if HTTP 2xx result) or false
59 * @var string the URL which was called
64 * @var string in case of redirect, content was finally retrieved from this URL
69 * @var string fetched content
74 * @var array some informations about the fetched data
79 * @var boolean true if the URL has a redirect
81 private $isRedirectUrl;
84 * @var boolean true if the curl request timed out
89 * @var int the error number or 0 (zero) if no error
94 * @var string the error message or '' (the empty string) if no
99 * Creates an errored CURL response
101 * @param string $url optional URL
103 * @return CurlResult a CURL with error response
104 * @throws InternalServerErrorException
106 public static function createErrorCurl($url = '')
108 return new CurlResult($url, '', ['http_code' => 0]);
113 * @param string $url the URL which was called
114 * @param string $result the result of the curl execution
115 * @param array $info an additional info array
116 * @param int $errorNumber the error number or 0 (zero) if no error
117 * @param string $error the error message or '' (the empty string) if no
119 * @throws InternalServerErrorException when HTTP code of the CURL response is missing
121 public function __construct($url, $result, $info, $errorNumber = 0, $error = '')
123 if (!array_key_exists('http_code', $info)) {
124 throw new InternalServerErrorException('CURL response doesn\'t contains a response HTTP code');
127 $this->returnCode = $info['http_code'];
130 $this->errorNumber = $errorNumber;
131 $this->error = $error;
133 Logger::log($url . ': ' . $this->returnCode . " " . $result, Logger::DATA);
135 $this->parseBodyHeader($result);
136 $this->checkSuccess();
137 $this->checkRedirect();
141 private function parseBodyHeader($result)
143 // Pull out multiple headers, e.g. proxy and continuation headers
144 // allow for HTTP/2.x without fixing code
148 while (preg_match('/^HTTP\/.+? \d+/', $base)) {
149 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
151 $base = substr($base, strlen($chunk));
154 $this->body = substr($result, strlen($header));
155 $this->header = $header;
156 $this->header_fields = []; // Is filled on demand
159 private function checkSuccess()
161 $this->isSuccess = ($this->returnCode >= 200 && $this->returnCode <= 299) || $this->errorNumber == 0;
163 // Everything higher or equal 400 is not a success
164 if ($this->returnCode >= 400) {
165 $this->isSuccess = false;
168 if (!$this->isSuccess) {
169 Logger::log('error: ' . $this->url . ': ' . $this->returnCode . ' - ' . $this->error, Logger::INFO);
170 Logger::log('debug: ' . print_r($this->info, true), Logger::DATA);
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 = '';
234 * @return string The Curl Code
236 public function getReturnCode()
238 return $this->returnCode;
242 * Returns the Curl Content Type
244 * @return string the Curl Content Type
246 public function getContentType()
248 return $this->contentType;
252 * Returns the Curl headers
254 * @param string $field optional header field. Return all fields if empty
256 * @return string the Curl headers or the specified content of the header variable
258 public function getHeader(string $field = '')
261 return $this->header;
264 $field = strtolower(trim($field));
266 $headers = $this->getHeaderArray();
268 if (isset($headers[$field])) {
269 return $headers[$field];
276 * Check if a specified header exists
278 * @param string $field header field
280 * @return boolean "true" if header exists
282 public function inHeader(string $field)
284 $field = strtolower(trim($field));
286 $headers = $this->getHeaderArray();
288 return array_key_exists($field, $headers);
292 * Returns the Curl headers as an associated array
294 * @return array associated header array
296 public function getHeaderArray()
298 if (!empty($this->header_fields)) {
299 return $this->header_fields;
302 $this->header_fields = [];
304 $lines = explode("\n", trim($this->header));
305 foreach ($lines as $line) {
306 $parts = explode(':', $line);
307 $headerfield = strtolower(trim(array_shift($parts)));
308 $headerdata = trim(implode(':', $parts));
309 $this->header_fields[$headerfield] = $headerdata;
312 return $this->header_fields;
318 public function isSuccess()
320 return $this->isSuccess;
326 public function getUrl()
334 public function getRedirectUrl()
336 return $this->redirectUrl;
342 public function getBody()
350 public function getInfo()
358 public function isRedirectUrl()
360 return $this->isRedirectUrl;
366 public function getErrorNumber()
368 return $this->errorNumber;
374 public function getError()
382 public function isTimeout()
384 return $this->isTimeout;