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
|
<?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\Tracker;
use Piwik\Cache;
use Piwik\CacheId;
use Piwik\Tracker\Cache as TrackerCache;
use Piwik\Common;
use Piwik\Config;
use Piwik\Piwik;
use Piwik\Plugins\SitesManager\API as APISitesManager;
use Piwik\UrlHelper;
class PageUrl
{
/**
* Map URL prefixes to integers.
* @see self::normalizeUrl(), self::reconstructNormalizedUrl()
*/
public static $urlPrefixMap = array(
'http://www.' => 1,
'http://' => 0,
'https://www.' => 3,
'https://' => 2,
);
/**
* Given the Input URL, will exclude all query parameters set for this site
*
* @static
* @param string $originalUrl
* @param $idSite
* @param array $additionalParametersToExclude
* @return bool|string Returned URL is HTML entities decoded
*/
public static function excludeQueryParametersFromUrl($originalUrl, $idSite, $additionalParametersToExclude = [])
{
$originalUrl = self::cleanupUrl($originalUrl);
$parsedUrl = @parse_url($originalUrl);
$parsedUrl = self::cleanupHostAndHashTag($parsedUrl, $idSite);
$parametersToExclude = array_merge(self::getQueryParametersToExclude($idSite), $additionalParametersToExclude);
if (empty($parsedUrl['query'])) {
if (empty($parsedUrl['fragment'])) {
return UrlHelper::getParseUrlReverse($parsedUrl);
}
// Exclude from the hash tag as well
$queryParameters = UrlHelper::getArrayFromQueryString($parsedUrl['fragment']);
$parsedUrl['fragment'] = UrlHelper::getQueryStringWithExcludedParameters($queryParameters, $parametersToExclude);
$url = UrlHelper::getParseUrlReverse($parsedUrl);
return $url;
}
$queryParameters = UrlHelper::getArrayFromQueryString($parsedUrl['query']);
$parsedUrl['query'] = UrlHelper::getQueryStringWithExcludedParameters($queryParameters, $parametersToExclude);
$url = UrlHelper::getParseUrlReverse($parsedUrl);
return $url;
}
/**
* Returns the array of parameters names that must be excluded from the Query String in all tracked URLs
* @static
* @param $idSite
* @return array
*/
public static function getQueryParametersToExclude($idSite)
{
$campaignTrackingParameters = Common::getCampaignParameters(intval($idSite), $skipCompliancePolicyCheck = true);
$campaignTrackingParameters = array_merge(
$campaignTrackingParameters[0], // campaign name parameters
$campaignTrackingParameters[1] // campaign keyword parameters
);
$website = TrackerCache::getCacheWebsiteAttributes($idSite);
$excludedParameters = self::getExcludedParametersFromWebsite($website);
$parametersToExclude = array_merge(
['ignore_referrer', 'ignore_referer'],
$excludedParameters,
self::getUrlParameterNamesToExcludeFromUrl(),
$campaignTrackingParameters
);
/**
* Triggered before setting the action url in Piwik\Tracker\Action so plugins can register
* parameters to be excluded from the tracking URL (e.g. campaign parameters).
*
* @param array &$parametersToExclude An array of parameters to exclude from the tracking url.
*/
Piwik::postEvent('Tracker.PageUrl.getQueryParametersToExclude', array(&$parametersToExclude));
if (!empty($parametersToExclude)) {
Common::printDebug('Excluding parameters "' . implode(',', $parametersToExclude) . '" from URL');
}
$parametersToExclude = array_map('strtolower', $parametersToExclude);
return $parametersToExclude;
}
/**
* Returns the list of URL query parameters that should be removed from the tracked URL query string.
*
* @return array
*/
protected static function getUrlParameterNamesToExcludeFromUrl()
{
$paramsToExclude = Config::getInstance()->Tracker['url_query_parameter_to_exclude_from_url'];
$paramsToExclude = explode(",", $paramsToExclude);
$paramsToExclude = array_map('trim', $paramsToExclude);
return $paramsToExclude;
}
/**
* Returns true if URL fragments should be removed for a specific site,
* false if otherwise.
*
* This function uses the Tracker cache and not the MySQL database.
*
* @param $idSite int The ID of the site to check for.
* @return bool
*/
public static function shouldRemoveURLFragmentFor($idSite)
{
$websiteAttributes = TrackerCache::getCacheWebsiteAttributes($idSite);
return empty($websiteAttributes['keep_url_fragment']);
}
/**
* Cleans and/or removes the URL fragment of a URL.
*
* @param $urlFragment string The URL fragment to process.
* @param $idSite int|bool If not false, this function will check if URL fragments
* should be removed for the site w/ this ID and if so,
* the returned processed fragment will be empty.
*
* @return string The processed URL fragment.
*/
public static function processUrlFragment($urlFragment, $idSite = false)
{
// if we should discard the url fragment for this site, return an empty string as
// the processed url fragment
if (
$idSite !== false
&& PageUrl::shouldRemoveURLFragmentFor($idSite)
) {
return '';
} else {
// Remove trailing Hash tag in ?query#hash#
if (substr($urlFragment, -1) == '#') {
$urlFragment = substr($urlFragment, 0, strlen($urlFragment) - 1);
}
return $urlFragment;
}
}
/**
* Will cleanup the hostname (some browser do not strolower the hostname),
* and deal ith the hash tag on incoming URLs based on website setting.
*
* @param $parsedUrl
* @param $idSite int|bool The site ID of the current visit. This parameter is
* only used by the tracker to see if we should remove
* the URL fragment for this site.
* @return array
*/
protected static function cleanupHostAndHashTag($parsedUrl, $idSite = false)
{
if (empty($parsedUrl)) {
return $parsedUrl;
}
if (!empty($parsedUrl['host'])) {
$parsedUrl['host'] = mb_strtolower($parsedUrl['host']);
}
if (!empty($parsedUrl['fragment'])) {
$parsedUrl['fragment'] = PageUrl::processUrlFragment($parsedUrl['fragment'], $idSite);
}
return $parsedUrl;
}
/**
* Converts Matrix URL format
* from https://example.org/thing;paramA=1;paramB=6542
* to https://example.org/thing?paramA=1¶mB=6542
*
* @param string $originalUrl
* @return string
*/
public static function convertMatrixUrl($originalUrl)
{
$posFirstSemiColon = strpos($originalUrl, ";");
if (false === $posFirstSemiColon) {
return $originalUrl;
}
$posQuestionMark = strpos($originalUrl, "?");
$replace = (false === $posQuestionMark);
if ($posQuestionMark > $posFirstSemiColon) {
$originalUrl = substr_replace($originalUrl, ";", $posQuestionMark, 1);
$replace = true;
}
if ($replace) {
$originalUrl = substr_replace($originalUrl, "?", strpos($originalUrl, ";"), 1);
$originalUrl = str_replace(";", "&", $originalUrl);
}
return $originalUrl;
}
/**
* Clean up string contents (filter, truncate, ...)
*
* @param string $string Dirty string
* @return string
*/
public static function cleanupString($string)
{
$string = trim($string);
$string = str_replace(array("\n", "\r", "\0"), '', $string);
$limit = Config::getInstance()->Tracker['page_maximum_length'];
$clean = substr($string, 0, $limit);
return $clean;
}
protected static function reencodeParameterValue($value, $encoding)
{
if (is_string($value)) {
$decoded = urldecode($value);
try {
if (
function_exists('mb_check_encoding')
&& @mb_check_encoding($decoded, $encoding)
) {
$value = urlencode(mb_convert_encoding($decoded, 'UTF-8', $encoding));
}
} catch (\Error $e) {
// mb_check_encoding might throw an ValueError on PHP 8 if the given encoding does not exist
// we can't simply catch ValueError as it was introduced in PHP 8
}
}
return $value;
}
protected static function reencodeParametersArray($queryParameters, $encoding)
{
foreach ($queryParameters as &$value) {
if (is_array($value)) {
$value = self::reencodeParametersArray($value, $encoding);
} else {
$value = PageUrl::reencodeParameterValue($value, $encoding);
}
}
return $queryParameters;
}
/**
* Checks if query parameters are of a non-UTF-8 encoding and converts the values
* from the specified encoding to UTF-8.
* This method is used to workaround browser/webapp bugs (see #3450). When
* browsers fail to encode query parameters in UTF-8, the tracker will send the
* charset of the page viewed and we can sometimes work around invalid data
* being stored.
*
* @param array $queryParameters Name/value mapping of query parameters.
* @param bool|string $encoding of the HTML page the URL is for. Used to workaround
* browser bugs & mis-coded webapps. See #3450.
*
* @return array
*/
public static function reencodeParameters(&$queryParameters, $encoding = false)
{
if (function_exists('mb_check_encoding')) {
// if query params are encoded w/ non-utf8 characters (due to browser bug or whatever),
// encode to UTF-8.
if (
is_string($encoding) &&
strtolower($encoding) !== 'utf-8'
) {
Common::printDebug("Encoding page URL query parameters to $encoding.");
$queryParameters = PageUrl::reencodeParametersArray($queryParameters, $encoding);
}
} else {
Common::printDebug("Page charset supplied in tracking request, but mbstring extension is not available.");
}
return $queryParameters;
}
public static function cleanupUrl($url)
{
$url = Common::unsanitizeInputValue($url);
$url = PageUrl::cleanupString($url);
$url = PageUrl::convertMatrixUrl($url);
return $url;
}
/**
* Build the full URL from the prefix ID and the rest.
*
* @param string $url
* @param integer $prefixId
* @return string
*/
public static function reconstructNormalizedUrl($url, $prefixId)
{
$map = array_flip(self::$urlPrefixMap);
if ($prefixId !== null && isset($map[$prefixId])) {
$fullUrl = $map[$prefixId] . $url;
} else {
$fullUrl = $url;
}
// Clean up host & hash tags, for URLs
$parsedUrl = @parse_url($fullUrl);
$parsedUrl = PageUrl::cleanupHostAndHashTag($parsedUrl);
$url = UrlHelper::getParseUrlReverse($parsedUrl);
if (!empty($url)) {
return $url;
}
return $fullUrl;
}
/**
* Returns if the given host is also configured as https in page urls of given site
*
* @param $idSite
* @param $host
* @return false|mixed
* @throws \Exception
*/
public static function shouldUseHttpsHost($idSite, $host)
{
$cache = Cache::getTransientCache();
$cacheKeySiteUrls = CacheId::siteAware('siteurls', [$idSite]);
$cacheKeyHttpsForHost = CacheId::siteAware(sprintf('shouldusehttps-%s', $host), [$idSite]);
$siteUrlCache = $cache->fetch($cacheKeySiteUrls);
if (empty($siteUrlCache)) {
$siteUrlCache = APISitesManager::getInstance()->getSiteUrlsFromId($idSite);
$cache->save($cacheKeySiteUrls, $siteUrlCache);
}
if (!$cache->contains($cacheKeyHttpsForHost)) {
$hostSiteCache = false;
foreach ($siteUrlCache as $siteUrl) {
if (strpos(mb_strtolower($siteUrl), mb_strtolower('https://' . $host)) === 0) {
$hostSiteCache = true;
break;
}
}
$cache->save($cacheKeyHttpsForHost, $hostSiteCache);
}
return $cache->fetch($cacheKeyHttpsForHost);
}
/**
* Extract the prefix from a URL.
* Return the prefix ID and the rest.
*
* @param string $url
* @return array
*/
public static function normalizeUrl($url)
{
foreach (self::$urlPrefixMap as $prefix => $id) {
if (strtolower(substr($url, 0, strlen($prefix))) == $prefix) {
return array(
'url' => substr($url, strlen($prefix)),
'prefixId' => $id,
);
}
}
return array('url' => $url, 'prefixId' => null);
}
public static function getUrlIfLookValid($url)
{
$url = PageUrl::cleanupString($url);
if (!UrlHelper::isLookLikeUrl($url)) {
Common::printDebug("WARNING: URL looks invalid and is discarded");
return false;
}
return $url;
}
private static function getExcludedParametersFromWebsite($website)
{
if (isset($website['excluded_parameters'])) {
return $website['excluded_parameters'];
}
return array();
}
public static function urldecodeValidUtf8($value)
{
$value = urldecode($value);
if (
function_exists('mb_check_encoding')
&& !@mb_check_encoding($value, 'utf-8')
) {
return urlencode($value);
}
return $value;
}
}
|