1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
|
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik;
use Exception;
use Matomo\Network\IPUtils;
use Piwik\Config\GeneralConfig;
/**
* Provides URL related helper methods.
*
* This class provides simple methods that can be used to parse and modify
* the current URL. It is most useful when plugins need to redirect the current
* request to a URL and when they need to link to other parts of Piwik in
* HTML.
*
* ### Examples
*
* **Redirect to a different controller action**
*
* public function myControllerAction()
* {
* $url = Url::getCurrentQueryStringWithParametersModified(array(
* 'module' => 'DevicesDetection',
* 'action' => 'index'
* ));
* Url::redirectToUrl($url);
* }
*
* **Link to a different controller action in a template**
*
* public function myControllerAction()
* {
* $url = Url::getCurrentQueryStringWithParametersModified(array(
* 'module' => 'UserCountryMap',
* 'action' => 'realtimeMap',
* 'changeVisitAlpha' => 0,
* 'removeOldVisits' => 0
* ));
* $view = new View("@MyPlugin/myPopup");
* $view->realtimeMapUrl = $url;
* return $view->render();
* }
*
*/
class Url
{
/**
* Returns the current URL.
*
* @return string eg, `"https://example.org/dir1/dir2/index.php?param1=value1¶m2=value2"`
* @api
*/
public static function getCurrentUrl()
{
return self::getCurrentScheme() . '://'
. self::getCurrentHost()
. self::getCurrentScriptName(false)
. self::getCurrentQueryString();
}
/**
* Returns the current URL without the query string.
*
* @param bool $checkTrustedHost Whether to do trusted host check. Should ALWAYS be true,
* except in {@link Piwik\Plugin\Controller}.
* @return string eg, `"https://example.org/dir1/dir2/index.php"` if the current URL is
* `"https://example.org/dir1/dir2/index.php?param1=value1¶m2=value2"`.
* @api
*/
public static function getCurrentUrlWithoutQueryString($checkTrustedHost = true)
{
return self::getCurrentScheme() . '://'
. self::getCurrentHost($default = 'unknown', $checkTrustedHost)
. self::getCurrentScriptName(false);
}
/**
* Returns the current URL without the query string and without the name of the file
* being executed.
*
* @return string eg, `"https://example.org/dir1/dir2/"` if the current URL is
* `"https://example.org/dir1/dir2/index.php?param1=value1¶m2=value2"`.
* @api
*/
public static function getCurrentUrlWithoutFileName()
{
return self::getCurrentScheme() . '://'
. self::getCurrentHost()
. self::getCurrentScriptPath();
}
/**
* Returns the path to the script being executed. The script file name is not included.
*
* @return string eg, `"/dir1/dir2/"` if the current URL is
* `"https://example.org/dir1/dir2/index.php?param1=value1¶m2=value2"`
* @api
*/
public static function getCurrentScriptPath()
{
$queryString = self::getCurrentScriptName();
//add a fake letter case /test/test2/ returns /test which is not expected
$urlDir = dirname($queryString . 'x');
$urlDir = str_replace('\\', '/', $urlDir);
// if we are in a subpath we add a trailing slash
if (strlen($urlDir) > 1) {
$urlDir .= '/';
}
return $urlDir;
}
/**
* Returns the path to the script being executed. Includes the script file name.
*
* @param bool $removePathInfo If true (default value) then the PATH_INFO will be stripped.
* @return string eg, `"/dir1/dir2/index.php"` if the current URL is
* `"https://example.org/dir1/dir2/index.php?param1=value1¶m2=value2"`
* @api
*/
public static function getCurrentScriptName($removePathInfo = true)
{
$url = '';
// insert extra path info if proxy_uri_header is set and enabled
$proxyUriHeader = GeneralConfig::getConfigValue('proxy_uri_header');
if (
is_scalar($proxyUriHeader)
&& (int)$proxyUriHeader === 1
&& !empty($_SERVER['HTTP_X_FORWARDED_URI'])
) {
$url .= $_SERVER['HTTP_X_FORWARDED_URI'];
}
if (!empty($_SERVER['REQUEST_URI'])) {
$url .= $_SERVER['REQUEST_URI'];
// strip https://host (Apache+Rails anomaly)
if (preg_match('~^https?://[^/]+($|/.*)~D', $url, $matches)) {
$url = $matches[1];
}
// strip parameters
if (($pos = mb_strpos($url, "?")) !== false) {
$url = mb_substr($url, 0, $pos);
}
// strip path_info
if ($removePathInfo && !empty($_SERVER['PATH_INFO'])) {
$url = mb_substr($url, 0, -mb_strlen($_SERVER['PATH_INFO']));
}
}
/**
* SCRIPT_NAME is our fallback, though it may not be set correctly
*
* @see https://php.net/manual/en/reserved.variables.php
*/
if (empty($url)) {
if (isset($_SERVER['SCRIPT_NAME'])) {
$url = $_SERVER['SCRIPT_NAME'];
} elseif (isset($_SERVER['SCRIPT_FILENAME'])) {
$url = $_SERVER['SCRIPT_FILENAME'];
} elseif (isset($_SERVER['argv'])) {
$url = $_SERVER['argv'][0];
}
}
// A hash part should actually be never send to the server, as browsers automatically remove them from the request
// The same happens for tools like cUrl. While Apache won't answer requests that contain them, Nginx would handle them
// and the hash part would be included in REQUEST_URI. Therefor we always remove any hash parts here.
if (mb_strpos($url, '#') > 0) {
$url = mb_substr($url, 0, mb_strpos($url, '#'));
}
// replace relative path references with absolute.
if (strlen($url) > 0) {
$urlSections = explode('/', $url);
$absoluteUrlComponents = [];
foreach ($urlSections as $section) {
if ($section === '.' || $section === '~') {
continue;
}
if ($section === '..') {
if (!empty($absoluteUrlComponents)) {
array_pop($absoluteUrlComponents);
}
continue;
}
$absoluteUrlComponents[] = $section;
}
$url = implode('/', $absoluteUrlComponents);
}
// to handle instances of empty strings that don't appear at either end
// of the url, and creates double slashes in the resulting url.
$url = str_replace('//', '/', $url);
if (!str_starts_with($url, '/')) {
$url = '/' . $url;
}
return $url;
}
/**
* Returns the current URL's protocol.
*
* @return string `'https'` or `'http'`
* @api
*/
public static function getCurrentScheme()
{
if (self::isPiwikConfiguredToAssumeSecureConnection()) {
return 'https';
}
return self::getCurrentSchemeFromRequestHeader();
}
/**
* Validates the **Host** HTTP header (untrusted user input). Used to prevent Host header
* attacks.
*
* @param string|null|false $host Contents of Host: header from the HTTP request. If `false`, gets the
* value from the request.
* @return bool `true` if valid; `false` otherwise.
*/
public static function isValidHost($host = false): bool
{
// only do trusted host check if it's enabled
if (
isset(Config::getInstance()->General['enable_trusted_host_check'])
&& Config::getInstance()->General['enable_trusted_host_check'] == 0
) {
return true;
}
if (false === $host || null === $host) {
$host = self::getHostFromServerVariable();
if (empty($host)) {
// if no current host, assume valid
return true;
}
}
// if host is in hardcoded allowlist, assume it's valid
if (in_array($host, self::getAlwaysTrustedHosts())) {
return true;
}
$trustedHosts = self::getTrustedHosts();
// Only punctuation we allow is '[', ']', ':', '.', '_' and '-'
$hostLength = strlen($host);
if ($hostLength !== strcspn($host, '`~!@#$%^&*()+={}\\|;"\'<>,?/ ')) {
return false;
}
// if no trusted hosts, just assume it's valid
if (empty($trustedHosts)) {
self::saveTrustedHostnameInConfig($host);
return true;
}
// Escape trusted hosts for preg_match call below
foreach ($trustedHosts as &$trustedHost) {
$trustedHost = preg_quote($trustedHost);
}
$trustedHosts = str_replace("/", "\\/", $trustedHosts);
$untrustedHost = mb_strtolower($host);
$untrustedHost = rtrim($untrustedHost, '.');
$hostRegex = mb_strtolower('/(^|\.)(' . implode('|', $trustedHosts) . ')$/');
$result = preg_match($hostRegex, $untrustedHost);
return 0 !== $result;
}
/**
* Records one host, or an array of hosts in the config file,
* if user is Super User
*
* @static
* @param string|string[] $host
* @return bool
*/
public static function saveTrustedHostnameInConfig($host)
{
return self::saveHostsnameInConfig($host, 'General', 'trusted_hosts');
}
/**
* @param string|string[] $host
* @return bool
* @deprecated no longer in use, will be removed with Matomo 6
*/
public static function saveCORSHostnameInConfig($host)
{
return self::saveHostsnameInConfig($host, 'General', 'cors_domains');
}
/**
* @param string|string[] $host
* @param string $domain
* @param string $key
* @return bool
*/
protected static function saveHostsnameInConfig($host, $domain, $key)
{
if (
Piwik::hasUserSuperUserAccess()
&& file_exists(Config::getLocalConfigPath())
) {
$config = Config::getInstance()->$domain;
if (!is_array($host)) {
$host = [$host];
}
$host = array_filter($host);
if (empty($host)) {
return false;
}
$config[$key] = $host;
Config::getInstance()->$domain = $config;
Config::getInstance()->forceSave();
return true;
}
return false;
}
/**
* Returns the current host.
*
* @param bool $checkIfTrusted Whether to do trusted host check. Should ALWAYS be true,
* except in Controller.
* @return string|false eg, `"demo.matomo.cloud"` or false if no host found.
*/
public static function getHost($checkIfTrusted = true)
{
$host = self::getHostFromServerVariable();
if (!empty($host) && (!$checkIfTrusted || self::isValidHost($host))) {
return $host;
}
try {
$hosts = self::getTrustedHosts();
if (count($hosts) > 0) {
return $hosts[0];
}
} catch (\Exception $e) {
// fall back
}
return false;
}
/**
* @return string|false
*/
protected static function getHostFromServerVariable()
{
try {
// this fails when trying to get the hostname before the config was initialized
// e.g. for loading the domain specific configuration file
// in such a case we always use HTTP_HOST
$preferServerName = GeneralConfig::getConfigValue('host_validation_use_server_name');
} catch (\Exception $e) {
$preferServerName = false;
}
if ($preferServerName && strlen($host = self::getHostFromServerNameVar())) {
return $host;
} elseif (isset($_SERVER['HTTP_HOST']) && strlen($host = $_SERVER['HTTP_HOST'])) {
return $host;
}
return false;
}
/**
* Returns the valid hostname (according to RFC standards) as a string; else it will return false if it isn't valid.
* If the hostname isn't supplied it will default to using Url::getHost
* Note: this will not verify if the hostname is trusted.
* @param string|null $hostname
* @return false|string
*/
public static function getRFCValidHostname($hostname = null)
{
if (empty($hostname)) {
$hostname = self::getHost(false);
}
return filter_var($hostname, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME);
}
/**
* Sets the host. Useful for CLI scripts, eg. core:archive command
*
* @param string $host
* @return void
*/
public static function setHost($host)
{
$_SERVER['SERVER_NAME'] = $host;
$_SERVER['HTTP_HOST'] = $host;
unset($_SERVER['SERVER_PORT']);
}
/**
* Returns the current host.
*
* @param string $default Default value to return if host unknown
* @param bool $checkTrustedHost Whether to do trusted host check. Should ALWAYS be true,
* except in Controller.
* @return string eg, `"example.org"` if the current URL is
* `"https://example.org/dir1/dir2/index.php?param1=value1¶m2=value2"`
* @api
*/
public static function getCurrentHost($default = 'unknown', $checkTrustedHost = true)
{
$hostHeaders = [];
$hostHeadersInConfig = GeneralConfig::getConfigValue('proxy_host_headers');
if (is_array($hostHeadersInConfig)) {
$hostHeaders = $hostHeadersInConfig;
}
$host = self::getHost($checkTrustedHost);
$default = Common::sanitizeInputValue($host ? $host : $default);
return IP::getNonProxyIpFromHeader($default, $hostHeaders);
}
/**
* Returns the query string of the current URL.
*
* @return string eg, `"?param1=value1¶m2=value2"` if the current URL is
* `"https://example.org/dir1/dir2/index.php?param1=value1¶m2=value2"`
* @api
*/
public static function getCurrentQueryString()
{
$url = '';
if (
isset($_SERVER['QUERY_STRING'])
&& !empty($_SERVER['QUERY_STRING'])
) {
$url .= "?" . $_SERVER['QUERY_STRING'];
}
return $url;
}
/**
* Returns an array mapping query parameter names with query parameter values for
* the current URL.
*
* @return array If current URL is `"https://example.org/dir1/dir2/index.php?param1=value1¶m2=value2"`
* this will return:
*
* array(
* 'param1' => string 'value1',
* 'param2' => string 'value2'
* )
* @api
*/
public static function getArrayFromCurrentQueryString()
{
$queryString = self::getCurrentQueryString();
return UrlHelper::getArrayFromQueryString($queryString);
}
/**
* Modifies the current query string with the supplied parameters and returns
* the result. Parameters in the current URL will be overwritten with values
* in `$params` and parameters absent from the current URL but present in `$params`
* will be added to the result.
*
* @param array $params set of parameters to modify/add in the current URL
* eg, `array('param3' => 'value3')`
* @return string eg, `"?param2=value2¶m3=value3"`
* @api
*/
public static function getCurrentQueryStringWithParametersModified($params)
{
$urlValues = self::getArrayFromCurrentQueryString();
foreach ($params as $key => $value) {
$urlValues[$key] = $value;
}
$query = self::getQueryStringFromParameters($urlValues);
if (strlen($query) > 0) {
return '?' . $query;
}
return '';
}
/**
* Converts an array of parameters name => value mappings to a query
* string. Values must already be URL encoded before you call this function.
*
* @param array $parameters eg. `array('param1' => 10, 'param2' => array(1,2))`
* @return string eg. `"param1=10¶m2[]=1¶m2[]=2"`
* @api
*/
public static function getQueryStringFromParameters($parameters)
{
$query = '';
foreach ($parameters as $name => $value) {
if (is_null($value) || $value === false) {
continue;
}
if (is_array($value)) {
foreach ($value as $theValue) {
$query .= $name . "[]=" . $theValue . "&";
}
} else {
$query .= $name . "=" . $value . "&";
}
}
$query = substr($query, 0, -1);
return $query;
}
/**
* @param string $url
* @return string|false|null
*/
public static function getQueryStringFromUrl($url)
{
return parse_url($url, PHP_URL_QUERY);
}
/**
* Redirects the user to the referrer. If no referrer exists, the user is redirected
* to the current URL without query string.
*
* @return void
* @api
*/
public static function redirectToReferrer()
{
$referrer = self::getReferrer();
if ($referrer !== false) {
self::redirectToUrl($referrer);
}
self::redirectToUrl(self::getCurrentUrlWithoutQueryString());
}
private static function redirectToUrlNoExit(string $url): void
{
if (
UrlHelper::isLookLikeUrl($url)
|| strpos($url, 'index.php') === 0
) {
Common::sendResponseCode(302);
Common::sendHeader("X-Robots-Tag: noindex");
Common::sendHeader("Location: $url");
} else {
echo "Invalid URL to redirect to.";
}
if (Common::isPhpCliMode()) {
throw new Exception("If you were using a browser, Matomo would redirect you to this URL: $url \n\n");
}
}
/**
* Redirects the user to the specified URL.
*
* @param string $url
* @return void
* @throws Exception
* @api
*/
public static function redirectToUrl($url)
{
// Close the session manually.
// We should not have to call this because it was registered via register_shutdown_function,
// but it is not always called fast enough
Session::close();
self::redirectToUrlNoExit($url);
exit;
}
/**
* If the page is using HTTP, redirect to the same page over HTTPS
*
* @return void
*/
public static function redirectToHttps()
{
if (ProxyHttp::isHttps()) {
return;
}
$url = self::getCurrentUrl();
$url = str_replace("http://", "https://", $url);
self::redirectToUrl($url);
}
/**
* Returns the **HTTP_REFERER** `$_SERVER` variable, or `false` if not found.
*
* @return string|false
* @api
*/
public static function getReferrer()
{
if (!empty($_SERVER['HTTP_REFERER'])) {
return $_SERVER['HTTP_REFERER'];
}
return false;
}
/**
* Returns `true` if the URL points to something on the same host, `false` if otherwise.
*
* @param string $url
* @return bool True if local; false otherwise.
* @api
*/
public static function isLocalUrl($url)
{
if (empty($url)) {
return true;
}
// handle host name mangling
$requestUri = isset($_SERVER['SCRIPT_URI']) ? $_SERVER['SCRIPT_URI'] : '';
$parseRequest = @parse_url($requestUri);
$hosts = [self::getHost(), self::getCurrentHost()];
if (!empty($parseRequest['host'])) {
$hosts[] = $parseRequest['host'];
}
// drop invalid host values and port numbers from hostnames/IPs
$hosts = array_filter($hosts, 'is_string');
$hosts = array_map(self::class . '::getHostSanitized', $hosts);
$disableHostCheck = GeneralConfig::getConfigValue('enable_trusted_host_check') == 0;
// compare scheme and host
$parsedUrl = @parse_url($url);
$host = IPUtils::sanitizeIp($parsedUrl['host'] ?? '');
return !empty($host)
&& ($disableHostCheck || in_array($host, $hosts))
&& !empty($parsedUrl['scheme'])
&& in_array($parsedUrl['scheme'], ['http', 'https']);
}
/**
* Checks whether the given host is a local host like `127.0.0.1` or `localhost`.
*
* @param string $host
* @return bool
*/
public static function isLocalHost($host)
{
if (empty($host)) {
return false;
}
// remove port
$hostWithoutPort = explode(':', $host);
array_pop($hostWithoutPort);
$hostWithoutPort = implode(':', $hostWithoutPort);
$localHostnames = Url::getLocalHostnames();
return in_array($host, $localHostnames, true)
|| in_array($hostWithoutPort, $localHostnames, true);
}
/**
* @return string[]
*/
public static function getTrustedHostsFromConfig()
{
$hosts = self::getHostsFromConfig('General', 'trusted_hosts');
// Case user wrote in the config, https://example.com/test instead of example.com
foreach ($hosts as &$host) {
if (UrlHelper::isLookLikeUrl($host)) {
$host = parse_url($host, PHP_URL_HOST);
}
}
return $hosts;
}
/**
* @return string[]
*/
public static function getTrustedHosts()
{
return self::getTrustedHostsFromConfig();
}
/**
* @return string[]
*/
public static function getCorsHostsFromConfig()
{
return self::getHostsFromConfig('General', 'cors_domains');
}
/**
* Returns hostname, without port numbers
*
* @param string $host
* @return string
*/
public static function getHostSanitized($host)
{
if (!class_exists("Matomo\\Network\\IPUtils")) {
throw new Exception("Matomo\\Network\\IPUtils could not be found, maybe you are using Matomo from git and need to update Composer. $ php composer.phar update");
}
return IPUtils::sanitizeIp($host);
}
/**
* @param string $domain
* @param string $key
* @return string[]
*/
protected static function getHostsFromConfig($domain, $key)
{
$config = @Config::getInstance()->$domain;
if (!isset($config[$key])) {
return [];
}
$hosts = $config[$key];
if (!is_array($hosts)) {
return [];
}
return $hosts;
}
/**
* Returns the host part of any valid URL.
*
* @param string $url Any fully qualified URL
* @return string|null The actual host in lower case or null if $url is not a valid fully qualified URL.
*/
public static function getHostFromUrl($url)
{
if (!is_string($url)) {
return null;
}
$urlHost = parse_url($url, PHP_URL_HOST);
if (empty($urlHost)) {
return null;
}
return mb_strtolower($urlHost);
}
/**
* Checks whether any of the given URLs has the given host. If not, we will also check whether any URL uses a
* subdomain of the given host. For instance if host is "example.com" and a URL is "https://www.example.com" we
* consider this as valid and return true. The always trusted hosts such as "127.0.0.1" are considered valid as well.
*
* @param string $host
* @param string[] $urls
* @return bool
*/
public static function isHostInUrls($host, $urls)
{
if (empty($host)) {
return false;
}
$host = mb_strtolower($host);
if (!empty($urls)) {
foreach ($urls as $url) {
if (mb_strtolower($url) === $host) {
return true;
}
$siteHost = self::getHostFromUrl($url);
if ($siteHost === $host) {
return true;
}
if (Common::stringEndsWith($siteHost, '.' . $host)) {
// allow subdomains
return true;
}
}
}
return in_array($host, self::getAlwaysTrustedHosts());
}
/**
* List of hosts that are never checked for validity.
*
* @return string[]
*/
private static function getAlwaysTrustedHosts(): array
{
return self::getLocalHostnames();
}
/**
* @return string[]
*/
public static function getLocalHostnames(): array
{
return ['localhost', '127.0.0.1', '::1', '[::1]', '[::]', '0000::1', '0177.0.0.1', '2130706433', '[0:0:0:0:0:ffff:127.0.0.1]'];
}
public static function isSecureConnectionAssumedByPiwikButNotForcedYet(): bool
{
$isSecureConnectionLikelyNotUsed = Url::isSecureConnectionLikelyNotUsed();
$hasSessionCookieSecureFlag = ProxyHttp::isHttps();
$isSecureConnectionAssumedByPiwikButNotForcedYet = Url::isPiwikConfiguredToAssumeSecureConnection() && !SettingsPiwik::isHttpsForced();
return $isSecureConnectionLikelyNotUsed
&& $hasSessionCookieSecureFlag
&& $isSecureConnectionAssumedByPiwikButNotForcedYet;
}
protected static function getCurrentSchemeFromRequestHeader(): string
{
$proxySchemeHeaders = self::getProxySchemeHeadersFromConfig();
foreach ($proxySchemeHeaders as $header) {
if (empty($header) || !isset($_SERVER[$header])) {
continue;
}
$scheme = self::getSchemeFromHeaderValue($_SERVER[$header]);
if ($scheme !== null) {
return $scheme;
}
}
if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] === true)) {
return 'https';
}
return 'http';
}
/**
* @return string[]
*/
protected static function getProxySchemeHeadersFromConfig(): array
{
$proxySchemeHeaders = GeneralConfig::getConfigValue('proxy_scheme_headers');
if (empty($proxySchemeHeaders) || !is_array($proxySchemeHeaders)) {
return [];
}
return $proxySchemeHeaders;
}
/**
* @param mixed $value
*/
private static function getSchemeFromHeaderValue($value): ?string
{
if (!is_string($value)) {
return null;
}
$value = trim($value);
if ($value === '') {
return null;
}
$value = strtolower($value);
if ($value === 'http' || $value === 'https') {
return $value;
}
return null;
}
protected static function isSecureConnectionLikelyNotUsed(): bool
{
return Url::getCurrentSchemeFromRequestHeader() == 'http';
}
protected static function isPiwikConfiguredToAssumeSecureConnection(): bool
{
$assume_secure_protocol = GeneralConfig::getConfigValue('assume_secure_protocol');
return (bool) $assume_secure_protocol;
}
/**
* @return string
*/
public static function getHostFromServerNameVar()
{
$host = @$_SERVER['SERVER_NAME'];
if (!empty($host)) {
if (
strpos($host, ':') === false
&& !empty($_SERVER['SERVER_PORT'])
&& $_SERVER['SERVER_PORT'] != 80
&& $_SERVER['SERVER_PORT'] != 443
) {
$host .= ':' . $_SERVER['SERVER_PORT'];
}
}
return $host;
}
/**
* Add campaign parameters to URLs linking to matomo.org to improve understanding of how online help is being
* used for different parts of the application, no personally identifiable information is included, just the area
* of the application from which the link originated.
*
* @param string|null $url eg. www.matomo.org/faq/123 or https://matomo.org/faq/456
* @param string|null $campaign Optional campaign override, defaults to 'Matomo_App'
* @param string|null $source Optional campaign source override, defaults to either 'Matomo_App_OnPremise' or
* 'Matomo_App_Cloud'
* @param string|null $medium Optional campaign medium, defaults to App.[module].[action] where module and action are
* taken from the currently viewed application page, eg. 'CoreAdminHome.trackingCodeGenerator'
*
* @return ($url is string ? string : null) www.matomo.org/faq/123?mtm_campaign=Matomo_App&mtm_source=Matomo_App_OnPremise&mtm_medium=App.CoreAdminHome.trackingCodeGenerator
*/
public static function addCampaignParametersToMatomoLink(
?string $url = null,
?string $campaign = null,
?string $source = null,
?string $medium = null
): ?string {
// Ignore if disabled by config setting
if (GeneralConfig::getConfigValue('disable_tracking_matomo_app_links')) {
return $url;
}
// Ignore nulls
if ($url === null) {
return $url;
}
// Ignore non-matomo domains
$domain = self::getHostFromUrl($url);
if (!in_array($domain, ['matomo.org', 'www.matomo.org', 'developer.matomo.org', 'plugins.matomo.org'])) {
return $url;
}
// Build parameters
if ($medium === null) {
$module = Piwik::getModule();
$action = Piwik::getAction();
if (empty($module) || empty($action)) {
return $url; // Ignore if no module or action
}
$medium = 'App.' . $module . '.' . $action;
}
$newParams = [
'mtm_campaign' => $campaign ?? 'Matomo_App',
'mtm_source' => $source ?? 'Matomo_App_' . (\Piwik\Plugin\Manager::getInstance()->isPluginActivated('Cloud') ? 'Cloud' : 'OnPremise'),
'mtm_medium' => $medium,
];
// Add parameters to the link, overriding any existing campaign parameters while preserving the path and query string
$pathAndQueryString = UrlHelper::getPathAndQueryFromUrl($url, $newParams, true);
return 'https://' . $domain . '/' . $pathAndQueryString;
}
/**
* Create an external link tag with optional campaign params if link goes to matomo.org
*
* @since 5.6.0
*/
public static function getExternalLinkTag(
string $url,
?string $campaign = null,
?string $source = null,
?string $medium = null
): string {
$url = self::addCampaignParametersToMatomoLink($url, $campaign, $source, $medium);
return '<a target="_blank" rel="noreferrer noopener" href="' . $url . '">';
}
}
|