2020-09-22 06:04:33 +00:00
|
|
|
<?php
|
|
|
|
class UrlHelper {
|
2021-06-18 08:20:57 +00:00
|
|
|
const EXTRA_HREF_SCHEMES = [
|
2021-06-06 22:51:02 +00:00
|
|
|
"magnet",
|
|
|
|
"mailto",
|
|
|
|
"tel"
|
|
|
|
];
|
|
|
|
|
2022-02-17 19:38:38 +00:00
|
|
|
const EXTRA_SCHEMES_BY_CONTENT_TYPE = [
|
|
|
|
"application/x-bittorrent" => [ "magnet" ],
|
|
|
|
];
|
|
|
|
|
2022-08-12 14:13:26 +00:00
|
|
|
static string $fetch_last_error;
|
|
|
|
static int $fetch_last_error_code;
|
|
|
|
static string $fetch_last_error_content;
|
|
|
|
static string $fetch_last_content_type;
|
|
|
|
static string $fetch_last_modified;
|
|
|
|
static string $fetch_effective_url;
|
|
|
|
static string $fetch_effective_ip_addr;
|
2023-12-22 16:51:04 +00:00
|
|
|
|
|
|
|
private static ?GuzzleHttp\ClientInterface $client = null;
|
|
|
|
|
|
|
|
private static function get_client(): GuzzleHttp\ClientInterface {
|
|
|
|
if (self::$client == null) {
|
|
|
|
self::$client = new GuzzleHttp\Client([
|
|
|
|
GuzzleHttp\RequestOptions::COOKIES => false,
|
|
|
|
GuzzleHttp\RequestOptions::PROXY => Config::get(Config::HTTP_PROXY) ?: null,
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
|
|
|
return self::$client;
|
|
|
|
}
|
2021-11-10 21:38:25 +00:00
|
|
|
|
|
|
|
/**
|
2021-11-11 11:08:04 +00:00
|
|
|
* @param array<string, string|int> $parts
|
2021-11-10 21:38:25 +00:00
|
|
|
*/
|
|
|
|
static function build_url(array $parts): string {
|
2020-12-12 16:04:22 +00:00
|
|
|
$tmp = $parts['scheme'] . "://" . $parts['host'];
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2020-12-12 16:04:22 +00:00
|
|
|
if (isset($parts['path'])) $tmp .= $parts['path'];
|
2020-09-22 06:04:33 +00:00
|
|
|
if (isset($parts['query'])) $tmp .= '?' . $parts['query'];
|
|
|
|
if (isset($parts['fragment'])) $tmp .= '#' . $parts['fragment'];
|
|
|
|
|
|
|
|
return $tmp;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2021-05-21 12:39:41 +00:00
|
|
|
* Converts a (possibly) relative URL to a absolute one, using provided base URL.
|
2021-06-18 08:20:57 +00:00
|
|
|
* Provides some exceptions for additional schemes like data: if called with owning element/attribute.
|
2020-09-22 06:04:33 +00:00
|
|
|
*
|
2021-05-21 12:39:41 +00:00
|
|
|
* @param string $base_url Base URL (i.e. from where the document is)
|
2020-09-22 06:04:33 +00:00
|
|
|
* @param string $rel_url Possibly relative URL in the document
|
2021-06-18 08:30:11 +00:00
|
|
|
* @param string $owner_element Owner element tag name (i.e. "a") (optional)
|
|
|
|
* @param string $owner_attribute Owner attribute (i.e. "href") (optional)
|
2022-02-17 19:38:38 +00:00
|
|
|
* @param string $content_type URL content type as specified by enclosures, etc.
|
2020-09-22 06:04:33 +00:00
|
|
|
*
|
2021-11-15 03:28:17 +00:00
|
|
|
* @return false|string Absolute URL or false on failure (either during URL parsing or validation)
|
2020-09-22 06:04:33 +00:00
|
|
|
*/
|
2022-02-17 19:38:38 +00:00
|
|
|
public static function rewrite_relative($base_url,
|
|
|
|
$rel_url,
|
|
|
|
string $owner_element = "",
|
|
|
|
string $owner_attribute = "",
|
|
|
|
string $content_type = "") {
|
|
|
|
|
2020-09-22 06:04:33 +00:00
|
|
|
$rel_parts = parse_url($rel_url);
|
|
|
|
|
2022-03-22 11:32:32 +00:00
|
|
|
if (!$rel_url) return $base_url;
|
|
|
|
|
2021-11-15 03:28:17 +00:00
|
|
|
/**
|
|
|
|
* If parse_url failed to parse $rel_url return false to match the current "invalid thing" behavior
|
|
|
|
* of UrlHelper::validate().
|
|
|
|
*
|
|
|
|
* TODO: There are many places where a string return value is assumed. We should either update those
|
|
|
|
* to account for the possibility of failure, or look into updating this function's return values.
|
|
|
|
*/
|
|
|
|
if ($rel_parts === false) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2021-02-05 20:41:32 +00:00
|
|
|
if (!empty($rel_parts['host']) && !empty($rel_parts['scheme'])) {
|
2020-09-22 11:54:15 +00:00
|
|
|
return self::validate($rel_url);
|
2021-06-18 08:20:57 +00:00
|
|
|
|
|
|
|
// protocol-relative URL (rare but they exist)
|
2020-09-22 06:04:33 +00:00
|
|
|
} else if (strpos($rel_url, "//") === 0) {
|
2020-09-22 11:54:15 +00:00
|
|
|
return self::validate("https:" . $rel_url);
|
2021-06-18 08:20:57 +00:00
|
|
|
// allow some extra schemes for A href
|
2021-06-18 08:30:11 +00:00
|
|
|
} else if (in_array($rel_parts["scheme"] ?? "", self::EXTRA_HREF_SCHEMES, true) &&
|
2021-06-18 08:20:57 +00:00
|
|
|
$owner_element == "a" &&
|
|
|
|
$owner_attribute == "href") {
|
|
|
|
return $rel_url;
|
2022-02-17 19:38:38 +00:00
|
|
|
// allow some extra schemes for links with feed-specified content type i.e. enclosures
|
|
|
|
} else if ($content_type &&
|
2022-02-18 13:44:03 +00:00
|
|
|
isset(self::EXTRA_SCHEMES_BY_CONTENT_TYPE[$content_type]) &&
|
2022-02-17 19:38:38 +00:00
|
|
|
in_array($rel_parts["scheme"], self::EXTRA_SCHEMES_BY_CONTENT_TYPE[$content_type])) {
|
|
|
|
return $rel_url;
|
2021-06-18 08:20:57 +00:00
|
|
|
// allow limited subset of inline base64-encoded images for IMG elements
|
2021-06-18 10:52:29 +00:00
|
|
|
} else if (($rel_parts["scheme"] ?? "") == "data" &&
|
2021-06-18 08:20:57 +00:00
|
|
|
preg_match('%^image/(webp|gif|jpg|png|svg);base64,%', $rel_parts["path"]) &&
|
|
|
|
$owner_element == "img" &&
|
|
|
|
$owner_attribute == "src") {
|
2020-09-22 06:04:33 +00:00
|
|
|
return $rel_url;
|
|
|
|
} else {
|
2021-05-21 12:39:41 +00:00
|
|
|
$base_parts = parse_url($base_url);
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2021-11-20 13:11:44 +00:00
|
|
|
$rel_parts['host'] = $base_parts['host'] ?? "";
|
|
|
|
$rel_parts['scheme'] = $base_parts['scheme'] ?? "";
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2022-03-22 16:43:32 +00:00
|
|
|
if ($rel_parts['path'] ?? "") {
|
2021-05-21 12:39:41 +00:00
|
|
|
|
2022-03-22 09:24:31 +00:00
|
|
|
// we append dirname() of base path to relative URL path as per RFC 3986 section 5.2.2
|
2022-03-22 16:43:32 +00:00
|
|
|
$base_path = with_trailing_slash(dirname($base_parts['path'] ?? ""));
|
2021-05-21 12:39:41 +00:00
|
|
|
|
2022-03-22 09:24:31 +00:00
|
|
|
// 1. absolute relative path (/test.html) = no-op, proceed as is
|
|
|
|
|
|
|
|
// 2. dotslash relative URI (./test.html) - strip "./", append base path
|
|
|
|
if (strpos($rel_parts['path'], './') === 0) {
|
|
|
|
$rel_parts['path'] = $base_path . substr($rel_parts['path'], 2);
|
|
|
|
// 3. anything else relative (test.html) - append dirname() of base path
|
|
|
|
} else if (strpos($rel_parts['path'], '/') !== 0) {
|
|
|
|
$rel_parts['path'] = $base_path . $rel_parts['path'];
|
2021-05-21 12:39:41 +00:00
|
|
|
}
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2022-03-22 09:24:31 +00:00
|
|
|
//$rel_parts['path'] = str_replace("/./", "/", $rel_parts['path']);
|
|
|
|
//$rel_parts['path'] = str_replace("//", "/", $rel_parts['path']);
|
2020-12-12 16:04:22 +00:00
|
|
|
}
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2020-09-22 11:54:15 +00:00
|
|
|
return self::validate(self::build_url($rel_parts));
|
2020-09-22 06:04:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-14 17:53:30 +00:00
|
|
|
/** extended filtering involves validation for safe ports and loopback
|
|
|
|
* @return false|string false if something went wrong, otherwise the URL string
|
2021-11-10 21:38:25 +00:00
|
|
|
*/
|
|
|
|
static function validate(string $url, bool $extended_filtering = false) {
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2020-09-22 16:56:26 +00:00
|
|
|
$url = clean($url);
|
2020-09-22 06:04:33 +00:00
|
|
|
|
|
|
|
# fix protocol-relative URLs
|
|
|
|
if (strpos($url, "//") === 0)
|
|
|
|
$url = "https:" . $url;
|
|
|
|
|
|
|
|
$tokens = parse_url($url);
|
|
|
|
|
2020-09-22 11:37:45 +00:00
|
|
|
// this isn't really necessary because filter_var(... FILTER_VALIDATE_URL) requires host and scheme
|
|
|
|
// as per https://php.watch/versions/7.3/filter-var-flag-deprecation but it might save time
|
2021-02-05 20:41:32 +00:00
|
|
|
if (empty($tokens['host']))
|
2020-09-22 06:04:33 +00:00
|
|
|
return false;
|
|
|
|
|
|
|
|
if (!in_array(strtolower($tokens['scheme']), ['http', 'https']))
|
|
|
|
return false;
|
|
|
|
|
2020-09-22 12:32:22 +00:00
|
|
|
//convert IDNA hostname to punycode if possible
|
|
|
|
if (function_exists("idn_to_ascii")) {
|
|
|
|
if (mb_detect_encoding($tokens['host']) != 'ASCII') {
|
2020-11-14 12:13:35 +00:00
|
|
|
if (defined('IDNA_NONTRANSITIONAL_TO_ASCII') && defined('INTL_IDNA_VARIANT_UTS46')) {
|
|
|
|
$tokens['host'] = idn_to_ascii($tokens['host'], IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
|
|
|
|
} else {
|
|
|
|
$tokens['host'] = idn_to_ascii($tokens['host']);
|
|
|
|
}
|
2021-11-11 11:08:04 +00:00
|
|
|
|
|
|
|
// if `idn_to_ascii` failed
|
|
|
|
if ($tokens['host'] === false) {
|
|
|
|
return false;
|
|
|
|
}
|
2020-09-22 12:32:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-28 16:46:31 +00:00
|
|
|
// separate set of tokens with urlencoded 'path' because filter_var() rightfully fails on non-latin characters
|
|
|
|
// (used for validation only, we actually request the original URL, in case of urlencode breaking it)
|
|
|
|
$tokens_filter_var = $tokens;
|
|
|
|
|
2021-02-05 20:41:32 +00:00
|
|
|
if ($tokens['path'] ?? false) {
|
2020-09-28 16:46:31 +00:00
|
|
|
$tokens_filter_var['path'] = implode("/",
|
|
|
|
array_map("rawurlencode",
|
|
|
|
array_map("rawurldecode",
|
|
|
|
explode("/", $tokens['path']))));
|
|
|
|
}
|
|
|
|
|
2020-09-22 11:37:45 +00:00
|
|
|
$url = self::build_url($tokens);
|
2020-09-28 16:46:31 +00:00
|
|
|
$url_filter_var = self::build_url($tokens_filter_var);
|
2020-09-22 11:37:45 +00:00
|
|
|
|
2020-09-28 16:46:31 +00:00
|
|
|
if (filter_var($url_filter_var, FILTER_VALIDATE_URL) === false)
|
2020-09-22 11:37:45 +00:00
|
|
|
return false;
|
|
|
|
|
2020-09-22 06:04:33 +00:00
|
|
|
if ($extended_filtering) {
|
2021-02-05 20:41:32 +00:00
|
|
|
if (!in_array($tokens['port'] ?? '', [80, 443, '']))
|
2020-09-22 06:04:33 +00:00
|
|
|
return false;
|
|
|
|
|
|
|
|
if (strtolower($tokens['host']) == 'localhost' || $tokens['host'] == '::1' || strpos($tokens['host'], '127.') === 0)
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return $url;
|
|
|
|
}
|
|
|
|
|
2021-11-10 21:38:25 +00:00
|
|
|
/**
|
2021-11-14 17:53:30 +00:00
|
|
|
* @return false|string
|
2021-11-10 21:38:25 +00:00
|
|
|
*/
|
2023-12-22 16:51:04 +00:00
|
|
|
static function resolve_redirects(string $url, int $timeout) {
|
2023-10-20 19:39:41 +00:00
|
|
|
$span = Tracer::start(__METHOD__);
|
|
|
|
$span->setAttribute('func.args', json_encode(func_get_args()));
|
2023-12-22 16:51:04 +00:00
|
|
|
$client = self::get_client();
|
|
|
|
|
|
|
|
try {
|
|
|
|
$response = $client->request('HEAD', $url, [
|
|
|
|
GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => $timeout ?: Config::get(Config::FILE_FETCH_CONNECT_TIMEOUT),
|
|
|
|
GuzzleHttp\RequestOptions::TIMEOUT => $timeout ?: Config::get(Config::FILE_FETCH_TIMEOUT),
|
|
|
|
GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => ['max' => 10, 'track_redirects' => true, 'http_errors' => false],
|
|
|
|
GuzzleHttp\RequestOptions::HEADERS => [
|
|
|
|
'User-Agent' => Config::get_user_agent(),
|
|
|
|
'Connection' => 'close',
|
|
|
|
],
|
|
|
|
]);
|
|
|
|
} catch (GuzzleHttp\Exception\GuzzleException $ex) {
|
|
|
|
// TODO: catch just the "too many redirects" exception, and set a different 'error' for general issues
|
2023-10-20 19:39:41 +00:00
|
|
|
$span->setAttribute('error', 'too many redirects');
|
|
|
|
$span->end();
|
2020-09-22 06:04:33 +00:00
|
|
|
return false;
|
2023-04-09 20:26:51 +00:00
|
|
|
}
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
// If a history header value doesn't exist there was no redirection and the original URL is fine.
|
|
|
|
$history_header = $response->getHeader(GuzzleHttp\RedirectMiddleware::HISTORY_HEADER);
|
2023-10-20 19:39:41 +00:00
|
|
|
$span->end();
|
2023-12-22 16:51:04 +00:00
|
|
|
return ($history_header ? end($history_header) : $url);
|
2020-09-22 06:04:33 +00:00
|
|
|
}
|
|
|
|
|
2021-11-10 21:38:25 +00:00
|
|
|
/**
|
2021-11-11 11:08:04 +00:00
|
|
|
* @param array<string, bool|int|string>|string $options
|
2021-11-11 22:07:32 +00:00
|
|
|
* @return false|string false if something went wrong, otherwise string contents
|
2021-11-10 21:38:25 +00:00
|
|
|
*/
|
|
|
|
// TODO: max_size currently only works for CURL transfers
|
2020-09-22 06:04:33 +00:00
|
|
|
// TODO: multiple-argument way is deprecated, first parameter is a hash now
|
|
|
|
public static function fetch($options /* previously: 0: $url , 1: $type = false, 2: $login = false, 3: $pass = false,
|
2023-12-23 15:34:21 +00:00
|
|
|
4: $post_query = false, 5: $timeout = false, 6: $timestamp = 0, 7: $useragent = false, 8: $retry_once_request = false,
|
|
|
|
9: $auth_type = "basic" */) {
|
2023-12-22 16:51:04 +00:00
|
|
|
$span = Tracer::start(__METHOD__);
|
|
|
|
$span->setAttribute('func.args', json_encode(func_get_args()));
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2021-11-10 21:38:25 +00:00
|
|
|
self::$fetch_last_error = "";
|
2021-02-28 07:12:57 +00:00
|
|
|
self::$fetch_last_error_code = -1;
|
|
|
|
self::$fetch_last_error_content = "";
|
|
|
|
self::$fetch_last_content_type = "";
|
|
|
|
self::$fetch_last_modified = "";
|
|
|
|
self::$fetch_effective_url = "";
|
|
|
|
self::$fetch_effective_ip_addr = "";
|
2020-09-22 06:04:33 +00:00
|
|
|
|
|
|
|
if (!is_array($options)) {
|
|
|
|
|
|
|
|
// falling back on compatibility shim
|
2023-12-23 15:34:21 +00:00
|
|
|
$option_names = [ "url", "type", "login", "pass", "post_query", "timeout", "last_modified", "useragent", "retry-once-request", "auth_type" ];
|
2020-09-22 06:04:33 +00:00
|
|
|
$tmp = [];
|
|
|
|
|
|
|
|
for ($i = 0; $i < func_num_args(); $i++) {
|
|
|
|
$tmp[$option_names[$i]] = func_get_arg($i);
|
|
|
|
}
|
|
|
|
|
|
|
|
$options = $tmp;
|
|
|
|
|
|
|
|
/*$options = array(
|
|
|
|
"url" => func_get_arg(0),
|
|
|
|
"type" => @func_get_arg(1),
|
|
|
|
"login" => @func_get_arg(2),
|
|
|
|
"pass" => @func_get_arg(3),
|
|
|
|
"post_query" => @func_get_arg(4),
|
|
|
|
"timeout" => @func_get_arg(5),
|
|
|
|
"timestamp" => @func_get_arg(6),
|
2023-12-22 16:51:04 +00:00
|
|
|
"useragent" => @func_get_arg(7),
|
|
|
|
"retry-once-request" => @func_get_arg(8),
|
2023-12-23 15:34:21 +00:00
|
|
|
"auth_type" => @func_get_arg(9),
|
2020-09-22 06:04:33 +00:00
|
|
|
); */
|
|
|
|
}
|
2023-04-09 20:26:51 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
$url = $options["url"];
|
2020-09-22 06:04:33 +00:00
|
|
|
$type = isset($options["type"]) ? $options["type"] : false;
|
|
|
|
$login = isset($options["login"]) ? $options["login"] : false;
|
|
|
|
$pass = isset($options["pass"]) ? $options["pass"] : false;
|
2023-12-23 15:34:21 +00:00
|
|
|
$auth_type = isset($options["auth_type"]) ? $options["auth_type"] : "basic";
|
2020-09-22 06:04:33 +00:00
|
|
|
$post_query = isset($options["post_query"]) ? $options["post_query"] : false;
|
|
|
|
$timeout = isset($options["timeout"]) ? $options["timeout"] : false;
|
|
|
|
$last_modified = isset($options["last_modified"]) ? $options["last_modified"] : "";
|
|
|
|
$useragent = isset($options["useragent"]) ? $options["useragent"] : false;
|
|
|
|
$followlocation = isset($options["followlocation"]) ? $options["followlocation"] : true;
|
2021-02-22 19:35:27 +00:00
|
|
|
$max_size = isset($options["max_size"]) ? $options["max_size"] : Config::get(Config::MAX_DOWNLOAD_FILE_SIZE); // in bytes
|
2020-09-22 06:04:33 +00:00
|
|
|
$http_accept = isset($options["http_accept"]) ? $options["http_accept"] : false;
|
|
|
|
$http_referrer = isset($options["http_referrer"]) ? $options["http_referrer"] : false;
|
|
|
|
|
|
|
|
$url = ltrim($url, ' ');
|
|
|
|
$url = str_replace(' ', '%20', $url);
|
|
|
|
|
2021-11-24 05:19:04 +00:00
|
|
|
Debug::log("[UrlHelper] fetching: $url", Debug::LOG_EXTENDED);
|
|
|
|
|
2020-09-22 11:54:15 +00:00
|
|
|
$url = self::validate($url, true);
|
2020-09-22 06:04:33 +00:00
|
|
|
|
|
|
|
if (!$url) {
|
2023-12-22 16:51:04 +00:00
|
|
|
self::$fetch_last_error = 'Requested URL failed extended validation.';
|
2023-10-20 19:39:41 +00:00
|
|
|
$span->setAttribute('error', self::$fetch_last_error);
|
|
|
|
$span->end();
|
2020-09-22 06:04:33 +00:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
$url_host = parse_url($url, PHP_URL_HOST);
|
|
|
|
$ip_addr = gethostbyname($url_host);
|
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
if (!$ip_addr || strpos($ip_addr, '127.') === 0) {
|
2021-02-28 07:12:57 +00:00
|
|
|
self::$fetch_last_error = "URL hostname failed to resolve or resolved to a loopback address ($ip_addr)";
|
2023-10-20 19:39:41 +00:00
|
|
|
$span->setAttribute('error', self::$fetch_last_error);
|
|
|
|
$span->end();
|
2020-09-22 06:04:33 +00:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
$req_options = [
|
|
|
|
GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => $timeout ?: Config::get(Config::FILE_FETCH_CONNECT_TIMEOUT),
|
|
|
|
GuzzleHttp\RequestOptions::TIMEOUT => $timeout ?: Config::get(Config::FILE_FETCH_TIMEOUT),
|
|
|
|
GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => $followlocation ? ['max' => 20, 'track_redirects' => true] : false,
|
|
|
|
GuzzleHttp\RequestOptions::HEADERS => [
|
|
|
|
'User-Agent' => $useragent ?: Config::get_user_agent(),
|
|
|
|
],
|
2023-12-23 15:34:21 +00:00
|
|
|
'curl' => [],
|
2023-12-22 16:51:04 +00:00
|
|
|
];
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
if ($last_modified && !$post_query)
|
|
|
|
$req_options[GuzzleHttp\RequestOptions::HEADERS]['If-Modified-Since'] = $last_modified;
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
if ($http_accept)
|
|
|
|
$req_options[GuzzleHttp\RequestOptions::HEADERS]['Accept'] = $http_accept;
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
if ($http_referrer)
|
|
|
|
$req_options[GuzzleHttp\RequestOptions::HEADERS]['Referer'] = $http_referrer;
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-23 15:34:21 +00:00
|
|
|
if ($login && $pass && in_array($auth_type, ['basic', 'digest', 'ntlm'])) {
|
|
|
|
// Let Guzzle handle the details for auth types it supports
|
2023-12-22 16:51:04 +00:00
|
|
|
$req_options[GuzzleHttp\RequestOptions::AUTH] = [$login, $pass];
|
2023-12-23 15:34:21 +00:00
|
|
|
} elseif ($auth_type === 'any') {
|
|
|
|
// https://docs.guzzlephp.org/en/stable/faq.html#how-can-i-add-custom-curl-options
|
|
|
|
$req_options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_ANY;
|
|
|
|
if ($login && $pass)
|
|
|
|
$req_options['curl'][\CURLOPT_USERPWD] = "$login:$pass";
|
|
|
|
}
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
if ($post_query)
|
|
|
|
$req_options[GuzzleHttp\RequestOptions::FORM_PARAMS] = $post_query;
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
if ($max_size) {
|
|
|
|
$req_options[GuzzleHttp\RequestOptions::PROGRESS] = function($download_size, $downloaded, $upload_size, $uploaded) use(&$max_size, $url) {
|
|
|
|
//Debug::log("[curl progressfunction] $downloaded $max_size", Debug::$LOG_EXTENDED);
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
if ($downloaded > $max_size) {
|
|
|
|
Debug::log("[UrlHelper] fetch error: max size of $max_size bytes exceeded when downloading $url . Aborting.", Debug::LOG_VERBOSE);
|
|
|
|
throw new \LengthException("Download exceeded size limit");
|
2020-09-22 06:04:33 +00:00
|
|
|
}
|
2023-12-22 16:51:04 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
# Alternative/supplement to `progress` checking
|
|
|
|
$req_options[GuzzleHttp\RequestOptions::ON_HEADERS] = function(Psr\Http\Message\ResponseInterface $response) use(&$max_size, $url) {
|
|
|
|
$content_length = $response->getHeaderLine('Content-Length');
|
|
|
|
if ($content_length > $max_size) {
|
|
|
|
Debug::log("[UrlHelper] fetch error: server indicated (via 'Content-Length: {$content_length}') max size of $max_size bytes " .
|
|
|
|
"would be exceeded when downloading $url . Aborting.", Debug::LOG_VERBOSE);
|
|
|
|
throw new \LengthException("Server sent 'Content-Length' exceeding download limit");
|
2022-08-14 16:38:58 +00:00
|
|
|
}
|
2023-12-22 16:51:04 +00:00
|
|
|
};
|
|
|
|
}
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
$client = self::get_client();
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
try {
|
|
|
|
if (($options['retry-once-request'] ?? null) instanceof Psr\Http\Message\RequestInterface) {
|
|
|
|
$response = $client->send($options['retry-once-request']);
|
|
|
|
} else {
|
|
|
|
$response = $client->request($post_query ? 'POST' : 'GET', $url, $req_options);
|
2020-09-22 06:04:33 +00:00
|
|
|
}
|
2023-12-22 16:51:04 +00:00
|
|
|
} catch (\LengthException $ex) {
|
2023-12-23 15:34:21 +00:00
|
|
|
// Either 'Content-Length' indicated the download limit would be exceeded, or the transfer actually exceeded the download limit.
|
2023-12-22 16:51:04 +00:00
|
|
|
self::$fetch_last_error = (string) $ex;
|
|
|
|
$span->setAttribute('error', self::$fetch_last_error);
|
2023-10-20 19:39:41 +00:00
|
|
|
$span->end();
|
2023-12-22 16:51:04 +00:00
|
|
|
return false;
|
|
|
|
} catch (GuzzleHttp\Exception\GuzzleException $ex) {
|
|
|
|
self::$fetch_last_error = (string) $ex;
|
|
|
|
|
|
|
|
if ($ex instanceof GuzzleHttp\Exception\RequestException) {
|
|
|
|
if ($ex instanceof GuzzleHttp\Exception\BadResponseException) {
|
|
|
|
// 4xx or 5xx
|
|
|
|
self::$fetch_last_error_code = $ex->getResponse()->getStatusCode();
|
|
|
|
|
2023-12-23 15:34:21 +00:00
|
|
|
// If credentials were provided and we got a 403 back, retry once with auth type 'any'
|
|
|
|
// to attempt compatibility with unusual configurations.
|
|
|
|
if ($login && $pass && self::$fetch_last_error_code === 403
|
|
|
|
&& isset($options['auth_type']) && $options['auth_type'] !== 'any') {
|
|
|
|
$options['auth_type'] = 'any';
|
|
|
|
$span->end();
|
|
|
|
return self::fetch($options);
|
|
|
|
}
|
2023-12-22 16:51:04 +00:00
|
|
|
|
|
|
|
self::$fetch_last_content_type = $ex->getResponse()->getHeaderLine('content-type');
|
|
|
|
|
|
|
|
if ($type && strpos(self::$fetch_last_content_type, "$type") === false)
|
|
|
|
self::$fetch_last_error_content = (string) $ex->getResponse()->getBody();
|
|
|
|
} elseif (array_key_exists('errno', $ex->getHandlerContext())) {
|
|
|
|
$errno = (int) $ex->getHandlerContext()['errno'];
|
|
|
|
|
|
|
|
// By default, all supported encoding types are sent via `Accept-Encoding` and decoding of
|
|
|
|
// responses with `Content-Encoding` is automatically attempted. If this fails, we do a
|
|
|
|
// single retry with `Accept-Encoding: none` to try and force an unencoded response.
|
|
|
|
if (($errno === \CURLE_WRITE_ERROR || $errno === \CURLE_BAD_CONTENT_ENCODING) &&
|
|
|
|
!array_key_exists('retry-once-request', $options)) {
|
|
|
|
$options['retry-once-request'] = $ex->getRequest()->withHeader('Accept-Encoding', 'none');
|
2023-12-23 15:34:21 +00:00
|
|
|
$span->end();
|
2023-12-22 16:51:04 +00:00
|
|
|
return self::fetch($options);
|
2020-09-22 06:04:33 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
$span->setAttribute('error', self::$fetch_last_error);
|
|
|
|
$span->end();
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
return false;
|
|
|
|
}
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
// Keep setting expected 'fetch_last_error_code' and 'fetch_last_error' values
|
|
|
|
self::$fetch_last_error_code = $response->getStatusCode();
|
|
|
|
self::$fetch_last_error = "HTTP/{$response->getProtocolVersion()} {$response->getStatusCode()} {$response->getReasonPhrase()}";
|
|
|
|
self::$fetch_last_modified = $response->getHeaderLine('last-modified');
|
|
|
|
self::$fetch_last_content_type = $response->getHeaderLine('content-type');
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
// If a history header value doesn't exist there was no redirection and the original URL is fine.
|
|
|
|
$history_header = $response->getHeader(GuzzleHttp\RedirectMiddleware::HISTORY_HEADER);
|
|
|
|
self::$fetch_effective_url = $history_header ? end($history_header) : $url;
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
if (!self::validate(self::$fetch_effective_url, true)) {
|
|
|
|
self::$fetch_last_error = "URL received after redirection failed extended validation.";
|
|
|
|
$span->setAttribute('error', self::$fetch_last_error);
|
|
|
|
$span->end();
|
|
|
|
return false;
|
|
|
|
}
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
self::$fetch_effective_ip_addr = gethostbyname(parse_url(self::$fetch_effective_url, PHP_URL_HOST));
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
if (!self::$fetch_effective_ip_addr || strpos(self::$fetch_effective_ip_addr, '127.') === 0) {
|
|
|
|
self::$fetch_last_error = 'URL hostname received after redirection failed to resolve or resolved to a loopback address (' .
|
|
|
|
self::$fetch_effective_ip_addr . ')';
|
|
|
|
$span->setAttribute('error', self::$fetch_last_error);
|
|
|
|
$span->end();
|
|
|
|
return false;
|
|
|
|
}
|
2020-09-22 06:04:33 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
$body = (string) $response->getBody();
|
2023-04-09 20:26:51 +00:00
|
|
|
|
2023-12-22 16:51:04 +00:00
|
|
|
if (!$body) {
|
|
|
|
self::$fetch_last_error = 'Successful response, but no content was received.';
|
|
|
|
$span->setAttribute('error', self::$fetch_last_error);
|
|
|
|
$span->end();
|
|
|
|
return false;
|
2020-09-22 06:04:33 +00:00
|
|
|
}
|
2023-12-22 16:51:04 +00:00
|
|
|
|
|
|
|
$span->end();
|
|
|
|
return $body;
|
2020-09-22 06:04:33 +00:00
|
|
|
}
|
|
|
|
|
2021-11-11 11:08:04 +00:00
|
|
|
/**
|
2021-11-14 17:53:30 +00:00
|
|
|
* @return false|string false if the provided URL didn't match expected patterns, otherwise the video ID string
|
2021-11-11 11:08:04 +00:00
|
|
|
*/
|
|
|
|
public static function url_to_youtube_vid(string $url) {
|
2021-05-07 04:37:27 +00:00
|
|
|
$url = str_replace("youtube.com", "youtube-nocookie.com", $url);
|
|
|
|
|
|
|
|
$regexps = [
|
|
|
|
"/\/\/www\.youtube-nocookie\.com\/v\/([\w-]+)/",
|
|
|
|
"/\/\/www\.youtube-nocookie\.com\/embed\/([\w-]+)/",
|
|
|
|
"/\/\/www\.youtube-nocookie\.com\/watch?v=([\w-]+)/",
|
|
|
|
"/\/\/youtu.be\/([\w-]+)/",
|
|
|
|
];
|
|
|
|
|
|
|
|
foreach ($regexps as $re) {
|
|
|
|
$matches = [];
|
|
|
|
|
|
|
|
if (preg_match($re, $url, $matches)) {
|
|
|
|
return $matches[1];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2020-09-22 06:04:33 +00:00
|
|
|
}
|