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\Util;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\System;
30 use Friendica\Network\CurlResult;
37 * If binary flag is true, return binary results.
38 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
39 * to preserve cookies from one request to the next.
41 * @param string $url URL to fetch
42 * @param bool $binary default false
43 * TRUE if asked to return binary results (file download)
44 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
45 * @param string $accept_content supply Accept: header with 'accept_content' as the value
46 * @param string $cookiejar Path to cookie jar file
47 * @param int $redirects The recursion counter for internal use - default 0
49 * @return string The fetched content
50 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
52 public static function fetchUrl(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
54 $ret = self::fetchUrlFull($url, $binary, $timeout, $accept_content, $cookiejar, $redirects);
56 return $ret->getBody();
60 * Curl wrapper with array of return values.
62 * Inner workings and parameters are the same as @ref fetchUrl but returns an array with
63 * all the information collected during the fetch.
65 * @param string $url URL to fetch
66 * @param bool $binary default false
67 * TRUE if asked to return binary results (file download)
68 * @param int $timeout Timeout in seconds, default system config value or 60 seconds
69 * @param string $accept_content supply Accept: header with 'accept_content' as the value
70 * @param string $cookiejar Path to cookie jar file
71 * @param int $redirects The recursion counter for internal use - default 0
73 * @return CurlResult With all relevant information, 'body' contains the actual fetched content.
74 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
76 public static function fetchUrlFull(string $url, bool $binary = false, int $timeout = 0, string $accept_content = '', string $cookiejar = '', int &$redirects = 0)
82 'timeout' => $timeout,
83 'accept_content' => $accept_content,
84 'cookiejar' => $cookiejar
93 * @param string $url URL to fetch
94 * @param bool $binary default false
95 * TRUE if asked to return binary results (file download)
96 * @param array $opts (optional parameters) assoziative array with:
97 * 'accept_content' => supply Accept: header with 'accept_content' as the value
98 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
99 * 'http_auth' => username:password
100 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
101 * 'nobody' => only return the header
102 * 'cookiejar' => path to cookie jar file
103 * 'header' => header array
104 * @param int $redirects The recursion counter for internal use - default 0
107 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
109 public static function curl(string $url, bool $binary = false, array $opts = [], int &$redirects = 0)
111 $stamp1 = microtime(true);
115 if (strlen($url) > 1000) {
116 Logger::log('URL is longer than 1000 characters. Callstack: ' . System::callstack(20), Logger::DEBUG);
117 return CurlResult::createErrorCurl(substr($url, 0, 200));
121 $parts = parse_url($url);
122 $path_parts = explode('/', $parts['path'] ?? '');
123 foreach ($path_parts as $part) {
124 if (strlen($part) <> mb_strlen($part)) {
125 $parts2[] = rawurlencode($part);
130 $parts['path'] = implode('/', $parts2);
131 $url = self::unparseURL($parts);
133 if (self::isUrlBlocked($url)) {
134 Logger::log('domain of ' . $url . ' is blocked', Logger::DATA);
135 return CurlResult::createErrorCurl($url);
138 $ch = @curl_init($url);
140 if (($redirects > 8) || (!$ch)) {
141 return CurlResult::createErrorCurl($url);
144 @curl_setopt($ch, CURLOPT_HEADER, true);
146 if (!empty($opts['cookiejar'])) {
147 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
148 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
151 // These settings aren't needed. We're following the location already.
152 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
153 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
155 if (!empty($opts['accept_content'])) {
159 ['Accept: ' . $opts['accept_content']]
163 if (!empty($opts['header'])) {
164 curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['header']);
167 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
168 @curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
170 $range = intval(DI::config()->get('system', 'curl_range_bytes', 0));
173 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
176 // Without this setting it seems as if some webservers send compressed content
177 // This seems to confuse curl so that it shows this uncompressed.
178 /// @todo We could possibly set this value to "gzip" or something similar
179 curl_setopt($ch, CURLOPT_ENCODING, '');
181 if (!empty($opts['headers'])) {
182 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
185 if (!empty($opts['nobody'])) {
186 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
189 if (!empty($opts['timeout'])) {
190 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
192 $curl_time = DI::config()->get('system', 'curl_timeout', 60);
193 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
196 // by default we will allow self-signed certs
197 // but you can override this
199 $check_cert = DI::config()->get('system', 'verifyssl');
200 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
203 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
206 $proxy = DI::config()->get('system', 'proxy');
208 if (strlen($proxy)) {
209 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
210 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
211 $proxyuser = @DI::config()->get('system', 'proxyuser');
213 if (strlen($proxyuser)) {
214 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
218 if (DI::config()->get('system', 'ipv4_resolve', false)) {
219 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
223 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
226 // don't let curl abort the entire application
227 // if it throws any errors.
229 $s = @curl_exec($ch);
230 $curl_info = @curl_getinfo($ch);
232 // Special treatment for HTTP Code 416
233 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
234 if (($curl_info['http_code'] == 416) && ($range > 0)) {
235 @curl_setopt($ch, CURLOPT_RANGE, '');
236 $s = @curl_exec($ch);
237 $curl_info = @curl_getinfo($ch);
240 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
242 if ($curlResponse->isRedirectUrl()) {
244 Logger::log('curl: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
246 return self::curl($curlResponse->getRedirectUrl(), $binary, $opts, $redirects);
251 DI::profiler()->saveTimestamp($stamp1, 'network', System::callstack());
253 return $curlResponse;
257 * Send POST request to $url
259 * @param string $url URL to post
260 * @param mixed $params array of POST variables
261 * @param array $headers HTTP headers
262 * @param int $redirects Recursion counter for internal use - default = 0
263 * @param int $timeout The timeout in seconds, default system config value or 60 seconds
265 * @return CurlResult The content
266 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
268 public static function post(string $url, $params, array $headers = [], int $timeout = 0, int &$redirects = 0)
270 $stamp1 = microtime(true);
272 if (self::isUrlBlocked($url)) {
273 Logger::log('post_url: domain of ' . $url . ' is blocked', Logger::DATA);
274 return CurlResult::createErrorCurl($url);
278 $ch = curl_init($url);
280 if (($redirects > 8) || (!$ch)) {
281 return CurlResult::createErrorCurl($url);
284 Logger::log('post_url: start ' . $url, Logger::DATA);
286 curl_setopt($ch, CURLOPT_HEADER, true);
287 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
288 curl_setopt($ch, CURLOPT_POST, 1);
289 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
290 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
292 if (DI::config()->get('system', 'ipv4_resolve', false)) {
293 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
296 if (intval($timeout)) {
297 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
299 $curl_time = DI::config()->get('system', 'curl_timeout', 60);
300 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
303 if (!empty($headers)) {
304 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
307 $check_cert = DI::config()->get('system', 'verifyssl');
308 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
311 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
314 $proxy = DI::config()->get('system', 'proxy');
316 if (strlen($proxy)) {
317 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
318 curl_setopt($ch, CURLOPT_PROXY, $proxy);
319 $proxyuser = DI::config()->get('system', 'proxyuser');
320 if (strlen($proxyuser)) {
321 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
325 // don't let curl abort the entire application
326 // if it throws any errors.
328 $s = @curl_exec($ch);
330 $curl_info = curl_getinfo($ch);
332 $curlResponse = new CurlResult($url, $s, $curl_info, curl_errno($ch), curl_error($ch));
334 if ($curlResponse->isRedirectUrl()) {
336 Logger::log('post_url: redirect ' . $url . ' to ' . $curlResponse->getRedirectUrl());
338 return self::post($curlResponse->getRedirectUrl(), $params, $headers, $redirects, $timeout);
343 DI::profiler()->saveTimestamp($stamp1, 'network', System::callstack());
345 // Very old versions of Lighttpd don't like the "Expect" header, so we remove it when needed
346 if ($curlResponse->getReturnCode() == 417) {
349 if (empty($headers)) {
350 $headers = ['Expect:'];
352 if (!in_array('Expect:', $headers)) {
353 array_push($headers, 'Expect:');
356 Logger::info('Server responds with 417, applying workaround', ['url' => $url]);
357 return self::post($url, $params, $headers, $redirects, $timeout);
360 Logger::log('post_url: end ' . $url, Logger::DATA);
362 return $curlResponse;
366 * Return raw post data from a post request
368 * @return string post data
370 public static function postdata()
372 return file_get_contents('php://input');
376 * Check URL to see if it's real
378 * Take a URL from the wild, prepend http:// if necessary
379 * and check DNS to see if it's real (or check if is a valid IP address)
381 * @param string $url The URL to be validated
382 * @return string|boolean The actual working URL, false else
383 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
385 public static function isUrlValid(string $url)
387 if (DI::config()->get('system', 'disable_url_validation')) {
391 // no naked subdomains (allow localhost for tests)
392 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
396 if (substr($url, 0, 4) != 'http') {
397 $url = 'http://' . $url;
400 /// @TODO Really suppress function outcomes? Why not find them + debug them?
401 $h = @parse_url($url);
403 if (!empty($h['host']) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME) || filter_var($h['host'], FILTER_VALIDATE_IP))) {
411 * Checks that email is an actual resolvable internet address
413 * @param string $addr The email address
414 * @return boolean True if it's a valid email address, false if it's not
416 public static function isEmailDomainValid(string $addr)
418 if (DI::config()->get('system', 'disable_email_validation')) {
422 if (! strpos($addr, '@')) {
426 $h = substr($addr, strpos($addr, '@') + 1);
428 // Concerning the @ see here: https://stackoverflow.com/questions/36280957/dns-get-record-a-temporary-server-error-occurred
429 if ($h && (@dns_get_record($h, DNS_A + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP))) {
432 if ($h && @dns_get_record($h, DNS_CNAME + DNS_MX)) {
439 * Check if URL is allowed
441 * Check $url against our list of allowed sites,
442 * wildcards allowed. If allowed_sites is unset return true;
444 * @param string $url URL which get tested
445 * @return boolean True if url is allowed otherwise return false
447 public static function isUrlAllowed(string $url)
449 $h = @parse_url($url);
455 $str_allowed = DI::config()->get('system', 'allowed_sites');
456 if (! $str_allowed) {
462 $host = strtolower($h['host']);
464 // always allow our own site
465 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
469 $fnmatch = function_exists('fnmatch');
470 $allowed = explode(',', $str_allowed);
472 if (count($allowed)) {
473 foreach ($allowed as $a) {
474 $pat = strtolower(trim($a));
475 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
485 * Checks if the provided url domain is on the domain blocklist.
486 * Returns true if it is or malformed URL, false if not.
488 * @param string $url The url to check the domain from
492 public static function isUrlBlocked(string $url)
494 $host = @parse_url($url, PHP_URL_HOST);
499 $domain_blocklist = DI::config()->get('system', 'blocklist', []);
500 if (!$domain_blocklist) {
504 foreach ($domain_blocklist as $domain_block) {
505 if (fnmatch(strtolower($domain_block['domain']), strtolower($host))) {
514 * Check if email address is allowed to register here.
516 * Compare against our list (wildcards allowed).
518 * @param string $email email address
519 * @return boolean False if not allowed, true if allowed
520 * or if allowed list is not configured
521 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
523 public static function isEmailDomainAllowed(string $email)
525 $domain = strtolower(substr($email, strpos($email, '@') + 1));
530 $str_allowed = DI::config()->get('system', 'allowed_email', '');
531 if (empty($str_allowed)) {
535 $allowed = explode(',', $str_allowed);
537 return self::isDomainAllowed($domain, $allowed);
541 * Checks for the existence of a domain in a domain list
543 * @param string $domain
544 * @param array $domain_list
547 public static function isDomainAllowed(string $domain, array $domain_list)
551 foreach ($domain_list as $item) {
552 $pat = strtolower(trim($item));
553 if (fnmatch($pat, $domain) || ($pat == $domain)) {
562 public static function lookupAvatarByEmail(string $email)
564 $avatar['size'] = 300;
565 $avatar['email'] = $email;
567 $avatar['success'] = false;
569 Hook::callAll('avatar_lookup', $avatar);
571 if (! $avatar['success']) {
572 $avatar['url'] = DI::baseUrl() . '/images/person-300.jpg';
575 Logger::log('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], Logger::DEBUG);
576 return $avatar['url'];
580 * Remove Google Analytics and other tracking platforms params from URL
582 * @param string $url Any user-submitted URL that may contain tracking params
583 * @return string The same URL stripped of tracking parameters
585 public static function stripTrackingQueryParams(string $url)
587 $urldata = parse_url($url);
588 if (!empty($urldata["query"])) {
589 $query = $urldata["query"];
590 parse_str($query, $querydata);
592 if (is_array($querydata)) {
593 foreach ($querydata as $param => $value) {
597 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
598 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
599 "fb_action_ids", "fb_action_types", "fb_ref",
601 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
604 $pair = $param . "=" . urlencode($value);
605 $url = str_replace($pair, "", $url);
607 // Second try: if the url isn't encoded completely
608 $pair = $param . "=" . str_replace(" ", "+", $value);
609 $url = str_replace($pair, "", $url);
611 // Third try: Maybey the url isn't encoded at all
612 $pair = $param . "=" . $value;
613 $url = str_replace($pair, "", $url);
615 $url = str_replace(["?&", "&&"], ["?", ""], $url);
620 if (substr($url, -1, 1) == "?") {
621 $url = substr($url, 0, -1);
629 * Add a missing base path (scheme and host) to a given url
632 * @param string $basepath
635 public static function addBasePath(string $url, string $basepath)
637 if (!empty(parse_url($url, PHP_URL_SCHEME)) || empty(parse_url($basepath, PHP_URL_SCHEME)) || empty($url) || empty(parse_url($url))) {
641 $base = ['scheme' => parse_url($basepath, PHP_URL_SCHEME),
642 'host' => parse_url($basepath, PHP_URL_HOST)];
644 $parts = array_merge($base, parse_url('/' . ltrim($url, '/')));
645 return self::unparseURL($parts);
649 * Returns the original URL of the provided URL
651 * This function strips tracking query params and follows redirections, either
652 * through HTTP code or meta refresh tags. Stops after 10 redirections.
654 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
656 * @see ParseUrl::getSiteinfo
658 * @param string $url A user-submitted URL
659 * @param int $depth The current redirection recursion level (internal)
660 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
661 * @return string A canonical URL
662 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
664 public static function finalUrl(string $url, int $depth = 1, bool $fetchbody = false)
668 $url = self::stripTrackingQueryParams($url);
674 $url = trim($url, "'");
676 $stamp1 = microtime(true);
679 curl_setopt($ch, CURLOPT_URL, $url);
680 curl_setopt($ch, CURLOPT_HEADER, 1);
681 curl_setopt($ch, CURLOPT_NOBODY, 1);
682 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
683 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
684 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
687 $curl_info = @curl_getinfo($ch);
688 $http_code = $curl_info['http_code'];
691 DI::profiler()->saveTimestamp($stamp1, "network", System::callstack());
693 if ($http_code == 0) {
697 if (in_array($http_code, ['301', '302'])) {
698 if (!empty($curl_info['redirect_url'])) {
699 return self::finalUrl($curl_info['redirect_url'], ++$depth, $fetchbody);
700 } elseif (!empty($curl_info['location'])) {
701 return self::finalUrl($curl_info['location'], ++$depth, $fetchbody);
705 // Check for redirects in the meta elements of the body if there are no redirects in the header.
707 return(self::finalUrl($url, ++$depth, true));
710 // if the file is too large then exit
711 if ($curl_info["download_content_length"] > 1000000) {
715 // if it isn't a HTML file then exit
716 if (!empty($curl_info["content_type"]) && !strstr(strtolower($curl_info["content_type"]), "html")) {
720 $stamp1 = microtime(true);
723 curl_setopt($ch, CURLOPT_URL, $url);
724 curl_setopt($ch, CURLOPT_HEADER, 0);
725 curl_setopt($ch, CURLOPT_NOBODY, 0);
726 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
727 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
728 curl_setopt($ch, CURLOPT_USERAGENT, $a->getUserAgent());
730 $body = curl_exec($ch);
733 DI::profiler()->saveTimestamp($stamp1, "network", System::callstack());
735 if (trim($body) == "") {
739 // Check for redirect in meta elements
740 $doc = new DOMDocument();
741 @$doc->loadHTML($body);
743 $xpath = new DomXPath($doc);
745 $list = $xpath->query("//meta[@content]");
746 foreach ($list as $node) {
748 if ($node->attributes->length) {
749 foreach ($node->attributes as $attribute) {
750 $attr[$attribute->name] = $attribute->value;
754 if (@$attr["http-equiv"] == 'refresh') {
755 $path = $attr["content"];
756 $pathinfo = explode(";", $path);
757 foreach ($pathinfo as $value) {
758 if (substr(strtolower($value), 0, 4) == "url=") {
759 return self::finalUrl(substr($value, 4), ++$depth);
769 * Find the matching part between two url
771 * @param string $url1
772 * @param string $url2
773 * @return string The matching part
775 public static function getUrlMatch(string $url1, string $url2)
777 if (($url1 == "") || ($url2 == "")) {
781 $url1 = Strings::normaliseLink($url1);
782 $url2 = Strings::normaliseLink($url2);
784 $parts1 = parse_url($url1);
785 $parts2 = parse_url($url2);
787 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
791 if (empty($parts1["scheme"])) {
792 $parts1["scheme"] = '';
794 if (empty($parts2["scheme"])) {
795 $parts2["scheme"] = '';
798 if ($parts1["scheme"] != $parts2["scheme"]) {
802 if (empty($parts1["host"])) {
803 $parts1["host"] = '';
805 if (empty($parts2["host"])) {
806 $parts2["host"] = '';
809 if ($parts1["host"] != $parts2["host"]) {
813 if (empty($parts1["port"])) {
814 $parts1["port"] = '';
816 if (empty($parts2["port"])) {
817 $parts2["port"] = '';
820 if ($parts1["port"] != $parts2["port"]) {
824 $match = $parts1["scheme"]."://".$parts1["host"];
826 if ($parts1["port"]) {
827 $match .= ":".$parts1["port"];
830 if (empty($parts1["path"])) {
831 $parts1["path"] = '';
833 if (empty($parts2["path"])) {
834 $parts2["path"] = '';
837 $pathparts1 = explode("/", $parts1["path"]);
838 $pathparts2 = explode("/", $parts2["path"]);
843 $path1 = $pathparts1[$i] ?? '';
844 $path2 = $pathparts2[$i] ?? '';
846 if ($path1 == $path2) {
849 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
853 return Strings::normaliseLink($match);
857 * Glue url parts together
859 * @param array $parsed URL parts
861 * @return string The glued URL
863 public static function unparseURL(array $parsed)
865 $get = function ($key) use ($parsed) {
866 return isset($parsed[$key]) ? $parsed[$key] : null;
869 $pass = $get('pass');
870 $user = $get('user');
871 $userinfo = $pass !== null ? "$user:$pass" : $user;
872 $port = $get('port');
873 $scheme = $get('scheme');
874 $query = $get('query');
875 $fragment = $get('fragment');
876 $authority = ($userinfo !== null ? $userinfo."@" : '') .
878 ($port ? ":$port" : '');
880 return (strlen($scheme) ? $scheme.":" : '') .
881 (strlen($authority) ? "//".$authority : '') .
883 (strlen($query) ? "?".$query : '') .
884 (strlen($fragment) ? "#".$fragment : '');
889 * Switch the scheme of an url between http and https
891 * @param string $url URL
893 * @return string switched URL
895 public static function switchScheme(string $url)
897 $scheme = parse_url($url, PHP_URL_SCHEME);
898 if (empty($scheme)) {
902 if ($scheme === 'http') {
903 $url = str_replace('http://', 'https://', $url);
904 } elseif ($scheme === 'https') {
905 $url = str_replace('https://', 'http://', $url);
912 * Adds query string parameters to the provided URI. Replace the value of existing keys.
914 * @param string $path
915 * @param array $additionalParams Associative array of parameters
918 public static function appendQueryParam(string $path, array $additionalParams)
920 $parsed = parse_url($path);
923 if (!empty($parsed['query'])) {
924 parse_str($parsed['query'], $params);
927 $params = array_merge($params, $additionalParams);
929 $parsed['query'] = http_build_query($params);
931 return self::unparseURL($parsed);
935 * Generates ETag and Last-Modified response headers and checks them against
936 * If-None-Match and If-Modified-Since request headers if present.
938 * Blocking function, sends 304 headers and exits if check passes.
940 * @param string $etag The page etag
941 * @param string $last_modified The page last modification UTC date
944 public static function checkEtagModified(string $etag, string $last_modified)
946 $last_modified = DateTimeFormat::utc($last_modified, 'D, d M Y H:i:s') . ' GMT';
949 * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26
951 $if_none_match = filter_input(INPUT_SERVER, 'HTTP_IF_NONE_MATCH');
952 $if_modified_since = filter_input(INPUT_SERVER, 'HTTP_IF_MODIFIED_SINCE');
953 $flag_not_modified = null;
954 if ($if_none_match) {
956 preg_match('/^(?:W\/")?([^"]+)"?$/i', $etag, $result);
957 $etagTrimmed = $result[1];
958 // Lazy exact ETag match, could check weak/strong ETags
959 $flag_not_modified = $if_none_match == '*' || strpos($if_none_match, $etagTrimmed) !== false;
962 if ($if_modified_since && (!$if_none_match || $flag_not_modified)) {
963 // Lazy exact Last-Modified match, could check If-Modified-Since validity
964 $flag_not_modified = $if_modified_since == $last_modified;
967 header('Etag: ' . $etag);
968 header('Last-Modified: ' . $last_modified);
970 if ($flag_not_modified) {
971 header("HTTP/1.1 304 Not Modified");