Deploy Matomo fully configured for Hugging Face Spaces (part 3)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- core/Settings/Settings.phpAdded+124
- core/Settings/Storage/Backend/BackendInterface.phpAdded+47
- core/Settings/Storage/Backend/BaseSettingsTable.phpAdded+41
- core/Settings/Storage/Backend/Cache.phpAdded+77
- core/Settings/Storage/Backend/Config.phpAdded+75
- core/Settings/Storage/Backend/MeasurableSettingsTable.phpAdded+194
- core/Settings/Storage/Backend/NullBackend.phpAdded+42
- core/Settings/Storage/Backend/PluginSettingsTable.phpAdded+403
- core/Settings/Storage/Backend/SitesTable.phpAdded+145
- core/Settings/Storage/Factory.phpAdded+139
- core/Settings/Storage/LegacyUserSettingsMigration.phpAdded+316
- core/Settings/Storage/Storage.phpAdded+117
- core/Settings/Storage/UserScopedSettingsAccessManager.phpAdded+102
- core/SettingsPiwik.phpAdded+491
- core/SettingsServer.phpAdded+275
- core/Singleton.phpAdded+74
- core/Site.phpAdded+674
- core/SiteContentDetector.phpAdded+402
- core/SupportedBrowser.phpAdded+71
- core/TCPDF.phpAdded+87
- core/Theme.phpAdded+166
- core/Timer.phpAdded+126
- core/Tracker.phpAdded+402
- core/Tracker/Action.phpAdded+465
- core/Tracker/ActionPageview.phpAdded+95
- core/Tracker/BotRequest.phpAdded+91
- core/Tracker/BotRequestProcessor.phpAdded+38
- core/Tracker/Cache.phpAdded+321
- core/Tracker/Config/ThirdPartyCookies.phpAdded+114
- core/Tracker/Db.phpAdded+305
- core/Tracker/Db/DbException.phpAdded+20
- core/Tracker/Db/Mysqli.phpAdded+473
- core/Tracker/Db/Pdo/Mysql.phpAdded+438
- core/Tracker/Failures.phpAdded+200
- core/Tracker/FingerprintSalt.phpAdded+82
- core/Tracker/GoalManager.phpAdded+1002
- core/Tracker/Handler.phpAdded+121
- core/Tracker/Handler/Factory.phpAdded+42
- core/Tracker/IgnoreCookie.phpAdded+103
- core/Tracker/LogTable.phpAdded+133
- core/Tracker/Model.phpAdded+728
- core/Tracker/PageUrl.phpAdded+440
- core/Tracker/Request.phpAdded+979
- core/Tracker/RequestHandlerTrait.phpAdded+92
- core/Tracker/RequestProcessor.phpAdded+165
- core/Tracker/RequestSet.phpAdded+215
- core/Tracker/Response.phpAdded+231
- core/Tracker/ScheduledTasksRunner.phpAdded+87
- core/Tracker/Settings.phpAdded+191
- core/Tracker/TableLogAction.phpAdded+335
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124<?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\Settings;
/** * Base class of all settings providers. * * @api */abstract class Settings{ /** * An array containing all available settings: Array ( [setting-name] => [setting] ) * * @var Setting[] */ private $settings = array();
protected $pluginName;
/** * By default the plugin name is shown in the UI when managing plugin settings. However, you can overwrite * the displayed title by specifying a title. * @var string */ protected $title = '';
public function __construct() { if (!isset($this->pluginName)) { $classname = get_class($this); $parts = explode('\\', $classname);
if (count($parts) >= 3) { $this->pluginName = $parts[2]; } else { throw new \Exception(sprintf('Plugin Settings must have a plugin name specified in %s, could not detect plugin name', $classname)); } } }
public function getTitle() { if (!empty($this->title)) { return $this->title; }
return $this->pluginName; }
/** * @ignore */ public function getPluginName() { return $this->pluginName; }
/** * @ignore * @return ?Setting */ public function getSetting($name) { if (array_key_exists($name, $this->settings)) { return $this->settings[$name]; }
return null; }
/** * Implemented by descendants. This method should define plugin settings (via the * {@link addSetting()}) method and set the introduction text (via the * {@link setIntroduction()}). */ abstract protected function init();
/** * Returns the settings that can be displayed for the current user. * * @return Setting[] */ public function getSettingsWritableByCurrentUser() { return array_filter($this->settings, function (Setting $setting) { return $setting->isWritableByCurrentUser(); }); }
/** * Adds a new setting to the settings container. * * @throws \Exception If there is a setting with the same name that already exists. * If the name contains non-alphanumeric characters. */ public function addSetting(Setting $setting) { $name = $setting->getName();
if (isset($this->settings[$name])) { throw new \Exception(sprintf('A setting with name "%s" does already exist for plugin "%s"', $name, $this->pluginName)); }
$this->settings[$name] = $setting; }
/** * Saves (persists) the current setting values in the database. */ public function save() { foreach ($this->settings as $setting) { $setting->save(); } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647<?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\Settings\Storage\Backend;
/** * Interface for a storage backend. Any new storage backend must implement this interface. */interface BackendInterface{ /** * Get an id that identifies the current storage. Eg `Plugin_$pluginName_Settings` could be a storage id * for plugin settings. It's kind of like a cache key and the value will be actually used for this by a cache * decorator. * * @return string */ public function getStorageId();
/** * Saves (persists) the current setting values in the database. Always all values that belong to a group of * settings or backend needs to be passed. Usually existing values will be deleted and new values will be saved * @param array $values An array of key value pairs where $settingName => $settingValue. * Eg array('settingName1' > 'settingValue1') */ public function save($values);
/** * Deletes all saved settings. * @return void */ public function delete();
/** * Loads previously saved setting values and returns them (if some were saved) * * @return ?array An array of key value pairs where $settingName => $settingValue. * Eg array('settingName1' > 'settingValue1') */ public function load();}1234567891011121314151617181920212223242526272829303132333435363738394041<?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\Settings\Storage\Backend;
use Piwik\Concurrency\Lock;use Piwik\Container\StaticContainer;use Piwik\Db;
abstract class BaseSettingsTable implements BackendInterface{ /** * @var Db\AdapterInterface */ protected $db;
/** @var Lock */ protected $lock;
public function __construct() { $this->lock = StaticContainer::getContainer()->make( Lock::class, array ('namespace' => 'PluginSettingsTable') ); }
protected function initDbIfNeeded() { if (!isset($this->db)) { // we do not want to create a db connection on backend creation $this->db = Db::get(); } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677<?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\Settings\Storage\Backend;
use Piwik\Tracker;use Piwik\Cache as PiwikCache;
/** * Loads settings from tracker cache instead of database. If not yet present in tracker cache will cache it. * * Can be used as a decorator in combination with any other storage backend. */class Cache implements BackendInterface{ /** * @var BackendInterface */ private $backend;
public function __construct(BackendInterface $backend) { $this->backend = $backend; }
/** * Saves (persists) the current setting values in the database. */ public function save($values) { $this->backend->save($values); self::clearCache(); }
public function getStorageId() { return $this->backend->getStorageId(); }
public function delete() { $this->backend->delete(); self::clearCache(); }
public function load() { $cacheId = $this->getStorageId(); $cache = self::buildCache();
if ($cache->contains($cacheId)) { return $cache->fetch($cacheId); }
$settings = $this->backend->load(); $cache->save($cacheId, $settings);
return $settings; }
public static function clearCache() { Tracker\Cache::deleteTrackerCache(); self::buildCache()->flushAll(); }
public static function buildCache() { return PiwikCache::getEagerCache(); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475<?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\Settings\Storage\Backend;
/** * Backend for an existing site. Stores all settings in the "site" database table. */class Config implements BackendInterface{ private $section;
public function __construct($section) { if (empty($section)) { throw new \Exception('No section given for config section backend'); }
$this->section = $section; }
/** * @inheritdoc */ public function getStorageId() { return 'Config_' . $this->section; }
private function getConfig() { return \Piwik\Config::getInstance(); }
/** * Saves (persists) the current setting values in the database. */ public function save($values) { $section = $this->load();
foreach ($values as $key => $value) { $section[$key] = $value; }
$config = $this->getConfig(); $config->{$this->section} = $section; $config->forceSave(); }
public function load() { $config = $this->getConfig(); $section = $config->{$this->section};
$values = array(); // remove reference foreach ($section as $key => $value) { $values[$key] = $value; }
return $values; }
public function delete() { $this->getConfig()->{$this->section} = array(); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194<?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\Settings\Storage\Backend;
use Piwik\Common;use Piwik\Db;use Exception;
/** * Measurable settings backend. Stores all settings in a "site_setting" database table. * * If a value that needs to be stored is an array, it will be JSON-encoded and stored in a single row. */class MeasurableSettingsTable extends BaseSettingsTable{ /** * @var int */ private $idSite;
/** * @var string */ private $pluginName;
public function __construct($idSite, $pluginName) { parent::__construct();
if (empty($pluginName)) { throw new Exception('No plugin name given for MeasurableSettingsTable backend'); }
if (empty($idSite)) { throw new Exception('No idSite given for MeasurableSettingsTable backend'); }
$this->idSite = (int) $idSite; $this->pluginName = $pluginName; }
/** * Saves (persists) the current setting values in the database. * @param array $values Key/value pairs of setting values to be written */ public function save($values) { $this->initDbIfNeeded();
$valuesKeep = array(); foreach ($values as $name => $value) { if (!isset($value)) { continue; } if (is_array($value) || is_object($value)) { $jsonEncoded = 1; $value = json_encode($value); } else { $jsonEncoded = 0; if (is_bool($value)) { // we are currently not storing booleans as json as it could result in trouble with the UI and regress // preselecting the correct value $value = (int) $value; } } $valuesKeep[] = array($this->idSite, $this->pluginName, $name, $value, $jsonEncoded); }
$columns = array('idsite', 'plugin_name', 'setting_name', 'setting_value', 'json_encoded');
$table = $this->getTableName(); $lockKey = $this->getStorageId(); $this->lock->execute($lockKey, function () use ($valuesKeep, $table, $columns) { $this->delete(); // No values = nothing to save if (!empty($valuesKeep)) { Db\BatchInsert::tableInsertBatchSql($table, $columns, $valuesKeep, true); } }); }
/** * @inheritdoc */ public function getStorageId() { return 'MeasurableSettings_' . $this->idSite . '_' . $this->pluginName; }
private function jsonEncodedMissingError(Exception $e) { return strpos($e->getMessage(), 'json_encoded') !== false; }
public function load() { $this->initDbIfNeeded();
$table = $this->getTableName();
$sql = "SELECT `setting_name`, `setting_value`, `json_encoded` FROM `$table` WHERE idsite = ? and plugin_name = ?"; $bind = array($this->idSite, $this->pluginName);
try { $settings = $this->db->fetchAll($sql, $bind); } catch (\Exception $e) { // we catch an exception since json_encoded might not be present before matomo is updated to 3.5.0+ but the updater // may run this query if ($this->jsonEncodedMissingError($e)) { $sql = "SELECT `setting_name`, `setting_value` FROM `$table` WHERE idsite = ? and plugin_name = ?"; $settings = $this->db->fetchAll($sql, $bind); } else { throw $e; } }
$flat = array(); foreach ($settings as $setting) { $name = $setting['setting_name'];
if (!empty($setting['json_encoded'])) { $flat[$name] = json_decode($setting['setting_value'], true); } elseif (array_key_exists($name, $flat)) { if (!is_array($flat[$name])) { $flat[$name] = array($flat[$name]); } $flat[$name][] = $setting['setting_value']; } else { $flat[$name] = $setting['setting_value']; } }
return $flat; }
protected function getTableName() { return Common::prefixTable('site_setting'); }
public function delete() { $this->initDbIfNeeded();
$table = $this->getTableName(); $sql = "DELETE FROM `$table` WHERE `idsite` = ? and plugin_name = ?"; $bind = array($this->idSite, $this->pluginName);
$this->db->query($sql, $bind); }
/** * @internal * @param int $idSite * @throws \Exception */ public static function removeAllSettingsForSite($idSite) { try { $query = sprintf('DELETE FROM `%s` WHERE idsite = ?', Common::prefixTable('site_setting')); Db::query($query, array($idSite)); } catch (Exception $e) { if ($e->getCode() != 42) { // ignore table not found error, which might occur when updating from an older version of Piwik throw $e; } } }
/** * @internal * @param string $pluginName * @throws \Exception */ public static function removeAllSettingsForPlugin($pluginName) { try { $query = sprintf('DELETE FROM `%s` WHERE plugin_name = ?', Common::prefixTable('site_setting')); Db::query($query, array($pluginName)); } catch (Exception $e) { if ($e->getCode() != 42) { // ignore table not found error, which might occur when updating from an older version of Piwik throw $e; } } }}123456789101112131415161718192021222324252627282930313233343536373839404142<?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\Settings\Storage\Backend;
/** * Static / temporary storage where a value shall never be persisted. Meaning it will use the default value * for each request until configured differently. Useful for tests etc. */class NullBackend implements BackendInterface{ private $storageId;
public function __construct($storageId) { $this->storageId = $storageId; }
public function load() { return array(); }
public function getStorageId() { return $this->storageId; }
public function delete() { }
public function save($values) { }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403<?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\Settings\Storage\Backend;
use Piwik\Common;use Piwik\Db;use Exception;
/** * Plugin settings backend. Stores all settings in a "plugin_setting" database table. * * If a value that needs to be stored is an array, it will be JSON-encoded and stored in a single row. */class PluginSettingsTable extends BaseSettingsTable{ /** * @var string */ private $pluginName;
/** * @var string */ private $userLogin;
public function __construct($pluginName, $userLogin) { parent::__construct();
if (empty($pluginName)) { throw new Exception('No plugin name given for PluginSettingsTable backend'); }
if ($userLogin === false || $userLogin === null) { throw new Exception('Invalid user login name given for PluginSettingsTable backend'); }
$this->pluginName = $pluginName; $this->userLogin = $userLogin; }
/** * @inheritdoc */ public function getStorageId() { return 'PluginSettings_' . $this->pluginName . '_User_' . $this->userLogin; }
/** * Saves (persists) the current setting values in the database. * @param array $values Key/value pairs of setting values to be written */ public function save($values) { $this->initDbIfNeeded();
$valuesKeep = array();
foreach ($values as $name => $value) { if (!isset($value)) { continue; } if (is_array($value) || is_object($value)) { $jsonEncoded = 1; $value = json_encode($value); } else { $jsonEncoded = 0; if (is_bool($value)) { // we are currently not storing booleans as json as it could result in trouble with the UI and regress // preselecting the correct value $value = (int) $value; } }
$valuesKeep[] = array($this->pluginName, $this->userLogin, $name, $value, $jsonEncoded); }
$columns = self::getColumns();
$table = $this->getTableName(); $lockKey = $this->getStorageId(); $this->lock->execute($lockKey, function () use ($valuesKeep, $table, $columns) { $this->delete(); // No values = nothing to save if (!empty($valuesKeep)) { Db\BatchInsert::tableInsertBatchSql($table, $columns, $valuesKeep); } }); }
/** * Save exactly one setting key atomically for the current plugin/user context * * if the value is null, the key is deleted. * * @throws Exception when param $settingName is empty */ /** * @param mixed $value */ public function saveValue(string $settingName, $value): void { $this->initDbIfNeeded();
if (empty($settingName)) { throw new Exception('No setting name given for PluginSettingsTable backend'); }
$table = $this->getTableName(); $lockKey = $this->getStorageId(); $columns = self::getColumns();
$this->lock->execute($lockKey, function () use ($table, $columns, $settingName, $value) { $this->deleteValueWithoutLock($settingName);
if (is_null($value)) { return; }
[$storedValue, $jsonEncoded] = $this->encodeValueForStorage($value); Db\BatchInsert::tableInsertBatchSql( $table, $columns, [[$this->pluginName, $this->userLogin, $settingName, $storedValue, $jsonEncoded]] ); }); }
/** * @throws Exception when param $settingName is empty */ /** * @param mixed $defaultValue * @return mixed */ public function loadValue(string $settingName, $defaultValue = null) { $this->initDbIfNeeded(); if (empty($settingName)) { throw new Exception('No setting name given for PluginSettingsTable backend'); }
$table = $this->getTableName();
$sql = "SELECT `setting_name`, `setting_value`, `json_encoded` FROM `$table` WHERE plugin_name = ? and user_login = ? and setting_name = ?"; $bind = [$this->pluginName, $this->userLogin, $settingName];
try { $rows = $this->db->fetchAll($sql, $bind); } catch (\Exception $e) { if ($this->jsonEncodedMissingError($e)) { $sql = "SELECT `setting_name`, `setting_value` FROM `$table` WHERE plugin_name = ? and user_login = ? and setting_name = ?"; $rows = $this->db->fetchAll($sql, $bind); } else { throw $e; } }
if (empty($rows)) { return $defaultValue; }
$flat = $this->flattenSettingsRows($rows); return array_key_exists($settingName, $flat) ? $flat[$settingName] : $defaultValue; }
/** * @throws Exception when param $settingName is empty */ public function deleteValue(string $settingName): void { $this->initDbIfNeeded();
if (empty($settingName)) { throw new Exception('No setting name given for PluginSettingsTable backend'); }
$lockKey = $this->getStorageId(); $this->lock->execute($lockKey, function () use ($settingName) { $this->deleteValueWithoutLock($settingName); }); }
private function jsonEncodedMissingError(Exception $e) { return strpos($e->getMessage(), 'json_encoded') !== false; }
public function load() { $this->initDbIfNeeded();
$sql = "SELECT `setting_name`, `setting_value`, `json_encoded` FROM `" . $this->getTableName() . "` WHERE plugin_name = ? and user_login = ?"; $bind = array($this->pluginName, $this->userLogin);
try { $settings = $this->db->fetchAll($sql, $bind); } catch (\Exception $e) { // we catch an exception since json_encoded might not be present before matomo is updated to 3.5.0+ but the updater // may run this query if ($this->jsonEncodedMissingError($e)) { $sql = "SELECT `setting_name`, `setting_value` FROM `" . $this->getTableName() . "` WHERE plugin_name = ? and user_login = ?"; $settings = $this->db->fetchAll($sql, $bind); } else { throw $e; } }
return $this->flattenSettingsRows($settings); }
/** * Returns selected setting names for all users in one plugin * * @param string[] $settingNames * @return array<string, array<string, mixed>> */ public function loadValuesForUsers(array $settingNames): array { $this->initDbIfNeeded(); if (empty($settingNames)) { return []; }
$table = $this->getTableName(); $placeholders = Common::getSqlStringFieldsArray($settingNames); $sql = "SELECT user_login, setting_name, setting_value, json_encoded FROM `$table` WHERE plugin_name = ? AND setting_name IN ($placeholders) AND user_login <> ''"; $bind = array_merge([$this->pluginName], $settingNames);
try { $rows = $this->db->fetchAll($sql, $bind); } catch (\Exception $e) { if ($this->jsonEncodedMissingError($e)) { $sql = "SELECT user_login, setting_name, setting_value FROM `$table` WHERE plugin_name = ? AND setting_name IN ($placeholders) AND user_login <> ''"; $rows = $this->db->fetchAll($sql, $bind); } else { throw $e; } }
$valuesByUser = []; foreach ($rows as $row) { $jsonEncoded = isset($row['json_encoded']) ? (bool) $row['json_encoded'] : false; $value = $this->decodeValueFromStorage( $row['setting_value'], $jsonEncoded ); $valuesByUser[$row['user_login']][$row['setting_name']] = $value; } return $valuesByUser; }
protected function getTableName() { return Common::prefixTable('plugin_setting'); }
public function delete() { $this->initDbIfNeeded();
$table = $this->getTableName(); $sql = "DELETE FROM `$table` WHERE `plugin_name` = ? and `user_login` = ?"; $bind = array($this->pluginName, $this->userLogin);
$this->db->query($sql, $bind); }
private function deleteValueWithoutLock(string $settingName): void { $this->initDbIfNeeded();
$table = $this->getTableName(); $sql = "DELETE FROM `$table` WHERE `plugin_name` = ? and `user_login` = ? and `setting_name` = ?"; $bind = [$this->pluginName, $this->userLogin, $settingName];
$this->db->query($sql, $bind); }
/** * Unsets all settings for a user. The settings will be removed from the database. Used when * a user is deleted. * * @internal * @param string $userLogin * @throws \Exception If the `$userLogin` is empty. Otherwise we would delete most plugin settings */ public static function removeAllUserSettingsForUser($userLogin) { if (empty($userLogin)) { throw new Exception('No userLogin specified. Cannot remove all settings for this user'); }
try { $table = Common::prefixTable('plugin_setting'); Db::get()->query(sprintf('DELETE FROM `%s` WHERE user_login = ?', $table), array($userLogin)); } catch (Exception $e) { if ($e->getCode() != 42) { // ignore table not found error, which might occur when updating from an older version of Piwik throw $e; } } }
/** * Unsets all settings for a plugin. The settings will be removed from the database. Used when * a plugin is uninstalled. * * @internal * @param string $pluginName */ public static function removeAllSettingsForPlugin($pluginName) { try { $table = Common::prefixTable('plugin_setting'); Db::get()->query(sprintf('DELETE FROM `%s` WHERE plugin_name = ?', $table), array($pluginName)); } catch (Exception $e) { if ($e->getCode() != 42) { // ignore table not found error, which might occur when updating from an older version of Piwik throw $e; } } }
/** * @return string[] */ private static function getColumns(): array { return ['plugin_name', 'user_login', 'setting_name', 'setting_value', 'json_encoded']; }
/** * @param mixed $value * @return array{0: mixed, 1: int} */ private function encodeValueForStorage($value): array { if (is_array($value) || is_object($value)) { return [json_encode($value), 1]; }
if (is_bool($value)) { return [(int) $value, 0]; }
return [$value, 0]; }
/** * @param mixed $value * @return mixed */ private function decodeValueFromStorage($value, bool $jsonEncoded) { if ($jsonEncoded) { return json_decode($value, true); } return $value; }
/** * @return array<string, mixed> */ private function flattenSettingsRows(array $settings): array { $flat = []; foreach ($settings as $setting) { $name = $setting['setting_name']; $jsonEncoded = isset($setting['json_encoded']) ? (bool) $setting['json_encoded'] : false; $value = $this->decodeValueFromStorage($setting['setting_value'], $jsonEncoded); if (array_key_exists($name, $flat) && !$jsonEncoded) { $flat[$name] = (array) $flat[$name]; $flat[$name][] = $value; } else { $flat[$name] = $value; } } return $flat; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145<?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\Settings\Storage\Backend;
use Piwik\Plugins\SitesManager\Model;use Piwik\Site;use Exception;
/** * Backend for an existing site. Stores all settings in the "site" database table. */class SitesTable implements BackendInterface{ /** * @var int */ private $idSite;
/** * @var string[] */ private $commaSeparatedArrayFields = array( 'sitesearch_keyword_parameters', 'sitesearch_category_parameters', 'excluded_user_agents', 'excluded_parameters', 'excluded_ips', 'excluded_referrers', );
/** * these fields are standard fields of a site and cannot be adjusted via a setting * @var string[] */ private $allowedNames = array( 'ecommerce', 'sitesearch', 'sitesearch_keyword_parameters', 'sitesearch_category_parameters', 'exclude_unknown_urls', 'excluded_ips', 'excluded_parameters', 'excluded_referrers', 'excluded_user_agents', 'keep_url_fragment', 'urls', );
/** * @param string|int|null $idSite */ public function __construct($idSite) { if (empty($idSite)) { throw new Exception('No idSite given for Measurable backend'); }
$this->idSite = (int) $idSite; }
/** * @inheritdoc */ public function getStorageId() { return 'SitesTable_' . $this->idSite; }
/** * Saves (persists) the current setting values in the database. * @param array $values */ public function save($values) { $model = $this->getModel();
foreach ($values as $key => $value) { if (!in_array($key, $this->allowedNames)) { unset($values[$key]); continue; }
if (is_array($value) && in_array($key, $this->commaSeparatedArrayFields)) { $values[$key] = implode(',', $value); } elseif (is_bool($value)) { $values[$key] = (int) $value; } }
if (!empty($values['urls']) && is_array($values['urls'])) { $values['main_url'] = $this->processAdditionalUrls($values['urls']); }
unset($values['urls']);
$model->updateSite($values, $this->idSite); Site::clearCacheForSite($this->idSite); }
public function load() { if (!empty($this->idSite)) { $site = Site::getSite($this->idSite);
$urls = $this->getModel(); $site['urls'] = $urls->getSiteUrlsFromId($this->idSite);
foreach ($this->commaSeparatedArrayFields as $field) { if (!empty($site[$field]) && is_string($site[$field])) { $site[$field] = explode(',', $site[$field]); } }
return $site; }
return null; }
/** * @param string[] $urls */ private function processAdditionalUrls(array $urls): string { $model = $this->getModel(); $urls = array_unique($urls); $mainUrl = array_shift($urls);
$model->deleteSiteAliasUrls($this->idSite); foreach ($urls as $url) { $model->insertSiteUrl($this->idSite, $url); }
return $mainUrl; }
private function getModel(): Model { return new Model(); }
public function delete() { }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139<?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\Settings\Storage;
use Piwik\Settings\Storage\Backend\BackendInterface;use Piwik\SettingsServer;
/** * Factory to create an instance of a storage. The storage can be created with different backends depending on the need. */class Factory{ // cache prevents multiple loading of storage private $cache = array();
/** * Get a storage instance for plugin settings. * * The storage will hold values that belong to the given plugin name and user login. Be aware that instances * for a specific plugin and login will be cached during one request for better performance. * * @param string $pluginName * @param string $userLogin Use an empty string if settings should be not for a specific login * @return Storage */ public function getPluginStorage($pluginName, $userLogin) { $id = $pluginName . '#' . $userLogin;
if (!isset($this->cache[$id])) { $backend = new Backend\PluginSettingsTable($pluginName, $userLogin); $this->cache[$id] = $this->makeStorage($backend); }
return $this->cache[$id]; }
/** * @param string $section * @return Storage */ public function getConfigStorage($section) { $id = 'config' . $section; if (!isset($this->cache[$id])) { $backend = new Backend\Config($section); $this->cache[$id] = $this->makeStorage($backend); }
return $this->cache[$id]; }
/** * Get a storage instance for measurable settings. * * The storage will hold values that belong to the given idSite and plugin name. Be aware that a storage instance * for a specific site and plugin will be cached during one request for better performance. * * @param int $idSite If idSite is empty it will use a backend that never actually persists any value. Pass * $idSite = 0 to create a storage for a site that is about to be created. * @param string $pluginName * @return Storage */ public function getMeasurableSettingsStorage($idSite, $pluginName) { $id = 'measurableSettings' . (int) $idSite . '#' . $pluginName;
if (empty($idSite)) { return $this->getNonPersistentStorage($id . '#nonpersistent'); }
if (!isset($this->cache[$id])) { $backend = new Backend\MeasurableSettingsTable($idSite, $pluginName); $this->cache[$id] = $this->makeStorage($backend); }
return $this->cache[$id]; }
/** * Get a storage instance for settings that will be saved in the "site" table. * * The storage will hold values that belong to the given idSite. Be aware that a storage instance for a specific * site will be cached during one request for better performance. * * @param int $idSite If idSite is empty it will use a backend that never actually persists any value. Pass * $idSite = 0 to create a storage for a site that is about to be created. * * @param int $idSite * @return Storage */ public function getSitesTable($idSite) { $id = 'sitesTable#' . $idSite;
if (empty($idSite)) { return $this->getNonPersistentStorage($id . '#nonpersistent'); }
if (!isset($this->cache[$id])) { $backend = new Backend\SitesTable($idSite); $this->cache[$id] = $this->makeStorage($backend); }
return $this->cache[$id]; }
/** * Get a storage with a backend that will never persist or load any value. * * @param string $key * @return Storage */ public function getNonPersistentStorage($key) { return new Storage(new Backend\NullBackend($key)); }
/** * Makes a new storage object based on a custom backend interface. * * @return Storage */ public function makeStorage(BackendInterface $backend) { if (SettingsServer::isTrackerApiRequest()) { $backend = new Backend\Cache($backend); }
return new Storage($backend); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316<?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\Settings\Storage;
use Piwik\Common;use Piwik\Container\StaticContainer;use Piwik\Db;use Piwik\Option;use Piwik\Piwik;use Piwik\Plugins\MobileMessaging\MobileMessaging;use Piwik\Plugins\UsersManager\API as UsersManagerAPI;
class LegacyUserSettingsMigration{ /** * @var UserScopedSettingsAccessManager */ private $store;
public function __construct(?UserScopedSettingsAccessManager $store = null) { if ($store === null) { $store = new UserScopedSettingsAccessManager(); }
$this->store = $store; }
/** * @return array<string, int> */ public function migrate(): array { $knownLogins = $this->getKnownLogins();
return [ 'mobileMessaging' => $this->migrateMobileMessagingSettings($knownLogins), 'feedback' => $this->migrateFeedbackSettings($knownLogins), 'professionalServices' => $this->migrateProfessionalServicesSettings($knownLogins), 'usersManagerPreferences' => $this->migrateUsersManagerPreferences($knownLogins), ]; }
/** * @param array<string, bool> $knownLogins */ private function migrateMobileMessagingSettings(array $knownLogins): int { $migratedCount = 0; $suffix = MobileMessaging::USER_SETTINGS_POSTFIX_OPTION; $legacySettings = Option::getLike('%' . $suffix);
foreach ($legacySettings as $optionName => $optionValue) { if (!str_ends_with($optionName, $suffix)) { continue; }
$login = substr($optionName, 0, -strlen($suffix)); if ($login !== '' && !isset($knownLogins[$login])) { Option::delete($optionName); continue; }
$existingSettings = $this->getMobileMessagingSettings($login); if (empty($existingSettings) && is_string($optionValue)) { $decoded = json_decode($optionValue, true); if (is_array($decoded)) { $this->setMobileMessagingSettings($login, $decoded); ++$migratedCount; } }
Option::delete($optionName); }
return $migratedCount; }
/** * @param array<string, bool> $knownLogins */ private function migrateFeedbackSettings(array $knownLogins): int { $migratedCount = 0; $prefix = 'Feedback.nextFeedbackReminder.'; $legacySettings = Option::getLike($prefix . '%');
foreach ($legacySettings as $optionName => $optionValue) { if (!str_starts_with($optionName, $prefix)) { continue; }
$login = substr($optionName, strlen($prefix)); if ($login !== '' && isset($knownLogins[$login]) && !$this->hasSetting('Feedback', $login, 'nextFeedbackReminder')) { $this->store->set('Feedback', $login, 'nextFeedbackReminder', $optionValue); ++$migratedCount; }
Option::delete($optionName); }
return $migratedCount; }
/** * @param array<string, bool> $knownLogins */ private function migrateProfessionalServicesSettings(array $knownLogins): int { $migratedCount = 0; $prefix = 'ProfessionalServices.DismissedWidget.'; $legacySettings = Option::getLike($prefix . '%'); $legacyByLogin = []; $knownLoginNames = array_keys($knownLogins); // sort logins by length to avoid partial collisions usort($knownLoginNames, function ($a, $b) { return strlen($b) <=> strlen($a); });
foreach ($legacySettings as $optionName => $optionValue) { if (!str_starts_with($optionName, $prefix)) { continue; }
$payload = substr($optionName, strlen($prefix));
$matchedLogin = null; $matchedWidget = null;
foreach ($knownLoginNames as $candidateLogin) { if (empty($candidateLogin)) { continue; }
$suffix = '.' . $candidateLogin; if (!str_ends_with($payload, $suffix)) { continue; }
$widgetName = substr($payload, 0, strlen($suffix) * -1); if (empty($widgetName)) { continue; }
$matchedLogin = $candidateLogin; $matchedWidget = $widgetName; break; }
if (empty($matchedLogin)) { continue; }
$legacyByLogin[$matchedLogin][$matchedWidget] = (int) $optionValue; }
foreach ($legacyByLogin as $login => $legacyWidgets) { $dismissedWidgets = $this->store->get('ProfessionalServices', $login, 'dismissedWidgets', []); if (!is_array($dismissedWidgets)) { $dismissedWidgets = []; }
$hasChanges = false; foreach ($legacyWidgets as $widgetName => $optionValue) { if (!isset($dismissedWidgets[$widgetName])) { $dismissedWidgets[$widgetName] = $optionValue; $hasChanges = true; } }
if ($hasChanges) { $this->store->set('ProfessionalServices', $login, 'dismissedWidgets', $dismissedWidgets); ++$migratedCount; } }
Option::deleteLike('ProfessionalServices.DismissedWidget.%');
return $migratedCount; }
/** * @param array<string, bool> $knownLogins */ private function migrateUsersManagerPreferences(array $knownLogins): int { $migratedCount = 0; $preferenceNames = $this->getSupportedPreferenceNames();
foreach ($preferenceNames as $preferenceName) { $suffix = UsersManagerAPI::OPTION_NAME_PREFERENCE_SEPARATOR . $preferenceName; $legacySettings = Option::getLike('%' . $suffix);
foreach ($legacySettings as $optionName => $optionValue) { if (!str_ends_with($optionName, $suffix)) { continue; }
$login = substr($optionName, 0, -strlen($suffix)); if ($login === '' || !$this->isLikelyValidLogin($login)) { continue; }
if (isset($knownLogins[$login]) && !$this->hasSetting('UsersManager', $login, $preferenceName)) { $this->store->set('UsersManager', $login, $preferenceName, $optionValue); ++$migratedCount; }
/** * @deprecated Should be removed with Matomo 6, LoginLdap should be * updated to not rely on Option storage for this setting */ if ($preferenceName === 'isLDAPUser' && isset($knownLogins[$login])) { // Keep legacy option key for LoginLdap submodule compatibility. continue; }
Option::delete($optionName); } }
return $migratedCount; }
/** * @return array<string, bool> */ private function getKnownLogins(): array { $logins = ['anonymous' => true]; $rows = Db::fetchAll('SELECT login FROM `' . Common::prefixTable('user') . '`');
foreach ($rows as $row) { if (!empty($row['login'])) { $logins[$row['login']] = true; } }
return $logins; }
/** * @return string[] */ private function getSupportedPreferenceNames(): array { $preferenceNames = [ UsersManagerAPI::PREFERENCE_DEFAULT_REPORT, UsersManagerAPI::PREFERENCE_DEFAULT_REPORT_DATE, 'isLDAPUser', 'hideSegmentDefinitionChangeMessage', ]; $customPreferenceNames = StaticContainer::get('usersmanager.user_preference_names'); if (!is_array($customPreferenceNames)) { $customPreferenceNames = []; }
$customPreferenceNames = array_values(array_filter($customPreferenceNames, 'is_string'));
return array_values(array_unique(array_merge($preferenceNames, $customPreferenceNames))); }
private function isLikelyValidLogin(string $login): bool { try { Piwik::checkValidLoginString($login); return true; } catch (\Exception $exception) { return false; } }
private function hasSetting(string $pluginName, string $userLogin, string $settingName): bool { $settings = $this->store->getAll($pluginName, $userLogin); return array_key_exists($settingName, $settings); }
/** * @return array<string, mixed> */ private function getMobileMessagingSettings(string $userLogin): array { if ($userLogin === '') { $settings = $this->getFactory()->getPluginStorage('MobileMessaging', $userLogin)->getBackend()->load(); return is_array($settings) ? $settings : []; }
return $this->store->getAll('MobileMessaging', $userLogin); }
/** * @param array<string, mixed> $settings */ private function setMobileMessagingSettings(string $userLogin, array $settings): void { if ($userLogin === '') { $this->getFactory()->getPluginStorage('MobileMessaging', $userLogin)->getBackend()->save($settings); return; }
$this->store->setAll('MobileMessaging', $userLogin, $settings); }
private function getFactory(): Factory { return StaticContainer::get(Factory::class); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117<?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\Settings\Storage;
use Piwik\Settings\Storage\Backend;
/** * A storage stores values for multiple settings. Storing multiple settings here saves having to do * a "get" for each individual setting. A storage is usually stared between all individual setting instances * within a plugin. */class Storage{ /** * Array containing all plugin settings values: Array( [setting-key] => [setting-value] ). * * @var array */ protected $settingsValues = array();
// for lazy loading of setting values private $settingValuesLoaded = false;
/** * @var Backend\BackendInterface */ private $backend;
/** * Defines whether a value has changed since the settings were loaded or not. * @var bool */ private $isDirty = false;
public function __construct(Backend\BackendInterface $backend) { $this->backend = $backend; }
/** * Get the currently used backend for this storage. * @return Backend\BackendInterface */ public function getBackend() { return $this->backend; }
/** * Saves (persists) the current setting values in the database if a value has actually changed. */ public function save() { if ($this->isDirty) { $this->backend->save($this->settingsValues);
$this->isDirty = false;
Backend\Cache::clearCache(); } }
/** * Returns the current value for a setting. If no value is stored, the default value * is be returned. * * @param string $key The name / key of a setting * @param mixed $defaultValue Default value that will be used in case no value for this setting exists yet * @param string $type The PHP internal type the value of the setting should have, see FieldConfig::TYPE_* * constants. Only an actual value of the setting will be converted to the given type, the * default value will not be converted. * @return mixed */ public function getValue($key, $defaultValue, $type) { $this->loadSettingsIfNotDoneYet();
if (array_key_exists($key, $this->settingsValues)) { settype($this->settingsValues[$key], $type); return $this->settingsValues[$key]; }
return $defaultValue; }
/** * Sets (overwrites) the value of a setting in memory. To persist the change across requests, {@link save()} must be * called. * * @param string $key The name / key of a setting * @param mixed $value The value that shall be set for the given setting. */ public function setValue($key, $value) { $this->loadSettingsIfNotDoneYet();
$this->isDirty = true; $this->settingsValues[$key] = $value; }
private function loadSettingsIfNotDoneYet() { if ($this->settingValuesLoaded) { return; }
$this->settingValuesLoaded = true; $this->settingsValues = $this->backend->load(); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102<?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\Settings\Storage;
use Exception;use Piwik\Settings\Storage\Backend\PluginSettingsTable;
class UserScopedSettingsAccessManager{ /** * @var array<string, PluginSettingsTable> */ private $backends = [];
/** * @param mixed $defaultValue * @return mixed */ public function get(string $pluginName, string $userLogin, string $key, $defaultValue = null) { return $this->getBackend($pluginName, $userLogin)->loadValue($key, $defaultValue); }
/** * @param mixed $value */ public function set(string $pluginName, string $userLogin, string $key, $value): void { $this->getBackend($pluginName, $userLogin)->saveValue($key, $value); }
public function getAll(string $pluginName, string $userLogin): array { $this->validatePluginAndLogin($pluginName, $userLogin); return $this->getBackend($pluginName, $userLogin)->load(); }
public function setAll(string $pluginName, string $userLogin, array $settings): void { $this->validatePluginAndLogin($pluginName, $userLogin); $this->getBackend($pluginName, $userLogin)->save($settings); }
public function delete(string $pluginName, string $userLogin, string $key): void { $this->getBackend($pluginName, $userLogin)->deleteValue($key); }
public function deleteAll(string $pluginName, string $userLogin): void { $this->validatePluginAndLogin($pluginName, $userLogin); $this->getBackend($pluginName, $userLogin)->delete(); }
/** * @param string[] $settingNames * @return array<string, array<string, mixed>> */ public function getValuesForAllUsers(string $pluginName, array $settingNames): array { if (empty($pluginName) || empty($settingNames)) { return []; }
// login is not used by loadValuesForUsers(), value is irrelevant return $this->getBackend($pluginName, $userLogin = '')->loadValuesForUsers($settingNames); }
private function validatePluginAndLogin(string $pluginName, string $userLogin): void { if (empty($pluginName)) { throw new \Exception('No plugin name specified for user scoped settings store'); }
if (empty($userLogin)) { throw new \Exception('No username specified for user scoped settings store'); } }
/** * @throws Exception when $pluginName is empty */ private function getBackend(string $pluginName, string $userLogin): PluginSettingsTable { if (empty($pluginName)) { throw new \Exception('No plugin name specified for user scoped settings store'); }
$id = $pluginName . '#' . $userLogin; if (empty($this->backends[$id])) { $this->backends[$id] = new PluginSettingsTable($pluginName, $userLogin); } return $this->backends[$id]; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491<?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 Piwik\Cache as PiwikCache;use Piwik\Config\GeneralConfig;use Piwik\Container\StaticContainer;
/** * Contains helper methods that can be used to get common Piwik settings. * */class SettingsPiwik{ public const OPTION_PIWIK_URL = 'piwikUrl';
/** * Get salt from [General] section. Should ONLY be used as a seed to create hashes * * NOTE: Keep this salt secret! Never output anywhere or share it etc. */ public static function getSalt(): ?string { static $salt = null; if (is_null($salt)) { $salt = Config::getInstance()->General['salt'] ?? ''; } return $salt; }
/** * Should Piwik check that the login & password have minimum length and valid characters? * * @return bool True if checks enabled; false otherwise */ public static function isUserCredentialsSanityCheckEnabled(): bool { return Config::getInstance()->General['disable_checks_usernames_attributes'] == 0; }
/** * Should Piwik show the update notification to superusers only? * * @return bool True if show to superusers only; false otherwise */ public static function isShowUpdateNotificationToSuperUsersOnlyEnabled(): bool { return Config::getInstance()->General['show_update_notification_to_superusers_only'] == 1; }
/** * Returns every stored segment to pre-process for each site during cron archiving. * * @return array The list of stored segments that apply to all sites. */ public static function getKnownSegmentsToArchive(): array { $cacheId = 'KnownSegmentsToArchive'; $cache = PiwikCache::getTransientCache(); if ($cache->contains($cacheId)) { return $cache->fetch($cacheId); }
$segments = Config::getInstance()->Segments; $segmentsToProcess = isset($segments['Segments']) ? $segments['Segments'] : array();
/** * Triggered during the cron archiving process to collect segments that * should be pre-processed for all websites. The archiving process will be launched * for each of these segments when archiving data. * * This event can be used to add segments to be pre-processed. If your plugin depends * on data from a specific segment, this event could be used to provide enhanced * performance. * * _Note: If you just want to add a segment that is managed by the user, use the * SegmentEditor API._ * * **Example** * * Piwik::addAction('Segments.getKnownSegmentsToArchiveAllSites', function (&$segments) { * $segments[] = 'country=jp;city=Tokyo'; * }); * * @param array &$segmentsToProcess List of segment definitions, eg, * * array( * 'browserCode=ff;resolution=800x600', * 'country=jp;city=Tokyo' * ) * * Add segments to this array in your event handler. */ Piwik::postEvent('Segments.getKnownSegmentsToArchiveAllSites', array(&$segmentsToProcess));
$segmentsToProcess = array_unique($segmentsToProcess);
$cache->save($cacheId, $segmentsToProcess); return $segmentsToProcess; }
/** * Returns the list of stored segments to pre-process for an individual site when executing * cron archiving. * * @param int $idSite The ID of the site to get stored segments for. * @return string[] The list of stored segments that apply to the requested site. */ public static function getKnownSegmentsToArchiveForSite($idSite): array { $cacheId = 'KnownSegmentsToArchiveForSite' . $idSite; $cache = PiwikCache::getTransientCache(); if ($cache->contains($cacheId)) { return $cache->fetch($cacheId); }
$segments = array(); /** * Triggered during the cron archiving process to collect segments that * should be pre-processed for one specific site. The archiving process will be launched * for each of these segments when archiving data for that one site. * * This event can be used to add segments to be pre-processed for one site. * * _Note: If you just want to add a segment that is managed by the user, you should use the * SegmentEditor API._ * * **Example** * * Piwik::addAction('Segments.getKnownSegmentsToArchiveForSite', function (&$segments, $idSite) { * $segments[] = 'country=jp;city=Tokyo'; * }); * * @param array &$segmentsToProcess List of segment definitions, eg, * * array( * 'browserCode=ff;resolution=800x600', * 'country=JP;city=Tokyo' * ) * * Add segments to this array in your event handler. * @param int $idSite The ID of the site to get segments for. */ Piwik::postEvent('Segments.getKnownSegmentsToArchiveForSite', array(&$segments, $idSite));
$segments = array_unique($segments);
$cache->save($cacheId, $segments);
return $segments; }
/** * Number of websites to show in the Website selector */ public static function getWebsitesCountToDisplay(): int { $count = max( Config::getInstance()->General['site_selector_max_sites'], Config::getInstance()->General['autocomplete_min_sites'] ); return (int)$count; }
/** * Returns the URL to this Piwik instance, eg. **https://demo.piwik.org/** or **https://example.org/piwik/**. * * @return string|false return false if no value is configured and we are in PHP CLI mode * @api */ public static function getPiwikUrl() { $url = Option::get(self::OPTION_PIWIK_URL);
$isPiwikCoreDispatching = defined('PIWIK_ENABLE_DISPATCH') && PIWIK_ENABLE_DISPATCH; if ( Common::isPhpCliMode() // in case core:archive command is triggered (often with localhost domain) || SettingsServer::isArchivePhpTriggered() // When someone else than core is dispatching this request then we return the URL as it is read only || !$isPiwikCoreDispatching ) { return $url; }
$currentUrl = Common::sanitizeInputValue(Url::getCurrentUrlWithoutFileName());
// when script is called from /misc/cron/archive.php, Piwik URL is /index.php $currentUrl = str_replace("/misc/cron", "", $currentUrl);
if ( empty($url) // if URL changes, always update the cache || $currentUrl !== $url ) { $host = Url::getHostFromUrl($currentUrl);
if ( strlen($currentUrl) >= strlen('http://a/') && Url::isValidHost($host) && !Url::isLocalHost($host) ) { self::overwritePiwikUrl($currentUrl); } $url = $currentUrl; }
if (ProxyHttp::isHttps()) { $url = str_replace("http://", "https://", $url); } return $url; }
public static function isMatomoInstalled(): bool { $config = Config::getInstance()->getLocalPath(); $exists = file_exists($config);
// Piwik is not installed if the config file is not found if (!$exists) { return false; }
$general = Config::getInstance()->General;
$isInstallationInProgress = false; if (array_key_exists('installation_in_progress', $general)) { $isInstallationInProgress = (bool) $general['installation_in_progress']; } if ($isInstallationInProgress) { return false; }
// Check that the database section is really set, ie. file is not empty if (empty(Config::getInstance()->database['username'])) { return false; } return true; }
/** * Check if outgoing internet connections are enabled * This is often disable in an intranet environment */ public static function isInternetEnabled(): bool { return (bool) Config::getInstance()->General['enable_internet_features']; }
/** * Detect whether user has enabled auto updates. Please note this config is a bit misleading. It is currently * actually used for 2 things: To disable making any connections back to Piwik, and to actually disable the auto * update of core and plugins. */ public static function isAutoUpdateEnabled(): bool { $enableAutoUpdate = (bool) Config::getInstance()->General['enable_auto_update']; if (self::isInternetEnabled() === true && $enableAutoUpdate === true) { return true; }
return false; }
/** * Detects whether an auto update can be made. An update is possible if the user is not on multiple servers and if * automatic updates are actually enabled. If a user is running Piwik on multiple servers an update is not possible * as it would be installed only on one server instead of all of them. Also if a user has disabled automatic updates * we cannot perform any automatic updates. */ public static function isAutoUpdatePossible(): bool { return !self::isMultiServerEnvironment() && self::isAutoUpdateEnabled(); }
/** * Returns `true` if Piwik is running on more than one server. For example in a load balanced environment. In this * case we should not make changes to the config and not install a plugin via the UI as it would be only executed * on one server. */ public static function isMultiServerEnvironment(): bool { $is = Config::getInstance()->General['multi_server_environment'];
return !empty($is); }
/** * Returns `true` if segmentation is allowed for this user, `false` if otherwise. * * @api */ public static function isSegmentationEnabled(): bool { return !Piwik::isUserIsAnonymous() || Config::getInstance()->General['anonymous_user_enable_use_segments_API']; }
/** * Returns true if unique visitors should be processed for the given period type. * * Unique visitor processing is controlled by the `[General] enable_processing_unique_visitors_...` * INI config options. By default, unique visitors are processed only for day/week/month periods. * * @param string $periodLabel `"day"`, `"week"`, `"month"`, `"year"` or `"range"` * @api */ public static function isUniqueVisitorsEnabled(string $periodLabel): bool { $generalSettings = Config::getInstance()->General;
$settingName = "enable_processing_unique_visitors_$periodLabel"; $result = !empty($generalSettings[$settingName]) && $generalSettings[$settingName] == 1;
// check enable_processing_unique_visitors_year_and_range for backwards compatibility if ( ($periodLabel === 'year' || $periodLabel === 'range') && isset($generalSettings['enable_processing_unique_visitors_year_and_range']) ) { $result |= $generalSettings['enable_processing_unique_visitors_year_and_range'] == 1; }
return $result; }
/** * If Piwik uses per-domain config file, make sure CustomLogo is unique * @throws \Piwik\Exception\DI\DependencyException * @throws \Piwik\Exception\DI\NotFoundException * @throws Exception */ public static function rewriteMiscUserPathWithInstanceId(string $path): string { $tmp = StaticContainer::get('path.misc.user'); $path = self::rewritePathAppendPiwikInstanceId($path, $tmp); return $path; }
/** * Checks whether the Piwik server appears to be working. * * If the Piwik server is in an error state (eg. some directories are not writable and Piwik displays error message), * or if the Piwik server is "offline", * this will throw an exception. */ public static function checkPiwikServerWorking(string $piwikServerUrl, bool $acceptInvalidSSLCertificates = false): void { // Now testing if the webserver is running try { $fetched = Http::sendHttpRequestBy( 'curl', $piwikServerUrl, $timeout = 45, $userAgent = null, $destinationPath = null, $file = null, $followDepth = 0, $acceptLanguage = false, $acceptInvalidSSLCertificates ); } catch (Exception $e) { $fetched = "ERROR fetching: " . $e->getMessage(); } // this will match when Piwik not installed yet, or favicon not customised $expectedStringAlt = 'plugins/CoreHome/images/favicon.png';
// this will match when Piwik is installed and favicon has been customised $expectedString = 'misc/user/';
// see checkPiwikIsNotInstalled() $expectedStringAlreadyInstalled = 'piwik-is-already-installed';
$expectedStringNotFound = strpos($fetched, $expectedString) === false && strpos($fetched, $expectedStringAlt) === false && strpos($fetched, $expectedStringAlreadyInstalled) === false;
$hasError = false !== strpos($fetched, PAGE_TITLE_WHEN_ERROR);
if ($hasError || $expectedStringNotFound) { throw new Exception("\nMatomo should be running at: " . $piwikServerUrl . " but this URL returned an unexpected response: '" . $fetched . "'\n\n"); } }
/** * Returns true if Piwik is deployed using git * FAQ: https://piwik.org/faq/how-to-install/faq_18271/ */ public static function isGitDeployment(): bool { return file_exists(PIWIK_INCLUDE_PATH . '/.git/HEAD'); }
public static function getCurrentGitBranch(): string { $file = PIWIK_INCLUDE_PATH . '/.git/HEAD'; if (!file_exists($file)) { return ''; } $firstLineOfGitHead = file($file); if (empty($firstLineOfGitHead)) { return ''; } $firstLineOfGitHead = $firstLineOfGitHead[0]; $parts = explode('/', $firstLineOfGitHead); if (empty($parts[2])) { return ''; } $currentGitBranch = trim($parts[2]); return $currentGitBranch; }
/** * @throws Exception */ protected static function rewritePathAppendPiwikInstanceId(string $pathToRewrite, string $leadingPathToAppendHostnameTo): string { $instanceId = self::getPiwikInstanceId(); if (empty($instanceId)) { return $pathToRewrite; }
if (($posTmp = strrpos($pathToRewrite, $leadingPathToAppendHostnameTo)) === false) { throw new Exception("The path $pathToRewrite was expected to contain the string $leadingPathToAppendHostnameTo"); }
$tmpToReplace = $leadingPathToAppendHostnameTo . $instanceId . '/';
// replace only the latest occurrence (in case path contains twice /tmp) $pathToRewrite = substr_replace($pathToRewrite, $tmpToReplace, $posTmp, strlen($leadingPathToAppendHostnameTo)); return $pathToRewrite; }
/** * @throws Exception * @return string|false return string or false if not set */ public static function getPiwikInstanceId() { // until Matomo is installed, we use hostname as instance_id if (!self::isMatomoInstalled() && Common::isPhpCliMode()) { // enterprise:install use case return Config::getHostname(); }
// config.ini.php not ready yet, instance_id will not be set if (!Config::getInstance()->existsLocalConfig()) { return false; }
$instanceId = GeneralConfig::getConfigValue('instance_id'); if (!empty($instanceId)) { return preg_replace('/[^\w\.-]/', '', $instanceId); }
// do not rewrite the path as Matomo uses the standard config.ini.php file return false; }
public static function overwritePiwikUrl(string $currentUrl): void { Option::set(self::OPTION_PIWIK_URL, $currentUrl, $autoLoad = true); }
public static function isHttpsForced(): bool { if (!self::isMatomoInstalled()) { // Only enable this feature after Piwik is already installed return false; } return Config::getInstance()->General['force_ssl'] == 1; }
/** * Note: this config settig is also checked in the InterSites plugin */ public static function isSameFingerprintAcrossWebsites(): bool { return (bool)Config::getInstance()->Tracker['enable_fingerprinting_across_websites']; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275<?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;
/** * Contains helper methods that can be used to get information regarding the * server, its settings and currently used PHP settings. * */class SettingsServer{ /** * Returns true if the current script execution was triggered by the cron archiving script. * * Helpful for error handling: directly throw error without HTML (eg. when DB is down). * * @return bool * @api */ public static function isArchivePhpTriggered() { return !empty($_GET['trigger']) && $_GET['trigger'] == 'archivephp' && Piwik::hasUserSuperUserAccess(); }
/** * Returns true if the current request is a Tracker request. * * @return bool true if the current request is a Tracking API Request (ie. piwik.php) */ public static function isTrackerApiRequest() { return !empty($GLOBALS['PIWIK_TRACKER_MODE']); }
/** * Mark the current request as a Tracker API request */ public static function setIsTrackerApiRequest() { $GLOBALS['PIWIK_TRACKER_MODE'] = true; }
/** * Set the current request is not a tracker API request */ public static function setIsNotTrackerApiRequest() { $GLOBALS['PIWIK_TRACKER_MODE'] = false; }
/** * Returns true if Matomo is running within Matomo for WordPress. * * @return bool true if Matomo is running in WordPress, false if Matomo is running as part of On-Premise * @api */ public static function isMatomoForWordPress() { return defined('ABSPATH') && function_exists('\add_action'); }
/** * Returns `true` if running on Microsoft IIS 7 (or above), `false` if otherwise. * * @return bool * @api */ public static function isIIS() { $iis = isset($_SERVER['SERVER_SOFTWARE']) && preg_match('/^Microsoft-IIS\/(.+)/', $_SERVER['SERVER_SOFTWARE'], $matches) && version_compare($matches[1], '7') >= 0;
return $iis; }
/** * Returns `true` if running on a Windows operating system, `false` if otherwise. * * @since 0.6.5 * @return bool * @api */ public static function isWindows() { if (PHP_OS_FAMILY == "Unknown") { return DIRECTORY_SEPARATOR === '\\'; } return PHP_OS_FAMILY === "Windows"; }
/** * Returns `true` if this PHP version/build supports timezone manipulation * (e.g., php >= 5.2, or compiled with **EXPERIMENTAL_DATE_SUPPORT=1** for * php < 5.2). * * @return bool * @api */ public static function isTimezoneSupportEnabled() { return function_exists('date_create') && function_exists('date_default_timezone_set') && function_exists('timezone_identifiers_list') && function_exists('timezone_open') && function_exists('timezone_offset_get'); }
/** * Returns `true` if the GD PHP extension is available, `false` if otherwise. * * _Note: ImageGraph and the sparkline report visualization depend on the GD extension._ * * @return bool * @api */ public static function isGdExtensionEnabled() { static $gd = null; if (is_null($gd)) { $gd = false;
$extensions = @get_loaded_extensions(); if (is_array($extensions)) { $gd = in_array('gd', $extensions) && function_exists('imageftbbox'); } }
return $gd; }
/** * Raise PHP memory limit if below the minimum required * * @return bool true if set; false otherwise */ public static function raiseMemoryLimitIfNecessary() { if (self::isArchivePhpTriggered()) { // core:archive command: no time limit self::setMaxExecutionTime(0); }
$memoryLimit = self::getMemoryLimitValue(); if ($memoryLimit === false) { return false; } $minimumMemoryLimit = Config::getInstance()->General['minimum_memory_limit'];
if (self::isArchivePhpTriggered()) { // core:archive command: high memory limit $minimumMemoryLimitWhenArchiving = Config::getInstance()->General['minimum_memory_limit_when_archiving']; if ($memoryLimit < $minimumMemoryLimitWhenArchiving) { return self::setMemoryLimit($minimumMemoryLimitWhenArchiving); } return false; } if ($memoryLimit < $minimumMemoryLimit) { return self::setMemoryLimit($minimumMemoryLimit); } return false; }
/** * Set PHP memory limit * * Note: system settings may prevent scripts from overriding the master value * * @param int $minimumMemoryLimit * @return bool true if set; false otherwise */ protected static function setMemoryLimit($minimumMemoryLimit) { // in Megabytes $currentValue = self::getMemoryLimitValue(); if ( $currentValue === false || ($currentValue < $minimumMemoryLimit && @ini_set('memory_limit', $minimumMemoryLimit . 'M')) ) { return true; } return false; }
/** * Get php memory_limit (in Megabytes) * * Prior to PHP 5.2.1, or on Windows, --enable-memory-limit is not a * compile-time default, so ini_get('memory_limit') may return false. * * @return int|float|string|false memory limit in megabytes, or false if there is no limit */ public static function getMemoryLimitValue() { if (($memory = ini_get('memory_limit')) > 0) { return self::getMegaBytesFromShorthandByte($memory); }
// no memory limit return false; }
/** * Get php post_max_size (in Megabytes) * * @return int|float|string|false max upload size in megabytes, or false if there is no limit */ public static function getPostMaxUploadSize() { if (($maxPostSize = ini_get('post_max_size')) > 0) { return self::getMegaBytesFromShorthandByte($maxPostSize); }
// no max upload size return false; }
/** * @see https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes * @param $value * @return false|float|int|string */ private static function getMegaBytesFromShorthandByte($value) { $value = str_replace(' ', '', $value);
$shorthandByteOption = substr($value, -1); switch ($shorthandByteOption) { case 'G': case 'g': return substr($value, 0, -1) * 1024; case 'M': case 'm': return substr($value, 0, -1); case 'K': case 'k': return substr($value, 0, -1) / 1024; }
if (is_numeric($value)) { return (int) $value / 1048576; }
return false; }
/** * Set maximum script execution time. * * @param int $executionTime max execution time in seconds (0 = no limit) */ public static function setMaxExecutionTime($executionTime) { // in the event one or the other is disabled... @ini_set('max_execution_time', $executionTime); if (function_exists('set_time_limit')) { @set_time_limit($executionTime); } }
public static function isMac() { return defined('PHP_OS') && PHP_OS === 'Darwin'; }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374<?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;
/** * The singleton base class restricts the instantiation of derived classes to one object only. * * All plugin APIs are singletons and thus extend this class. * * @api */class Singleton{ protected static $instances;
protected function __construct() { }
final protected function __clone() { }
/** * Returns the singleton instance for the derived class. If the singleton instance * has not been created, this method will create it. * * @return static */ public static function getInstance() { $class = get_called_class();
if (!isset(self::$instances[$class])) { self::$instances[$class] = new $class(); } return self::$instances[$class]; }
/** * Used in tests only * @ignore */ public static function unsetInstance() { $class = get_called_class(); unset(self::$instances[$class]); }
/** * Sets the singleton instance. For testing purposes. * @ignore */ public static function setSingletonInstance($instance) { $class = get_called_class(); self::$instances[$class] = $instance; }
/** * @ignore */ public static function clearAll() { self::$instances = array(); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674<?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 Piwik\Exception\UnexpectedWebsiteFoundException;use Piwik\Http\BadRequestException;use Piwik\Plugins\SitesManager\API;
/** * Provides access to individual [site entity](/guides/persistence-and-the-mysql-backend#websites-aka-sites) data * (including name, URL, etc.). * * **Data Cache** * * Site data can be cached in order to avoid performing too many queries. * If a method needs many site entities, it is more efficient to query all of what * you need beforehand via the **SitesManager** API, then cache it using {@link setSites()} or * {@link setSitesFromArray()}. * * Subsequent calls to `new Site($id)` will use the data in the cache instead of querying the database. * * ### Examples * * **Basic usage** * * $site = new Site($idSite); * $name = $site->getName(); * * **Without allocation** * * $name = Site::getNameFor($idSite); * * @api */class Site{ public const DEFAULT_SITE_TYPE = "website";
private static $intProperties = [ 'idsite', 'ecommerce', 'sitesearch', 'exclude_unknown_urls', 'keep_url_fragment', ];
/** * @var int */ protected $id = null;
/** * @var array */ protected static $infoSites = array();
private $site = array();
/** * @param int $idsite The ID of the site we want data for. * @throws UnexpectedWebsiteFoundException */ public function __construct($idsite) { $this->id = (int) $idsite;
if (!empty(self::$infoSites[$this->id])) { $site = self::$infoSites[$this->id]; } else { $site = API::getInstance()->getSiteFromId($this->id);
if (empty($site)) { throw new UnexpectedWebsiteFoundException('The requested website id = ' . (int)$this->id . ' couldn\'t be found'); } }
$sites = array(&$site); self::triggerSetSitesEvent($sites); self::setSiteFromArray($this->id, $site);
$this->site = $site;
// for serialized format to be predictable across php/mysql/pdo/mysqli versions, make sure the int props stay ints foreach (self::$intProperties as $propertyName) { $this->site[$propertyName] = (int)$this->site[$propertyName]; } }
/** * Sets the cached site data with an array that associates site IDs with * individual site data. * * @param array $sites The array of sites data. Indexed by site ID. eg, * * array('1' => array('name' => 'Site 1', ...), * '2' => array('name' => 'Site 2', ...))` */ public static function setSites($sites) { self::triggerSetSitesEvent($sites);
foreach ($sites as $idsite => $site) { self::setSiteFromArray($idsite, $site); } }
private static function triggerSetSitesEvent(&$sites) { /** * Triggered so plugins can modify website entities without modifying the database. * * This event should **not** be used to add data that is expensive to compute. If you * need to make HTTP requests or query the database for more information, this is not * the place to do it. * * **Example** * * Piwik::addAction('Site.setSites', function (&$sites) { * foreach ($sites as &$site) { * $site['name'] .= " (original)"; * } * }); * * @param array $sites An array of website entities. [Learn more.](/guides/persistence-and-the-mysql-backend#websites-aka-sites) * * This is not yet public as it doesn't work 100% accurately. Eg if `setSiteFromArray()` is called directly this event will not be triggered. * @ignore */ Piwik::postEvent('Site.setSites', array(&$sites)); }
/** * Sets a site information in memory (statically cached). * * Plugins can filter the website attributes before it is cached, eg. to change the website name, * creation date, etc. * * @param $idSite * @param $infoSite * @throws Exception if website or idsite is invalid * @internal */ public static function setSiteFromArray($idSite, $infoSite) { if (empty($idSite) || empty($infoSite)) { throw new UnexpectedWebsiteFoundException("An unexpected website was found in the request: website id was set to '$idSite' ."); }
self::$infoSites[$idSite] = $infoSite; }
/** * Sets the cached Site data with a non-associated array of site data. * * This method will trigger the `Sites.setSites` event modifying `$sites` before setting cached * site data. In other words, this method will change the site data before it is cached and then * return the modified array. * * @param array $sites The array of sites data. eg, * * array( * array('idsite' => '1', 'name' => 'Site 1', ...), * array('idsite' => '2', 'name' => 'Site 2', ...), * ) * @return array The modified array. * @internal */ public static function setSitesFromArray($sites) { self::triggerSetSitesEvent($sites);
foreach ($sites as $site) { $idSite = null; if (!empty($site['idsite'])) { $idSite = $site['idsite']; }
self::setSiteFromArray($idSite, $site); }
return $sites; }
/** * The Multisites reports displays the first calendar date as the earliest day available for all websites. * Also, today is the later "today" available across all timezones. * @param array $siteIds Array of IDs for each site being displayed. * @return Date[] of two Date instances. First is the min-date & the second * is the max date. * @ignore */ public static function getMinMaxDateAcrossWebsites($siteIds) { $siteIds = self::getIdSitesFromIdSitesString($siteIds); $now = Date::now();
$minDate = null; $maxDate = $now->subDay(1)->getTimestamp(); foreach ($siteIds as $idsite) { // look for 'now' in the website's timezone $timezone = Site::getTimezoneFor($idsite); $date = Date::adjustForTimezone($now->getTimestamp(), $timezone); if ($date > $maxDate) { $maxDate = $date; }
// look for the absolute minimum date $creationDate = Site::getCreationDateFor($idsite); $date = Date::adjustForTimezone(strtotime($creationDate), $timezone); if (is_null($minDate) || $date < $minDate) { $minDate = $date; } }
return array(Date::factory($minDate), Date::factory($maxDate)); }
/** * Returns a string representation of the site this instance references. * * Useful for debugging. * * @return string */ public function __toString() { return "site id=" . $this->getId() . ", name=" . $this->getName() . ", url = " . $this->getMainUrl() . ", IPs excluded = " . $this->getExcludedIps() . ", timezone = " . $this->getTimezone() . ", currency = " . $this->getCurrency() . ", creation date = " . $this->getCreationDate(); }
/** * Returns the name of the site. * * @return string * @throws Exception if data for the site cannot be found. */ public function getName() { return $this->get('name'); }
/** * Returns the main url of the site. * * @return string * @throws Exception if data for the site cannot be found. */ public function getMainUrl() { return $this->get('main_url'); }
/** * Returns the id of the site. * * @return int * @throws Exception if data for the site cannot be found. */ public function getId() { return $this->id; }
/** * Returns a site property by name. * * @param string $name Name of the property to return (eg, `'main_url'` or `'name'`). * @return mixed * @throws Exception */ protected function get($name) { if (isset($this->site[$name])) { return $this->site[$name]; }
throw new Exception("The property $name could not be found on the website ID " . (int)$this->id); }
/** * Returns the website type (by default `"website"`, which means it is a single website). * * @return string */ public function getType() { $type = $this->get('type'); return $type; }
/** * Returns the creation date of the site. * * @return Date * @throws Exception if data for the site cannot be found. */ public function getCreationDate() { $date = $this->get('ts_created'); return Date::factory($date); }
/** * Returns the timezone of the size. * * @return string * @throws Exception if data for the site cannot be found. */ public function getTimezone() { return $this->get('timezone'); }
/** * Returns the currency of the site. * * @return string * @throws Exception if data for the site cannot be found. */ public function getCurrency() { return $this->get('currency'); }
/** * Returns the excluded ips of the site. * * @return string * @throws Exception if data for the site cannot be found. */ public function getExcludedIps() { return $this->get('excluded_ips'); }
/** * Returns the excluded query parameters of the site. * * @return string * @throws Exception if data for the site cannot be found. */ public function getExcludedQueryParameters() { return $this->get('excluded_parameters'); }
/** * Returns whether ecommerce is enabled for the site. * * @return bool * @throws Exception if data for the site cannot be found. */ public function isEcommerceEnabled() { return $this->get('ecommerce') == 1; }
/** * Returns the site search keyword query parameters for the site. * * @return string * @throws Exception if data for the site cannot be found. */ public function getSearchKeywordParameters() { return $this->get('sitesearch_keyword_parameters'); }
/** * Returns the site search category query parameters for the site. * * @return string * @throws Exception if data for the site cannot be found. */ public function getSearchCategoryParameters() { return $this->get('sitesearch_category_parameters'); }
/** * Returns whether Site Search Tracking is enabled for the site. * * @return bool * @throws Exception if data for the site cannot be found. */ public function isSiteSearchEnabled() { return $this->get('sitesearch') == 1; }
/** * Returns the user that created this site. * * @return string|null If null, the site was created before the creation user was tracked. */ public function getCreatorLogin() { return $this->get('creator_login'); }
/** * Checks the given string for valid site IDs and returns them as an array. * * @param bool|int|string|array<string|int|null> $ids Comma separated idSite list, eg, `'1,2,3,4'` or an array of IDs, eg, * `array(1, 2, 3, 4)`, or 'all'. * @param bool|string $_restrictSitesToLogin Implementation detail. Used only when running as a scheduled task. * @param bool $throwOnInvalid If true, throw when an invalid id is supplied. * @return list<int> An array of valid, unique integers. */ public static function getIdSitesFromIdSitesString($ids, $_restrictSitesToLogin = false, bool $throwOnInvalid = false): array { if (empty($ids)) { return []; }
if ($ids === 'all' || $ids === ['all']) { return API::getInstance()->getSitesIdWithAtLeastViewAccess($_restrictSitesToLogin); }
if (is_bool($ids)) { if ($throwOnInvalid) { throw new BadRequestException("The parameter 'idSite=' contains an invalid value."); } return []; } if (!is_array($ids)) { $ids = explode(',', $ids); } $validIds = []; foreach ($ids as $id) { $id = is_string($id) ? trim($id) : $id; if (is_null($id) || $id === '') { continue; } if (is_numeric($id) && (string)$id === (string)(int)$id && (int)$id > 0) { $validIds[] = (int)$id; continue; } if ($throwOnInvalid) { throw new BadRequestException("The parameter 'idSite=' contains an invalid value."); } } $validIds = array_filter($validIds); return array_unique($validIds); }
/** * Clears the site data cache. * * See also {@link setSites()} and {@link setSitesFromArray()}. */ public static function clearCache() { self::$infoSites = array(); }
/** * Clears the site data cache. * * See also {@link setSites()} and {@link setSitesFromArray()}. */ public static function clearCacheForSite($idSite) { $idSite = (int)$idSite; unset(self::$infoSites[$idSite]); }
/** * Utility function. Returns the value of the specified field for the * site with the specified ID. * * @param int $idsite The ID of the site whose data is being accessed. * @param string $field The name of the field to get. * @return string */ protected static function getFor(int $idsite, string $field) { if (!isset(self::$infoSites[$idsite])) { $site = API::getInstance()->getSiteFromId($idsite); self::setSiteFromArray($idsite, $site); }
return self::$infoSites[$idsite][$field]; }
/** * Returns all websites pre-cached * * @ignore */ public static function getSites() { return self::$infoSites; }
/** * @ignore */ public static function getSite($idsite) { $idsite = (int)$idsite;
if (!isset(self::$infoSites[$idsite])) { $site = API::getInstance()->getSiteFromId($idsite); self::setSiteFromArray($idsite, $site); }
return self::$infoSites[$idsite]; }
/** * Returns the name of the site with the specified ID. * * @param int $idsite The site ID. * @return string */ public static function getNameFor($idsite) { return self::getFor((int)$idsite, 'name'); }
/** * Returns the group of the site with the specified ID. * * @param int $idsite The site ID. * @return string */ public static function getGroupFor($idsite) { return self::getFor((int)$idsite, 'group'); }
/** * Returns the timezone of the site with the specified ID. * * @param int $idsite The site ID. * @return string */ public static function getTimezoneFor($idsite) { return self::getFor((int)$idsite, 'timezone'); }
/** * Returns the type of the site with the specified ID. * * @param $idsite * @return string */ public static function getTypeFor($idsite) { return self::getFor((int)$idsite, 'type'); }
/** * Returns the creation date of the site with the specified ID. * * @param int $idsite The site ID. * @return string */ public static function getCreationDateFor($idsite) { return self::getFor((int)$idsite, 'ts_created'); }
/** * Returns the url for the site with the specified ID. * * @param int $idsite The site ID. * @return string */ public static function getMainUrlFor($idsite) { return self::getFor((int)$idsite, 'main_url'); }
/** * Returns whether the site with the specified ID is ecommerce enabled or not. * * @param int $idsite The site ID. * @return string */ public static function isEcommerceEnabledFor($idsite) { return self::getFor((int)$idsite, 'ecommerce') == 1; }
/** * Returns whether the site with the specified ID is Site Search enabled. * * @param int $idsite The site ID. * @return string */ public static function isSiteSearchEnabledFor($idsite) { return self::getFor((int)$idsite, 'sitesearch') == 1; }
/** * Returns the currency of the site with the specified ID. * * @param int $idsite The site ID. * @return string */ public static function getCurrencyFor($idsite) { return self::getFor((int)$idsite, 'currency'); }
/** * Returns the currency of the site with the specified ID. * * @param int $idsite The site ID. * @return string */ public static function getCurrencySymbolFor($idsite) { $currencyCode = self::getCurrencyFor($idsite); $key = 'Intl_CurrencySymbol_' . $currencyCode; $symbol = Piwik::translate($key);
if ($key === $symbol) { return $currencyCode; }
return $symbol; }
/** * Returns the excluded IP addresses of the site with the specified ID. * * @param int $idsite The site ID. * @return string */ public static function getExcludedIpsFor($idsite) { return self::getFor((int)$idsite, 'excluded_ips'); }
/** * Returns the excluded query parameters for the site with the specified ID. * * @param int $idsite The site ID. * @return string */ public static function getExcludedQueryParametersFor($idsite) { return self::getFor((int)$idsite, 'excluded_parameters'); }
/** * Returns the user that created this site. * * @param int $idsite The site ID. * @return string|null If null, the site was created before the creation user was tracked. */ public static function getCreatorLoginFor($idsite) { return self::getFor((int)$idsite, 'creator_login'); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402<?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 Matomo\Cache\Lazy;use Piwik\Config\GeneralConfig;use Piwik\Container\StaticContainer;use Piwik\Plugins\SitesManager\SiteContentDetection\ConsentManagerDetectionAbstract;use Piwik\Plugins\SitesManager\SiteContentDetection\SiteContentDetectionAbstract;
/** * This class provides detection functions for specific content on a site. It can be used to easily detect the * presence of known third party code. * * Note: Calling the `detectContent()` method will create a HTTP request to the site to retrieve data, only the main site URL * will be checked * * Usage: * * $contentDetector = new SiteContentDetector(); * $contentDetector->detectContent([GoogleAnalytics3::getId()]); * if ($contentDetector->ga3) { * // site is using GA3 * } * * @api */class SiteContentDetector{ /** * @var array<string, array<string, SiteContentDetectionAbstract>> */ public $detectedContent = [ SiteContentDetectionAbstract::TYPE_TRACKER => [], SiteContentDetectionAbstract::TYPE_CMS => [], SiteContentDetectionAbstract::TYPE_JS_FRAMEWORK => [], SiteContentDetectionAbstract::TYPE_CONSENT_MANAGER => [], SiteContentDetectionAbstract::TYPE_JS_CRASH_ANALYTICS => [], SiteContentDetectionAbstract::TYPE_OTHER => [], ];
public $connectedConsentManagers = [];
private $siteResponse = [ 'data' => '', 'headers' => [], ];
/** @var Lazy */ private $cache;
public function __construct(?Lazy $cache = null) { if ($cache === null) { $this->cache = Cache::getLazyCache(); } else { $this->cache = $cache; } }
/** * @return array<string, SiteContentDetectionAbstract[]> */ public static function getSiteContentDetectionsByType(): array { $instancesByType = []; $classes = self::getAllSiteContentDetectionClasses();
foreach ($classes as $className) { $instancesByType[$className::getContentType()][] = StaticContainer::get($className); }
return $instancesByType; }
/** * Returns the site content detection object with the provided id, or null if it can't be found */ public function getSiteContentDetectionById(string $id): ?SiteContentDetectionAbstract { $classes = $this->getAllSiteContentDetectionClasses();
foreach ($classes as $className) { if ($className::getId() === $id) { return StaticContainer::get($className); } }
return null; }
/** * @return string[] */ protected static function getAllSiteContentDetectionClasses(): array { return Plugin\Manager::getInstance()->findMultipleComponents('SiteContentDetection', SiteContentDetectionAbstract::class); }
/** * Reset the detections */ private function resetDetections(): void { $this->detectedContent = [ SiteContentDetectionAbstract::TYPE_TRACKER => [], SiteContentDetectionAbstract::TYPE_CMS => [], SiteContentDetectionAbstract::TYPE_JS_FRAMEWORK => [], SiteContentDetectionAbstract::TYPE_CONSENT_MANAGER => [], SiteContentDetectionAbstract::TYPE_JS_CRASH_ANALYTICS => [], SiteContentDetectionAbstract::TYPE_OTHER => [], ]; $this->connectedConsentManagers = []; }
/** * This will query the site and populate the class properties with * the details of the detected content * * @param array $detectContent Array of content type for which to check, defaults to all, limiting this list * will speed up the detection check. * Allowed values are: * * empty array - to run all detections * * an array containing ids of detections, e.g. Wordpress::getId() or any of the * type constants, e.g. SiteContentDetectionAbstract::TYPE_TRACKER * @param ?int $idSite Override the site ID, will use the site from the current request if null * @param ?array $siteResponse String containing the site data to search, if blank then data will be retrieved * from the current request site via an http request * @param int $timeOut How long to wait for the site to response, defaults to 5 seconds */ public function detectContent( array $detectContent = [], ?int $idSite = null, ?array $siteResponse = null, int $timeOut = 5 ): void { $this->resetDetections();
// If site data was passed in, then just run the detection checks against it and return. if ($siteResponse) { $this->siteResponse = $siteResponse; $this->detectionChecks($detectContent); return; }
// Get the site id from the request object if not explicitly passed if ($idSite === null) { $idSite = Request::fromRequest()->getIntegerParameter('idSite', 0);
if (!$idSite) { return; } }
$url = Site::getMainUrlFor($idSite);
// Check and load previously cached site content detection data if it exists $cacheKey = 'SiteContentDetection_' . md5($url); $siteContentDetectionCache = $this->cache->fetch($cacheKey);
if ($siteContentDetectionCache !== false) { if ($this->checkCacheHasRequiredProperties($detectContent, $siteContentDetectionCache)) { $this->detectedContent = $siteContentDetectionCache['detectedContent']; $this->connectedConsentManagers = $siteContentDetectionCache['connectedConsentManagers']; return; } }
// No cache hit, no passed data, so make a request for the site content $siteResponse = $this->requestSiteResponse($url, $timeOut);
// Abort if still no site data if (empty($siteResponse['data'])) { return; }
$this->siteResponse = $siteResponse;
// We now have site data to analyze, so run the detection checks $this->detectionChecks($detectContent);
// A request was made to get this data and it isn't currently cached, so write it to the cache now $cacheLife = (60 * 60 * 24 * 7); $this->saveToCache($cacheKey, $cacheLife); }
/** * Returns if the detection with the provided id was detected or not * * Note: self::detectContent needs to be called before. */ public function wasDetected(string $detectionClassId): bool { foreach ($this->detectedContent as $type => $detectedClassIds) { if (array_key_exists($detectionClassId, $detectedClassIds)) { return $detectedClassIds[$detectionClassId] ?? false; } }
return false; }
/** * Returns an array containing ids of all detected detections of the given type * * @param int $type One of the SiteContentDetectionAbstract::TYPE_* constants * @return array */ public function getDetectsByType(int $type): array { $detected = [];
foreach ($this->detectedContent[$type] as $objId => $wasDetected) { if (true === $wasDetected) { $detected[] = $objId; } }
return $detected; }
/** * Checks that all required detections are in the cache array * * @param array $detectContent * @param array $cache */ private function checkCacheHasRequiredProperties(array $detectContent, array $cache): bool { if (empty($detectContent)) { foreach (self::getSiteContentDetectionsByType() as $type => $entries) { foreach ($entries as $entry) { if (!isset($cache['detectedContent'][$type][$entry::getId()])) { return false; // random detection missing } } }
return true; }
foreach ($detectContent as $requestedDetection) { if (is_string($requestedDetection)) { // specific detection $detectionObj = $this->getSiteContentDetectionById($requestedDetection); if (null !== $detectionObj && !isset($cache['detectedContent'][$detectionObj::getContentType()][$detectionObj::getId()])) { return false; // specific detection was run before } } elseif (is_int($requestedDetection)) { // detection type requested $detectionsByType = self::getSiteContentDetectionsByType(); if (isset($detectionsByType[$requestedDetection])) { foreach ($detectionsByType[$requestedDetection] as $detectionObj) { if (!isset($cache['detectedContent'][$requestedDetection][$detectionObj::getId()])) { return false; // random detection missing } } } } }
return true; }
/** * Save data to the cache */ private function saveToCache(string $cacheKey, int $cacheLife): void { $cacheData = [ 'detectedContent' => [], 'connectedConsentManagers' => [], ];
// Load any existing cached values $siteContentDetectionCache = $this->cache->fetch($cacheKey);
if (is_array($siteContentDetectionCache)) { $cacheData = $siteContentDetectionCache; }
foreach ($this->detectedContent as $type => $detections) { if (!isset($cacheData['detectedContent'][$type])) { $cacheData['detectedContent'][$type] = []; } foreach ($detections as $detectionId => $wasDetected) { if (null !== $wasDetected) { $cacheData['detectedContent'][$type][$detectionId] = $wasDetected; } } }
$cacheData['connectedConsentManagers'] = array_merge($cacheData['connectedConsentManagers'], $this->connectedConsentManagers);
$this->cache->save($cacheKey, $cacheData, $cacheLife); }
/** * Run various detection checks for site content * * @param array $detectContent Array of detection types used to filter the checks that are run */ private function detectionChecks(array $detectContent): void { $detections = $this->getSiteContentDetectionsByType();
foreach ($detections as $type => $typeDetections) { foreach ($typeDetections as $typeDetection) { $this->detectedContent[$type][$typeDetection::getId()] = null;
if ( in_array($type, $detectContent) || in_array($typeDetection::getId(), $detectContent) || empty($detectContent) ) { $this->detectedContent[$type][$typeDetection::getId()] = false;
if ($typeDetection->isDetected($this->siteResponse['data'], $this->siteResponse['headers'])) { if ( $typeDetection instanceof ConsentManagerDetectionAbstract && $typeDetection->checkIsConnected($this->siteResponse['data'], $this->siteResponse['headers']) ) { $this->connectedConsentManagers[] = $typeDetection::getId(); } $this->detectedContent[$type][$typeDetection::getId()] = true; } } } } }
/** * Retrieve data from the specified site using an HTTP request * * @return array */ private function requestSiteResponse(string $url, int $timeOut): array { if (!$url) { return []; }
// If internet features are disabled, we don't try to fetch any site content if (0 === GeneralConfig::getIntegerConfigValue('enable_internet_features', 0)) { return []; }
$siteData = [];
try { $siteData = Http::sendHttpRequestBy( Http::getTransportMethod(), $url, $timeOut, null, null, null, 0, false, true, false, true ); } catch (\Exception $e) { }
return $siteData; }
/** * Return an array of consent manager definitions which can be used to detect their presence on the site and show * the associated guide links * * Note: This list is also used to display the known / supported consent managers on the "Ask for Consent" page * For adding a new consent manager to this page, it needs to be added here. If a consent manager can't be detected * automatically, simply leave the detections empty. * * @return array[] */ public static function getKnownConsentManagers(): array { $detections = self::getSiteContentDetectionsByType(); $cmDetections = $detections[SiteContentDetectionAbstract::TYPE_CONSENT_MANAGER];
$consentManagers = [];
foreach ($cmDetections as $detection) { $consentManagers[$detection::getId()] = [ 'name' => $detection::getName(), 'instructionUrl' => $detection::getInstructionUrl(), ]; }
return $consentManagers; }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071<?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 Piwik\Container\StaticContainer;use Piwik\DeviceDetector\DeviceDetectorFactory;use Piwik\Exception\NotSupportedBrowserException;
class SupportedBrowser{ /** * A list of browsers with version numbers that are not supported. A browser * is not supported if it's included in this array and the version number * is smaller or equal to the number in this array. If the user's browser * not included in this list or the version number is higher, then * supported. * * Current version numbers are coming from this list: * $ npx browserslist */ private static $notSupportedBrowsers = [ 'FF' => 51, 'IE' => 11, 'SF' => 10, 'CH' => 48, 'OP' => 72, 'PS' => 17, ];
public static function checkIfBrowserSupported() { $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''; if ($userAgent === '') { return; }
$ddFactory = StaticContainer::get(DeviceDetectorFactory::class); /** @var \DeviceDetector\DeviceDetector */ $deviceDetector = $ddFactory->makeInstance($userAgent, Http::getClientHintsFromServerVariables());
$deviceDetector->parse(); $client = $deviceDetector->getClient();
if (!empty($client) && $client['type'] === 'browser' && self::browserNotSupported($client['short_name'], (int)$client['version'])) { self::throwException($client); } }
private static function browserNotSupported($shortName, $version) { return array_key_exists($shortName, self::$notSupportedBrowsers) && $version > 0 && $version <= self::$notSupportedBrowsers[$shortName]; }
private static function throwException($client) { $message = "<p><b>" . Piwik::translate('General_ExceptionNotSupportedBrowserTitle') . "</b></p>"; $message .= "<p>" . Piwik::translate('General_ExceptionNotSupportedBrowserText') . "</p>";
$exception = new NotSupportedBrowserException($message); $exception->setIsHtmlMessage();
throw $exception; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687<?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;
/** * TCPDF class wrapper. * * phpcs:ignoreFile PSR1.Methods.CamelCapsMethodName.NotCamelCaps */class TCPDF extends \TCPDF{ protected $footerContent = null; protected $currentPageNo = null;
/** * Render page footer * * @see TCPDF::Footer() */ public function Footer() { //Don't show footer on the frontPage if ($this->currentPageNo > 1) { $this->SetY(-15); $this->SetFont($this->footer_font[0], $this->footer_font[1], $this->footer_font[2]); $this->Cell(0, 10, $this->footerContent . Piwik::translate('ScheduledReports_Pagination', array($this->getAliasNumPage(), $this->getAliasNbPages())), 0, false, 'C', 0, '', 0, false, 'T', 'M'); } }
/** * @see TCPDF::Error() * @param $msg * @throws Exception */ public function Error($msg) { $this->_destroy(true); throw new Exception($msg); }
/** * Set current page number */ public function setCurrentPageNo() { if (empty($this->currentPageNo)) { $this->currentPageNo = 1; } else { $this->currentPageNo++; } }
/** * Add page to document * * @see TCPDF::AddPage() * * @param string $orientation * @param mixed $format * @param bool $keepmargins * @param bool $tocpage */ public function AddPage($orientation = '', $format = '', $keepmargins = false, $tocpage = false) { parent::AddPage($orientation); $this->setCurrentPageNo(); }
/** * Set footer content * * @param string $footerContent */ public function SetFooterContent($footerContent) { $this->footerContent = $footerContent; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166<?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 Piwik\Plugin\Manager;
/** * This class contains logic to make Themes work beautifully. * */class Theme{ /** @var string */ private $themeName;
/** @var \Piwik\Plugin */ private $theme;
/** * @param Plugin|false $plugin */ public function __construct($plugin = false) { $this->createThemeFromPlugin($plugin ? $plugin : Manager::getInstance()->getThemeEnabled()); }
/** * @param Plugin $plugin */ private function createThemeFromPlugin($plugin) { $this->theme = $plugin; $this->themeName = $plugin->getPluginName(); }
public function getStylesheet() { if ($this->themeName == \Piwik\Plugin\Manager::DEFAULT_THEME) { return false; }
$info = $this->theme->getInformation(); if (!isset($info['stylesheet'])) { return false; } $themeStylesheet = 'plugins/' . $this->theme->getPluginName() . '/' . $info['stylesheet']; return $themeStylesheet; }
public function getJavaScriptFiles() { if ($this->themeName == \Piwik\Plugin\Manager::DEFAULT_THEME) { return false; }
$info = $this->theme->getInformation(); if (empty($info['javascript'])) { return false; } $jsFiles = $info['javascript']; if (!is_array($jsFiles)) { $jsFiles = array($jsFiles); } foreach ($jsFiles as &$jsFile) { $jsFile = 'plugins/' . $this->theme->getPluginName() . '/' . $jsFile; } return $jsFiles; }
public function rewriteAssetsPathToTheme($output) { if ( $this->themeName == \Piwik\Plugin\Manager::DEFAULT_THEME && !Manager::getAlternativeWebRootDirectories() ) { return $output; }
$pattern = array( // Rewriting scripts includes to overrides '~<script type=[\'"]text/javascript[\'"] (src)=[\'"]([^\'"]+)[\'"]>~', '~<script (src)=[\'"]([^\'"]+)[\'"] type=[\'"]text/javascript[\'"]>~', '~<link (rel)=[\'"]stylesheet[\'"] type=[\'"]text/css[\'"] href=[\'"]([^\'"]+)[\'"] ?/?>~',
// Images as well '~(src|href)=[\'"]([^\'"]+)[\'"]~',
// rewrite images in CSS files '~(url\()[\'"]([^\)]?[plugins]+[^\)]+[.jpg|png|gif|svg]?)[\'"][\)]~',
// url(plugins/....) '~(url\()([^\)]?[plugins]+[^\)]+[.jpg|png|gif|svg]?)[\)]~',
// rewrites images in JS files '~(=)[\s]?[\'"]([^\'"]+[.jpg|.png|.gif|svg]?)[\'"]~', ); return preg_replace_callback($pattern, array($this, 'rewriteAssetPathIfOverridesFound'), $output); }
private function rewriteAssetPathIfOverridesFound($src) { $source = $src[0]; $pathAsset = $src[2];
// Basic health check, we don't replace if not starting with plugins/ $posPluginsInPath = strpos($pathAsset, 'plugins'); if ($posPluginsInPath !== 0) { return $source; }
// or if it's already rewritten if (strpos($pathAsset, $this->themeName) !== false) { return $source; }
$pathPluginName = substr($pathAsset, strlen('plugins/')); $nextSlash = strpos($pathPluginName, '/'); if ($nextSlash === false) { return $source; } $pathPluginName = substr($pathPluginName, 0, $nextSlash);
// replace all plugin assets to the theme, if the theme overrides this asset // when there are name conflicts (two plugins define the same asset name in same folder), // we shall rename so there is no more conflict. $defaultThemePath = "plugins/" . $pathPluginName; $newThemePath = "plugins/" . $this->themeName; $overridingAsset = str_replace($defaultThemePath, $newThemePath, $pathAsset);
// Strip trailing query string $fileToCheck = $overridingAsset; $queryStringPos = strpos($fileToCheck, '?'); if ($queryStringPos !== false) { $fileToCheck = substr($fileToCheck, 0, $queryStringPos); }
if (file_exists($fileToCheck)) { return str_replace($pathAsset, $overridingAsset, $source); }
// not rewritten by theme, but may be located in custom webroot directory foreach (Manager::getAlternativeWebRootDirectories() as $absDir => $webRootDirectory) { $withoutPlugins = str_replace('plugins/', '', $pathAsset); if (file_exists($absDir . '/' . $withoutPlugins)) { return str_replace($pathAsset, $webRootDirectory . $withoutPlugins, $source); } }
return $source; }
/** * @return string */ public function getThemeName() { return $this->themeName; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126<?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 Piwik\Metrics\Formatter;
class Timer{ private $timerStart; private $memoryStart; private $formatter; private $timerEnd;
public function __construct() { $this->formatter = new Formatter();
$this->init(); }
/** * @return void */ public function init() { $this->timerStart = $this->getMicrotime(); $this->memoryStart = $this->getMemoryUsage(); }
public function finish() { $this->timerEnd = $this->getMicrotime(); }
/** * @param int $decimals * @return string */ public function getTime($decimals = 3) { return number_format($this->getTimerEnd() - $this->timerStart, $decimals, '.', ''); }
/** * @param int $decimals * @return string */ public function getTimeMs($decimals = 3) { return number_format(1000 * ($this->getTimerEnd() - $this->timerStart), $decimals, '.', ''); }
/** * @return string */ public function getMemoryLeak() { return "Memory delta: " . $this->getMemoryLeakValue(); }
/** * @return string */ public function getMemoryLeakValue() { return $this->formatter->getPrettySizeFromBytes($this->getMemoryUsage() - $this->memoryStart); }
/** * @return string */ public function getPeakMemoryValue() { return $this->formatter->getPrettySizeFromBytes($this->getPeakMemoryUsage()); }
/** * @return string */ public function __toString() { return "Time elapsed: " . $this->getTime() . "s"; }
private function getTimerEnd() { return $this->timerEnd ?: $this->getMicrotime(); }
/** * @return float */ private function getMicrotime() { list($micro_seconds, $seconds) = explode(" ", microtime()); return ((float)$micro_seconds + (float)$seconds); }
/** * Returns current memory usage, if available * * @return int */ private function getMemoryUsage() { if (function_exists('memory_get_usage')) { return memory_get_usage(); } return 0; }
public function getPeakMemoryUsage() { if (function_exists('memory_get_peak_usage')) { return memory_get_peak_usage(); } return 0; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402<?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 Piwik\Container\StaticContainer;use Piwik\DeviceDetector\DeviceDetectorFactory;use Piwik\Plugins\BulkTracking\Tracker\Requests;use Piwik\Plugins\PrivacyManager\Config as PrivacyManagerConfig;use Piwik\Tracker\BotRequest;use Piwik\Tracker\Db as TrackerDb;use Piwik\Tracker\Db\DbException;use Piwik\Tracker\Handler;use Piwik\Tracker\Request;use Piwik\Tracker\RequestSet;use Piwik\Tracker\TrackerConfig;use Piwik\Tracker\Visit;use Piwik\Plugin\Manager as PluginManager;use Piwik\Log\LoggerInterface;
/** * Class used by the logging script piwik.php called by the javascript tag. * Handles the visitor and their actions on the website, saves the data in the DB, * saves information in the cookie, etc. * * We try to include as little files as possible (no dependency on 3rd party modules). */class Tracker{ /** * @var Db|null */ private static $db = null;
// We use hex ID that are 16 chars in length, ie. 64 bits IDs public const LENGTH_HEX_ID_STRING = 16; public const LENGTH_BINARY_ID = 8;
public static $initTrackerMode = false;
private $countOfLoggedRequests = 0; protected $isInstalled = null;
/** * @var LoggerInterface */ private $logger;
public function __construct() { $this->logger = StaticContainer::get(LoggerInterface::class); }
public function isDebugModeEnabled() { return array_key_exists('PIWIK_TRACKER_DEBUG', $GLOBALS) && $GLOBALS['PIWIK_TRACKER_DEBUG'] === true; }
public function shouldRecordStatistics() { $record = TrackerConfig::getConfigValue('record_statistics') != 0;
if (!$record) { $this->logger->debug('Tracking is disabled in the config.ini.php via record_statistics=0'); }
return $record && $this->isInstalled(); }
public static function loadTrackerEnvironment() { SettingsServer::setIsTrackerApiRequest(); if (empty($GLOBALS['PIWIK_TRACKER_DEBUG'])) { $GLOBALS['PIWIK_TRACKER_DEBUG'] = self::isDebugEnabled(); } if (!empty($GLOBALS['PIWIK_TRACKER_DEBUG']) && !Common::isPhpCliMode()) { Common::sendHeader('Content-Type: text/plain'); } PluginManager::getInstance()->loadTrackerPlugins(); }
private function init() { $this->handleFatalErrors();
if ($this->isDebugModeEnabled()) { ErrorHandler::registerErrorHandler(); ExceptionHandler::setUp();
$this->logger->debug("Debug enabled - Input parameters: {params}", [ 'params' => var_export($_GET + $_POST, true), ]); } }
public function isInstalled() { if (is_null($this->isInstalled)) { $this->isInstalled = SettingsPiwik::isMatomoInstalled(); }
return $this->isInstalled; }
public function main(Handler $handler, RequestSet $requestSet) { try { $this->init();
if ($this->isPreFlightCorsRequest()) { Common::sendHeader('Access-Control-Allow-Methods: GET, POST'); Common::sendHeader('Access-Control-Allow-Headers: *'); Common::sendHeader('Access-Control-Allow-Origin: *'); Common::sendResponseCode(204); $this->logger->debug("Tracker detected preflight CORS request. Skipping..."); return null; }
$handler->init($this, $requestSet);
$this->track($handler, $requestSet); } catch (Exception $e) { $this->logger->debug("Tracker encountered an exception: {ex}", [$e]);
$handler->onException($this, $requestSet, $e); }
Piwik::postEvent('Tracker.end'); $response = $handler->finish($this, $requestSet);
$this->disconnectDatabase();
return $response; }
public function track(Handler $handler, RequestSet $requestSet) { if (!$this->shouldRecordStatistics()) { return; }
$requestSet->initRequestsAndTokenAuth();
if ($requestSet->hasRequests()) { $handler->onStartTrackRequests($this, $requestSet); $handler->process($this, $requestSet); $handler->onAllRequestsTracked($this, $requestSet); } }
/** * @return void */ public function trackRequest(Request $request) { if ($request->isEmptyRequest()) { $this->logger->debug('The request is empty'); } else { $this->logger->debug('Current datetime: {date}', [ 'date' => date("Y-m-d H:i:s", $request->getCurrentTimestamp()), ]);
$isBot = $this->isBotRequest($request);
/** * Allows overwriting the Bot detection done using Device Detector * Use this event if you want to have a request handled as bot request instead of a normal visit * * @param bool &$isBot Indicates if the request should be handled as Bot * @param Request $request current tracking request */ Piwik::postEvent('Tracker.isBotRequest', [&$isBot, $request]);
$rawParams = $request->getRawParams();
/** * The recMode param will for now be used to keep BC. * If it is not set, which is currently the case for all tracking requests, it will be processed as Visit only * When set to 1, only bot tracking will be processed. In case the request is not detected as bot, it will be discarded * Setting it to 2 enables auto mode. Meaning it will be either processed as bot request or visit, depending on the detection * * @deprecated Remove this parameter handling with Matomo 6 and decide the tracking method based on the bot detection only. */ $recMode = $rawParams['recMode'] ?? null;
if (((int)$recMode === 1 || (int)$recMode === 2) && $isBot) { $botRequest = StaticContainer::get(BotRequest::class); $botRequest->setRequest($request); $botRequest->handle(); }
if (empty($recMode) || ((int)$recMode === 2 && !$isBot)) { $visit = Visit\Factory::make(); $visit->setRequest($request); $visit->handle(); } }
// increment successfully logged request count. make sure to do this after try-catch, // since an excluded visit is considered 'successfully logged' ++$this->countOfLoggedRequests; }
private function isBotRequest(Request $request): bool { $deviceDetector = StaticContainer::get(DeviceDetectorFactory::class)->makeInstance($request->getUserAgent(), $request->getClientHints()); return $deviceDetector->isBot(); }
/** * Used to initialize core Piwik components on a piwik.php request * Eg. when cache is missed and we will be calling some APIs to generate cache */ public static function initCorePiwikInTrackerMode() { if ( SettingsServer::isTrackerApiRequest() && self::$initTrackerMode === false ) { self::$initTrackerMode = true; require_once PIWIK_INCLUDE_PATH . '/core/Option.php';
Access::getInstance(); Config::getInstance();
try { Db::get(); } catch (Exception $e) { Db::createDatabaseObject(); }
PluginManager::getInstance()->loadCorePluginsDuringTracker(); } }
public static function restoreTrackerPlugins() { if (SettingsServer::isTrackerApiRequest() && Tracker::$initTrackerMode) { Plugin\Manager::getInstance()->loadTrackerPlugins(); } }
public function getCountOfLoggedRequests() { return $this->countOfLoggedRequests; }
public function setCountOfLoggedRequests($numLoggedRequests) { $this->countOfLoggedRequests = $numLoggedRequests; }
public function hasLoggedRequests() { return 0 !== $this->countOfLoggedRequests; }
public function isDatabaseConnected() { return !is_null(self::$db); }
public static function getDatabase() { if (is_null(self::$db)) { try { self::$db = TrackerDb::connectPiwikTrackerDb(); } catch (Exception $e) { $code = $e->getCode(); // Note: PDOException might return a string as code, but we can't use this for DbException throw new DbException($e->getMessage(), is_int($code) ? $code : 0); } }
return self::$db; }
protected function disconnectDatabase() { if ($this->isDatabaseConnected()) { // note: I think we do this only for the tests self::$db->disconnect(); self::$db = null; } }
// for tests public static function disconnectCachedDbConnection() { // code redundancy w/ above is on purpose; above disconnectDatabase depends on method that can potentially be overridden if (!is_null(self::$db)) { self::$db->disconnect(); self::$db = null; } }
public static function setTestEnvironment($args = null, $requestMethod = null) { if (is_null($args)) { $requests = new Requests(); $args = $requests->getRequestsArrayFromBulkRequest($requests->getRawBulkRequest()); $args = $_GET + $args; }
if (is_null($requestMethod) && array_key_exists('REQUEST_METHOD', $_SERVER)) { $requestMethod = $_SERVER['REQUEST_METHOD']; } elseif (is_null($requestMethod)) { $requestMethod = 'GET'; }
// Do not run scheduled tasks during tests if (!defined('DEBUG_FORCE_SCHEDULED_TASKS')) { TrackerConfig::setConfigValue('scheduled_tasks_min_interval', 0); }
// if nothing found in _GET/_POST and we're doing a POST, assume bulk request. in which case, // we have to bypass authentication if (empty($args) && $requestMethod == 'POST') { TrackerConfig::setConfigValue('tracking_requests_require_authentication', 0); }
// Tests can force the use of 3rd party cookie for ID visitor if (Common::getRequestVar('forceEnableFingerprintingAcrossWebsites', false, null, $args) == 1) { TrackerConfig::setConfigValue('enable_fingerprinting_across_websites', 1); }
// Tests can simulate the tracker API maintenance mode if (Common::getRequestVar('forceEnableTrackerMaintenanceMode', false, null, $args) == 1) { TrackerConfig::setConfigValue('record_statistics', 0); }
// Tests can force the use of 3rd party cookie for ID visitor if (Common::getRequestVar('forceUseThirdPartyCookie', false, null, $args) == 1) { TrackerConfig::setConfigValue('use_third_party_id_cookie', 1); }
// Tests using window_look_back_for_visitor if ( Common::getRequestVar('forceLargeWindowLookBackForVisitor', false, null, $args) == 1 // also look for this in bulk requests (see fake_logs_replay.log) || strpos(json_encode($args, true), '"forceLargeWindowLookBackForVisitor":"1"') !== false ) { TrackerConfig::setConfigValue('window_look_back_for_visitor', 2678400); }
// Tests can force the enabling of IP anonymization if (Common::getRequestVar('forceIpAnonymization', false, null, $args) == 1) { self::getDatabase(); // make sure db is initialized
$privacyConfig = new PrivacyManagerConfig(); $privacyConfig->ipAddressMaskLength = 2;
\Piwik\Plugins\PrivacyManager\IPAnonymizer::activate();
\Piwik\Tracker\Cache::deleteTrackerCache(); Filesystem::clearPhpCaches(); } }
private function handleFatalErrors() { register_shutdown_function(function () { // TODO: add a log here $lastError = error_get_last(); if (!empty($lastError) && $lastError['type'] == E_ERROR) { Common::sendResponseCode(500); } }); }
private static function isDebugEnabled() { try { $debug = TrackerConfig::getBoolConfigValue('debug', false); if ($debug) { return true; }
$debugOnDemand = TrackerConfig::getBoolConfigValue('debug_on_demand', false); if ($debugOnDemand) { return (bool) Common::getRequestVar('debug', false); } } catch (Exception $e) { }
return false; }
public function isPreFlightCorsRequest(): bool { if (isset($_SERVER['REQUEST_METHOD']) && strtoupper($_SERVER['REQUEST_METHOD']) === 'OPTIONS') { return !empty($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']) || !empty($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']); } return false; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465<?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 Exception;use Piwik\Common;use Piwik\Container\StaticContainer;use Piwik\Plugin\Dimension\ActionDimension;use Piwik\Plugin\Manager;use Piwik\Log\LoggerInterface;
/** * An action * */abstract class Action{ public const TYPE_PAGE_URL = 1; public const TYPE_OUTLINK = 2; public const TYPE_DOWNLOAD = 3; public const TYPE_PAGE_TITLE = 4; public const TYPE_ECOMMERCE_ITEM_SKU = 5; public const TYPE_ECOMMERCE_ITEM_NAME = 6; public const TYPE_ECOMMERCE_ITEM_CATEGORY = 7; public const TYPE_SITE_SEARCH = 8;
public const TYPE_EVENT = 10; // Alias TYPE_EVENT_CATEGORY public const TYPE_EVENT_CATEGORY = 10; public const TYPE_EVENT_ACTION = 11; public const TYPE_EVENT_NAME = 12;
public const TYPE_CONTENT = 13; // Alias TYPE_CONTENT_NAME public const TYPE_CONTENT_NAME = 13; public const TYPE_CONTENT_PIECE = 14; public const TYPE_CONTENT_TARGET = 15; public const TYPE_CONTENT_INTERACTION = 16;
public const DB_COLUMN_CUSTOM_FLOAT = 'custom_float';
private static $factoryPriority = array( self::TYPE_PAGE_URL, self::TYPE_SITE_SEARCH, self::TYPE_CONTENT, self::TYPE_EVENT, self::TYPE_OUTLINK, self::TYPE_DOWNLOAD, );
/** * Public so that events listener can access it * * @var Request */ public $request;
private $idLinkVisitAction; private $actionIdsCached = array(); private $customFields = array(); private $actionName; private $actionType;
/** * URL with excluded Query parameters */ private $actionUrl;
/** * Raw URL (will contain excluded URL query parameters) */ private $rawActionUrl;
/** * @var mixed|LoggerInterface */ private $logger;
/** * Makes the correct Action object based on the request. * * @return Action */ public static function factory(Request $request) { /** @var Action[] $actions */ $actions = self::getAllActions($request);
foreach ($actions as $actionType) { if (empty($action)) { $action = $actionType; continue; }
$posPrevious = self::getPriority($action); $posCurrent = self::getPriority($actionType);
if ($posCurrent > $posPrevious) { $action = $actionType; } }
if (!empty($action)) { return $action; }
if (self::isCustomActionRequest($request)) { throw new Exception('Request was meant for a plugin which is no longer activated. Request needs to be ignored.'); }
return new ActionPageview($request); }
/** * Returns true if the tracking request was meant for some action that isn't the page view. See * https://github.com/matomo-org/matomo/pull/16570 for more details. Basically, plugins that implement a tracker * action should send a `ca=1` tracking parameter along the request so it doesn't get executed should the plugin * be disabled but the JS tracker is still cached and keeps on sending these requests. * * @return bool * @throws Exception */ public static function isCustomActionRequest(Request $request) { return $request->hasParam('ca') && $request->getParam('ca'); }
private static function getPriority(Action $actionType) { $key = array_search($actionType->getActionType(), self::$factoryPriority);
if (false === $key) { return -1; }
return $key; }
public static function shouldHandle(Request $request) { return false; }
private static function getAllActions(Request $request) { static $actions;
if (is_null($actions)) { $actions = Manager::getInstance()->findMultipleComponents('Actions', '\\Piwik\\Tracker\\Action'); }
$instances = array();
foreach ($actions as $action) { /** @var \Piwik\Tracker\Action $action */ if ($action::shouldHandle($request)) { $instances[] = new $action($request); } }
return $instances; }
public function __construct($type, Request $request) { $this->actionType = $type; $this->request = $request; $this->logger = StaticContainer::get(LoggerInterface::class); }
/** * Returns URL of the page currently being tracked, or the file being downloaded, or the outlink being clicked * * @return string|false|null */ public function getActionUrl() { return $this->actionUrl; }
/** * Returns URL of page being tracked, including all original Query parameters */ public function getActionUrlRaw() { return $this->rawActionUrl; }
public function getActionName() { return $this->actionName; }
public function getActionType() { return $this->actionType; }
// custom_float column public function getCustomFloatValue() { return false; }
protected function setActionName($name) { $this->actionName = PageUrl::cleanupString((string)$name); }
protected function setActionUrl($url) { $this->rawActionUrl = PageUrl::getUrlIfLookValid($url); $url2 = PageUrl::excludeQueryParametersFromUrl($url, $this->request->getIdSite());
$this->actionUrl = PageUrl::getUrlIfLookValid($url2);
if ($url != $this->rawActionUrl) { $this->logger->debug(' Before was "{rawActionUrl}"', [ 'rawActionUrl' => $this->rawActionUrl, ]); $this->logger->debug(' After is "{url2}"', [ 'url2' => $url2, ]); } }
protected function setActionUrlWithoutExcludingParameters($url) { $url = PageUrl::getUrlIfLookValid($url); $this->rawActionUrl = $url; $this->actionUrl = $url; }
abstract protected function getActionsToLookup();
protected function getUrlAndType() { $url = $this->getActionUrl();
if (!empty($url)) { // normalize urls by stripping protocol and www $url = PageUrl::normalizeUrl($url); return array($url['url'], self::TYPE_PAGE_URL, $url['prefixId']); }
return false; }
public function setCustomField($field, $value) { $this->customFields[$field] = $value; }
public function getCustomField($field) { if (isset($this->customFields[$field])) { return $this->customFields[$field]; } }
public function getCustomFields() { return $this->customFields; }
public function getIdActionUrl() { $idUrl = isset($this->actionIdsCached['idaction_url']) ? $this->actionIdsCached['idaction_url'] : 0; // note; idaction_url = 0 is displayed as "Page URL Not Defined" return (int)$idUrl; }
public function getIdActionUrlForEntryAndExitIds() { return false; }
public function getIdActionNameForEntryAndExitIds() { return false; }
public function getIdActionName() { if (!isset($this->actionIdsCached['idaction_name'])) { return false; }
return $this->actionIdsCached['idaction_name']; }
/** * Returns the ID of the newly created record in the log_link_visit_action table * * @return int */ public function getIdLinkVisitAction() { return $this->idLinkVisitAction; }
public static function getTypeAsString($type) { $class = new \ReflectionClass("\\Piwik\\Tracker\\Action"); $constants = $class->getConstants();
$typeId = array_search($type, $constants);
if (false === $typeId) { return $type; }
return str_replace('TYPE_', '', $typeId); }
/** * Loads the idaction of the current action name and the current action url. * These idactions are used in the visitor logging table to link the visit information * (entry action, exit action) to the actions. * These idactions are also used in the table that links the visits and their actions. * * The methods takes care of creating a new record(s) in the action table if the existing * action name and action url doesn't exist yet. */ public function loadIdsFromLogActionTable() { if (!empty($this->actionIdsCached)) { return; }
/** @var ActionDimension[] $dimensions */ $dimensions = ActionDimension::getAllDimensions(); $actions = $this->getActionsToLookup();
foreach ($dimensions as $dimension) { $value = $dimension->onLookupAction($this->request, $this);
if (false !== $value) { if (is_float($value)) { $value = Common::forceDotAsSeparatorForDecimalPoint($value); }
$field = $dimension->getColumnName();
if (empty($field)) { $dimensionClass = get_class($dimension); throw new Exception('Dimension ' . $dimensionClass . ' does not define a field name'); }
$actionId = $dimension->getActionId(); $actions[$field] = array($value, $actionId); $this->logger->debug("$field = $value"); } }
$actions = array_filter($actions);
if (empty($actions)) { return; }
$loadedActionIds = TableLogAction::loadIdsAction($actions);
$this->actionIdsCached = $loadedActionIds; return $this->actionIdsCached; }
/** * Records in the DB the association between the visit and this action. * * @param int $idReferrerActionUrl is the ID of the last action done by the current visit. * @param $idReferrerActionName */ public function record(Visitor $visitor, $idReferrerActionUrl, $idReferrerActionName) {
$this->loadIdsFromLogActionTable();
$visitAction = array( 'idvisit' => $visitor->getVisitorColumn('idvisit'), 'idsite' => $this->request->getIdSite(), 'idvisitor' => $visitor->getVisitorColumn('idvisitor'), 'idaction_url' => $this->getIdActionUrl(), 'idaction_url_ref' => $idReferrerActionUrl, 'idaction_name_ref' => $idReferrerActionName, );
/** @var ActionDimension[] $dimensions */ $dimensions = ActionDimension::getAllDimensions();
foreach ($dimensions as $dimension) { $value = $dimension->onNewAction($this->request, $visitor, $this);
if ($value !== false) { if (is_float($value)) { $value = Common::forceDotAsSeparatorForDecimalPoint($value); }
$visitAction[$dimension->getColumnName()] = $value; } }
// idaction_name is NULLable. we only set it when applicable if ($this->isActionHasActionName()) { $visitAction['idaction_name'] = (int)$this->getIdActionName(); }
foreach ($this->actionIdsCached as $field => $idAction) { $visitAction[$field] = ($idAction === false) ? 0 : $idAction; }
$customValue = $this->getCustomFloatValue(); if ($customValue !== false && $customValue !== null && $customValue !== '') { $visitAction[self::DB_COLUMN_CUSTOM_FLOAT] = Common::forceDotAsSeparatorForDecimalPoint($customValue); }
$visitAction = array_merge($visitAction, $this->customFields);
$this->idLinkVisitAction = $this->getModel()->createAction($visitAction);
$visitAction['idlink_va'] = $this->idLinkVisitAction;
$visitActionDebug = $visitAction; $visitActionDebug['idvisitor'] = bin2hex($visitActionDebug['idvisitor']); $this->logger->debug("Inserted new action: {action}", [ 'action' => var_export($visitActionDebug, true), ]); }
public function writeDebugInfo() { $type = self::getTypeAsString($this->getActionType()); $name = $this->getActionName(); $url = $this->getActionUrl();
$this->logger->debug('Action is a {type}, Action name = {name}, Action URL = {url}', [ 'type' => $type, 'name' => $name, 'url' => $url, ]);
return true; }
private function getModel() { return new Model(); }
/** * @return bool */ private function isActionHasActionName() { $types = array(self::TYPE_PAGE_TITLE, self::TYPE_PAGE_URL, self::TYPE_SITE_SEARCH);
return in_array($this->getActionType(), $types); }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495<?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\Config;
/** * This class represents a page view, tracking URL, page title and generation time. * */class ActionPageview extends Action{ public function __construct(Request $request) { parent::__construct(Action::TYPE_PAGE_URL, $request);
$url = $request->getParam('url'); $this->setActionUrl($url);
$actionName = $request->getParam('action_name'); $actionName = $this->cleanupActionName($actionName); $this->setActionName($actionName); }
protected function getActionsToLookup() { return array( 'idaction_name' => array($this->getActionName(), Action::TYPE_PAGE_TITLE), 'idaction_url' => $this->getUrlAndType(), ); }
public static function shouldHandle(Request $request) { return !Action::isCustomActionRequest($request); }
public function getIdActionUrlForEntryAndExitIds() { return $this->getIdActionUrl(); }
public function getIdActionNameForEntryAndExitIds() { return $this->getIdActionName(); }
private function cleanupActionName($actionName) { // get the delimiter, by default '/'; BC, we read the old action_category_delimiter first (see #1067) $actionCategoryDelimiter = $this->getActionCategoryDelimiter();
if ($actionCategoryDelimiter === '') { return $actionName; }
// create an array of the categories delimited by the delimiter $split = explode($actionCategoryDelimiter, $actionName); $split = $this->trimEveryCategory($split); $split = $this->removeEmptyCategories($split);
return $this->rebuildNameOfCleanedCategories($actionCategoryDelimiter, $split); }
private function rebuildNameOfCleanedCategories($actionCategoryDelimiter, $split) { return implode($actionCategoryDelimiter, $split); }
private function removeEmptyCategories($split) { return array_filter($split, 'strlen'); }
private function trimEveryCategory($split) { return array_map('trim', $split); }
private function getActionCategoryDelimiter() { if (isset(Config::getInstance()->General['action_category_delimiter'])) { return Config::getInstance()->General['action_category_delimiter']; }
return Config::getInstance()->General['action_title_category_delimiter']; }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
declare(strict_types=1);
namespace Piwik\Tracker;
use Piwik\Log\LoggerInterface;use Piwik\Plugin\RequestProcessors;
/** * Class used to handle a Bot request. */class BotRequest{ use RequestHandlerTrait;
/** * @var Request */ protected $request;
/** * @var BotRequestProcessor[] */ protected $botRequestProcessors;
/** * @var RequestProcessor[] */ protected $requestProcessors;
/** * @var LoggerInterface */ protected $logger;
public function __construct(RequestProcessors $requestProcessors, LoggerInterface $logger) { $this->requestProcessors = $requestProcessors->getRequestProcessors(); $this->botRequestProcessors = $requestProcessors->getBotRequestProcessors(); $this->logger = $logger; }
public function setRequest(Request $request) { $this->request = $request; }
public function handle() { $this->checkSiteExists($this->request);
/** * For BC reasons we iterate over all visit request processors as well, to ensure a possible request manipulation is applied * For Matomo 6 we should remove that and ensure plugins that also should manipulate bot requests implement a BotRequestProcessor for it * @deprecated */ foreach ($this->requestProcessors as $processor) { $this->logger->debug("Executing " . get_class($processor) . "::manipulateRequest()...");
$processor->manipulateRequest($this->request); }
foreach ($this->botRequestProcessors as $processor) { $this->logger->debug("Executing " . get_class($processor) . "::manipulateRequest()...");
$processor->manipulateRequest($this->request); }
$this->validateRequest($this->request);
$wasHandled = false;
foreach ($this->botRequestProcessors as $processor) { $this->logger->debug("Executing " . get_class($processor) . "::handleRequest()...");
$wasHandled |= $processor->handleRequest($this->request); }
if ($wasHandled) { $this->markArchivedReportsAsInvalidIfArchiveAlreadyFinished($this->request); } }}1234567891011121314151617181920212223242526272829303132333435363738<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
declare(strict_types=1);
namespace Piwik\Tracker;
abstract class BotRequestProcessor{ /** * This is the first method called when processing a bot request. * * Derived classes can use this method to manipulate a bot request before the request * is handled. Plugins could change the URL, add custom variables, etc. */ public function manipulateRequest(Request $request): void { // empty }
/** * This method is called last. * * Derived classes should use this method to insert log data. * * @return bool return true if the processor handled the request, this will automatically trigger archive invalidation */ public function handleRequest(Request $request): bool { return false; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321<?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\Access;use Piwik\ArchiveProcessor\Rules;use Piwik\Cache as PiwikCache;use Piwik\Config;use Piwik\Container\StaticContainer;use Piwik\Option;use Piwik\Piwik;use Piwik\Tracker;use Piwik\Log\LoggerInterface;
/** * Simple cache mechanism used in Tracker to avoid requesting settings from mysql on every request * */class Cache{ /** * {@see self::withDelegatedCacheClears()} * @var bool */ private static $delegatingCacheClears;
/** * {@see self::withDelegatedCacheClears()} * @var array */ private static $delegatedClears = [];
private static $cacheIdGeneral = 'general';
/** * Public for tests only * @var \Matomo\Cache\Lazy */ public static $cache;
/** * @return \Matomo\Cache\Lazy */ private static function getCache() { if (is_null(self::$cache)) { self::$cache = PiwikCache::getLazyCache(); }
return self::$cache; }
private static function getTtl() { return Config::getInstance()->Tracker['tracker_cache_file_ttl']; }
/** * Returns array containing data about the website: goals, URLs, etc. * * @param int $idSite * @return array */ public static function getCacheWebsiteAttributes($idSite) { if ('all' === $idSite) { return []; }
$idSite = (int)$idSite; if ($idSite <= 0) { return []; }
$cache = self::getCache(); $cacheId = self::getCacheKeyWebsiteAttributes($idSite); $cacheContent = $cache->fetch($cacheId);
if (false !== $cacheContent) { return $cacheContent; }
return self::updateCacheWebsiteAttributes($idSite); }
private static function getCacheKeyWebsiteAttributes($idSite) { return $idSite; }
/** * Updates the website specific tracker cache containing data about the website: goals, URLs, etc. * * @param int $idSite * * @return array */ public static function updateCacheWebsiteAttributes($idSite) { $cache = self::getCache(); $cacheId = self::getCacheKeyWebsiteAttributes($idSite);
Tracker::initCorePiwikInTrackerMode();
$content = []; /* * Updating cached websites attributes might be triggered by various events, including actions performed by non super users. * Therefore we execute below code as super user, to ensure the cache is built without restrictions. */ Access::doAsSuperUser(function () use (&$content, $idSite) { /** * Triggered to get the attributes of a site entity that might be used by the * Tracker. * * Plugins add new site attributes for use in other tracking events must * use this event to put those attributes in the Tracker Cache. * * **Example** * * public function getSiteAttributes($content, $idSite) * { * $sql = "SELECT info FROM " . Common::prefixTable('myplugin_extra_site_info') . " WHERE idsite = ?"; * $content['myplugin_site_data'] = Db::fetchOne($sql, [$idSite]); * } * * @param array &$content Array mapping of site attribute names with values. * @param int $idSite The site ID to get attributes for. */ Piwik::postEvent('Tracker.Cache.getSiteAttributes', [&$content, $idSite]);
$logger = StaticContainer::get(LoggerInterface::class); $logger->debug("Website $idSite tracker cache was re-created."); });
// if nothing is returned from the plugins, we don't save the content // this is not expected: all websites are expected to have at least one URL if (!empty($content)) { $cache->save($cacheId, $content, self::getTtl()); }
Tracker::restoreTrackerPlugins();
return $content; }
/** * Clear general (global) cache */ public static function clearCacheGeneral() { if (self::$delegatingCacheClears) { self::$delegatedClears[__FUNCTION__] = [__FUNCTION__, []]; return; }
self::getCache()->delete(self::$cacheIdGeneral); }
/** * Returns contents of general (global) cache. * If the cache file tmp/cache/tracker/general.php does not exist yet, create it * * @return array */ public static function getCacheGeneral() { $cache = self::getCache(); $cacheContent = $cache->fetch(self::$cacheIdGeneral);
if (false !== $cacheContent) { return $cacheContent; }
return self::updateGeneralCache(); }
/** * Updates the contents of the general (global) cache. * * @return array */ public static function updateGeneralCache() { Tracker::initCorePiwikInTrackerMode(); $cacheContent = [ 'isBrowserTriggerEnabled' => Rules::isBrowserTriggerEnabled(), 'lastTrackerCronRun' => Option::get('lastTrackerCronRun'), ];
/** * Triggered before the [general tracker cache](/guides/all-about-tracking#the-tracker-cache) * is saved to disk. This event can be used to add extra content to the cache. * * Data that is used during tracking but is expensive to compute/query should be * cached to keep tracking efficient. One example of such data are options * that are stored in the option table. Querying data for each tracking * request means an extra unnecessary database query for each visitor action. Using * a cache solves this problem. * * **Example** * * public function setTrackerCacheGeneral(&$cacheContent) * { * $cacheContent['MyPlugin.myCacheKey'] = Option::get('MyPlugin_myOption'); * } * * @param array &$cacheContent Array of cached data. Each piece of data must be * mapped by name. */ Piwik::postEvent('Tracker.setTrackerCacheGeneral', [&$cacheContent]); self::setCacheGeneral($cacheContent);
$logger = StaticContainer::get(LoggerInterface::class); $logger->debug("General tracker cache was re-created.");
Tracker::restoreTrackerPlugins();
return $cacheContent; }
/** * Store data in general (global cache) * * @param mixed $value * @return bool */ public static function setCacheGeneral($value) { $cache = self::getCache();
return $cache->save(self::$cacheIdGeneral, $value, self::getTtl()); }
/** * Regenerate Tracker cache files * * @param array|int $idSites Array of idSites to clear cache for */ public static function regenerateCacheWebsiteAttributes($idSites = []) { if (!is_array($idSites)) { $idSites = [$idSites]; }
foreach ($idSites as $idSite) { self::deleteCacheWebsiteAttributes($idSite); self::getCacheWebsiteAttributes($idSite); } }
/** * Delete existing Tracker cache * * @param string|int $idSite website ID of the site to clear cache for */ public static function deleteCacheWebsiteAttributes($idSite) { if (self::$delegatingCacheClears) { self::$delegatedClears[__FUNCTION__ . $idSite] = [__FUNCTION__, func_get_args()]; return; }
self::getCache()->delete((int)$idSite); }
/** * Deletes all Tracker cache files */ public static function deleteTrackerCache() { if (self::$delegatingCacheClears) { self::$delegatedClears[__FUNCTION__] = [__FUNCTION__, []]; return; }
self::getCache()->flushAll(); }
/** * Runs `$callback` without clearing any tracker cache, just collecting which delete methods were called. * After `$callback` finishes, we clear caches, but just once per type of delete/clear method collected. * * Use this method if your code will create many cache clears in a short amount of time (eg, if you * are invalidating a lot of archives at once). * * @param $callback */ public static function withDelegatedCacheClears($callback) { try { self::$delegatingCacheClears = true; self::$delegatedClears = [];
return $callback(); } finally { self::$delegatingCacheClears = false;
self::callAllDelegatedClears();
self::$delegatedClears = []; } }
private static function callAllDelegatedClears() { foreach (self::$delegatedClears as list($methodName, $params)) { if (!method_exists(self::class, $methodName)) { continue; }
call_user_func_array([self::class, $methodName], $params); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114<?php
namespace Piwik\Tracker\Config;
use Piwik\Piwik;use Piwik\Settings\Interfaces\ConfigSettingInterface;use Piwik\Settings\Interfaces\PolicyComparisonInterface;use Piwik\Settings\Interfaces\SettingValueInterface;use Piwik\Settings\Interfaces\Traits\PolicyComparisonTrait;use Piwik\Settings\Interfaces\Traits\Getters\ConfigGetterTrait;use Piwik\Policy\CnilPolicy;
/** * @implements ConfigSettingInterface<bool|null> * @implements PolicyComparisonInterface<bool|null> * @implements SettingValueInterface<bool|null> */class ThirdPartyCookies implements ConfigSettingInterface, PolicyComparisonInterface, SettingValueInterface{ /** * @use ConfigGetterTrait<bool|null> */ use ConfigGetterTrait;
/** * @use PolicyComparisonTrait<bool|null> */ use PolicyComparisonTrait;
/** * @var bool|null */ private $value;
private function __construct(?bool $value) { $this->value = $value; }
protected static function getConfigSection(): string { return 'Tracker'; }
protected static function getConfigSettingName(): string { return 'use_third_party_id_cookie'; }
public static function getPolicyRequirements(): array { return [ CnilPolicy::class => false, ]; }
public static function isCompliant(string $policy, ?int $idSite = null): bool { $policyValues = self::getPolicyRequirements();
if (!array_key_exists($policy, $policyValues)) { return true; }
$currentValue = self::getInstance($idSite)->getValue();
return $currentValue === $policyValues[$policy]; }
public static function getComplianceRequirementNote(?int $idSite = null): string { return Piwik::translate('General_ThirdPartyCookieSettingNote'); }
protected static function compareStrictness($value1, $value2): bool { if ($value1 === true && $value2 === true) { return true; } return false; }
public static function getTitle(): string { return Piwik::translate('General_ThirdPartyCookieSettingTitle'); }
public static function getInstance(?int $idSite = null): self { $values = self::getPolicyRequiredValues($idSite); $configValue = self::getConfigValue($idSite);
if ($configValue === null) { // Without site ID $configValue = self::getConfigValue(); } $values['config'] = $configValue; $strictest = self::getStrictestValueFromArray($values); return new self($strictest); }
public function getValue() { return $this->value; }
public static function getInlineHelp(): string { return ''; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305<?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 Exception;use Piwik\Common;use Piwik\Config;use Piwik\Db\Adapter;use Piwik\Db\TransactionalDatabaseInterface;use Piwik\Db\TransactionalDatabaseStaticTrait;use Piwik\Piwik;use Piwik\Timer;use Piwik\Tracker\Db\DbException;
/** * Simple database wrapper. * We can't afford to have a dependency with the Zend_Db module in Tracker. * We wrote this simple class * */abstract class Db implements TransactionalDatabaseInterface{ use TransactionalDatabaseStaticTrait;
protected static $profiling = false;
protected $queriesProfiling = array();
protected $connection = null;
/** * Enables the SQL profiling. * For each query, saves in the DB the time spent on this query. * Very useful to see the slow query under heavy load. * You can then use Piwik::displayDbTrackerProfile(); * to display the SQLProfiling report and see which queries take time, etc. */ public static function enableProfiling() { self::$profiling = true; }
/** * Disables the SQL profiling logging. */ public static function disableProfiling() { self::$profiling = false; }
/** * Returns true if the SQL profiler is enabled * Only used by the unit test that tests that the profiler is off on a production server * * @return bool */ public static function isProfilingEnabled() { return self::$profiling; }
/** * Initialize profiler * * @return Timer */ protected function initProfiler() { return new Timer(); }
/** * Record query profile * * @param string $query * @param Timer $timer */ protected function recordQueryProfile($query, $timer) { if (!isset($this->queriesProfiling[$query])) { $this->queriesProfiling[$query] = array('sum_time_ms' => 0, 'count' => 0); }
$time = $timer->getTimeMs(2); $time += $this->queriesProfiling[$query]['sum_time_ms']; $count = $this->queriesProfiling[$query]['count'] + 1;
$this->queriesProfiling[$query] = array('sum_time_ms' => $time, 'count' => $count); }
/** * When destroyed, if SQL profiled enabled, logs the SQL profiling information */ public function recordProfiling() { if (is_null($this->connection)) { return; }
// turn off the profiler so we don't profile the following queries self::$profiling = false;
foreach ($this->queriesProfiling as $query => $info) { $time = $info['sum_time_ms']; $time = Common::forceDotAsSeparatorForDecimalPoint($time); $count = $info['count'];
$queryProfiling = "INSERT INTO " . Common::prefixTable('log_profiling') . " (query,count,sum_time_ms) VALUES (?,$count,$time) ON DUPLICATE KEY UPDATE count=count+$count,sum_time_ms=sum_time_ms+$time"; $this->query($queryProfiling, array($query)); }
// turn back on profiling self::$profiling = true; }
/** * Connects to the DB * * @throws \Piwik\Tracker\Db\DbException if there was an error connecting the DB */ abstract public function connect();
/** * Disconnects from the server */ public function disconnect() { $this->connection = null; }
/** * Returns an array containing all the rows of a query result, using optional bound parameters. * * @param string $query Query * @param array $parameters Parameters to bind * @see query() * @throws \Piwik\Tracker\Db\DbException if an exception occurred */ abstract public function fetchAll($query, $parameters = array());
/** * Returns the first row of a query result, using optional bound parameters. * * @param string $query Query * @param array $parameters Parameters to bind * @see also query() * * @throws DbException if an exception occurred */ abstract public function fetch($query, $parameters = array());
/** * This function is a proxy to fetch(), used to maintain compatibility with Zend_Db interface * * @see fetch() * @param string $query Query * @param array $parameters Parameters to bind * @return array|false */ public function fetchRow($query, $parameters = array()) { return $this->fetch($query, $parameters); }
/** * This function is a proxy to fetch(), used to maintain compatibility with Zend_Db interface * * @see fetch() * @param string $query Query * @param array $parameters Parameters to bind * @return bool|mixed */ public function fetchOne($query, $parameters = array()) { $result = $this->fetch($query, $parameters); return is_array($result) && !empty($result) ? reset($result) : false; }
/** * This function is a proxy to fetch(), used to maintain compatibility with Zend_Db + PDO interface * * @see fetch() * @param string $query Query * @param array $parameters Parameters to bind * @return array|false */ public function exec($query, $parameters = array()) { return $this->fetch($query, $parameters); }
/** * Return number of affected rows in last query * * @param mixed $queryResult Result from query() * @return int */ abstract public function rowCount($queryResult);
/** * Executes a query, using optional bound parameters. * * @param string $query Query * @param array $parameters Parameters to bind array('idsite'=> 1) * * @return PDOStatement or false if failed * @throws DbException if an exception occurred */ abstract public function query($query, $parameters = array());
/** * Returns the last inserted ID in the DB * Wrapper of PDO::lastInsertId() * * @return int */ abstract public function lastInsertId();
/** * Test error number * * @param Exception $e * @param string|int $errno * @return bool True if error number matches; false otherwise */ abstract public function isErrNo($e, $errno);
/** * Factory to create database objects * * @param array $configDb Database configuration * @throws Exception * @return \Piwik\Tracker\Db\Mysqli|\Piwik\Tracker\Db\Pdo\Mysql */ public static function factory($configDb) { /** * Triggered before a connection to the database is established by the Tracker. * * This event can be used to change the database connection settings used by the Tracker. * * @param array $dbInfos Reference to an array containing database connection info, * including: * * - **host**: The host name or IP address to the MySQL database. * - **username**: The username to use when connecting to the * database. * - **password**: The password to use when connecting to the * database. * - **dbname**: The name of the Piwik MySQL database. * - **port**: The MySQL database port to use. * - **adapter**: either `'PDO\MYSQL'` or `'MYSQLI'` * - **type**: The MySQL engine to use, for instance 'InnoDB' */ Piwik::postEvent('Tracker.getDatabaseConfig', array(&$configDb));
$className = 'Piwik\Tracker\Db\\' . str_replace(' ', '\\', ucwords(str_replace(array('_', '\\'), ' ', strtolower($configDb['adapter']))));
if (!class_exists($className)) { throw new Exception('Unsupported database adapter ' . $configDb['adapter']); }
return new $className($configDb); }
public static function connectPiwikTrackerDb() { $db = null; $configDb = Config::getInstance()->database;
if (!isset($configDb['port'])) { // before 0.2.4 there is no port specified in config file $configDb['port'] = '3306'; }
$db = self::factory($configDb);
try { $db->connect(); } catch (\Exception $e) { $msg = Adapter::overriddenExceptionMessage($e->getMessage()); if ('' !== $msg) { throw new \Exception($msg); } throw $e; }
$trackerConfig = Config::getInstance()->Tracker; if (!empty($trackerConfig['innodb_lock_wait_timeout']) && $trackerConfig['innodb_lock_wait_timeout'] > 0) { // we set this here because we only want to set this config if a connection is actually created. $time = (int) $trackerConfig['innodb_lock_wait_timeout']; $db->query('SET @@innodb_lock_wait_timeout = ' . $time); } return $db; }}1234567891011121314151617181920<?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\Db;
use Exception;
/** * Database Exception * */class DbException extends Exception{}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473<?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\Db;
use Exception;use Piwik\Tracker\Db;
/** * mysqli wrapper * */class Mysqli extends Db{ protected $connection = null; protected $host; protected $port; protected $socket; protected $dbname; protected $username; protected $password; protected $charset; protected $collation; protected $activeTransaction = null;
protected $enable_ssl; protected $ssl_key; protected $ssl_cert; protected $ssl_ca; protected $ssl_ca_path; protected $ssl_cipher; protected $ssl_no_verify; protected $paramNb; protected $params;
/** * Builds the DB object * * @param array $dbInfo */
public function __construct($dbInfo) { if (isset($dbInfo['unix_socket']) && substr($dbInfo['unix_socket'], 0, 1) == '/') { $this->host = null; $this->port = null; $this->socket = $dbInfo['unix_socket']; } elseif (isset($dbInfo['port']) && substr($dbInfo['port'], 0, 1) == '/') { $this->host = null; $this->port = null; $this->socket = $dbInfo['port']; } else { $this->host = $dbInfo['host']; $this->port = (int)$dbInfo['port']; $this->socket = null; }
$this->dbname = $dbInfo['dbname']; $this->username = $dbInfo['username']; $this->password = $dbInfo['password']; $this->charset = $dbInfo['charset'] ?? null; $this->collation = $dbInfo['collation'] ?? null;
if (!empty($dbInfo['enable_ssl'])) { $this->enable_ssl = $dbInfo['enable_ssl']; } if (!empty($dbInfo['ssl_key'])) { $this->ssl_key = $dbInfo['ssl_key']; } if (!empty($dbInfo['ssl_cert'])) { $this->ssl_cert = $dbInfo['ssl_cert']; } if (!empty($dbInfo['ssl_ca'])) { $this->ssl_ca = $dbInfo['ssl_ca']; } if (!empty($dbInfo['ssl_ca_path'])) { $this->ssl_ca_path = $dbInfo['ssl_ca_path']; } if (!empty($dbInfo['ssl_cipher'])) { $this->ssl_cipher = $dbInfo['ssl_cipher']; } if (!empty($dbInfo['ssl_no_verify'])) { $this->ssl_no_verify = $dbInfo['ssl_no_verify']; } }
/** * Destructor */ public function __destruct() { $this->connection = null; }
/** * Connects to the DB * * @throws Exception|DbException if there was an error connecting the DB */ public function connect() { if (self::$profiling) { $timer = $this->initProfiler(); }
// The default error reporting of mysqli changed in PHP 8.1. To circumvent problems in our error handling we set // the erroring reporting to the default that was used prior PHP 8.1 // See https://php.watch/versions/8.1/mysqli-error-mode for more details mysqli_report(MYSQLI_REPORT_OFF);
$this->connection = mysqli_init();
if ($this->enable_ssl) { mysqli_ssl_set($this->connection, $this->ssl_key, $this->ssl_cert, $this->ssl_ca, $this->ssl_ca_path, $this->ssl_cipher); }
// Make sure MySQL returns all matched rows on update queries including // rows that actually didn't have to be updated because the values didn't // change. This matches common behaviour among other database systems. // See #6296 why this is important in tracker $flags = MYSQLI_CLIENT_FOUND_ROWS; if ($this->enable_ssl) { $flags = $flags | MYSQLI_CLIENT_SSL; } if ($this->ssl_no_verify && defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT')) { $flags = $flags | MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT; } mysqli_real_connect($this->connection, $this->host, $this->username, $this->password, $this->dbname, $this->port, $this->socket, $flags); if (!$this->connection || mysqli_connect_errno()) { throw new DbException("Connect failed: " . mysqli_connect_error()); }
if ($this->charset && $this->collation) { // mysqli_set_charset does not support setting a collation $query = "SET NAMES '" . $this->charset . "' COLLATE '" . $this->collation . "'";
if (!mysqli_query($this->connection, $query)) { throw new DbException("Set charset/connection collation failed: " . mysqli_error($this->connection)); } } elseif ($this->charset) { if (!mysqli_set_charset($this->connection, $this->charset)) { throw new DbException("Set Charset failed: " . mysqli_error($this->connection)); } }
$this->password = '';
if (self::$profiling && isset($timer)) { $this->recordQueryProfile('connect', $timer); } }
/** * Disconnects from the server */ public function disconnect() { mysqli_close($this->connection); $this->connection = null; }
/** * @param \mysqli_stmt $stmt * @param $fields * @return array|bool|false */ private function fetchResult($stmt, $fields) {
$values = array_fill(0, count($fields), null);
$refs = array(); foreach ($values as $i => &$f) { $refs[$i] = &$f; }
call_user_func_array(array($stmt, 'bind_result'), $values);
$result = $stmt->fetch();
if ($result === null || $result === false) { $stmt->reset(); return false; }
$val = array(); foreach ($values as $key => $value) { $val[] = $value; }
$row = array_combine($fields, $values);
return $row; }
/** * Returns an array containing all the rows of a query result, using optional bound parameters. * * @see query() * * @param string $query Query * @param array $parameters Parameters to bind * @return array * @throws Exception|DbException if an exception occurred */ public function fetchAll($query, $parameters = array()) { try { if (self::$profiling) { $timer = $this->initProfiler(); }
list($stmt, $fields) = $this->executeQuery($query, $parameters);
$rows = array(); while ($row = $this->fetchResult($stmt, $fields)) { $rows[] = $row; }
$stmt->free_result(); $stmt->close();
if (self::$profiling && isset($timer)) { $this->recordQueryProfile($query, $timer); } return $rows; } catch (Exception $e) { throw new DbException("Error query: " . $e->getMessage()); } }
/** * Returns the first row of a query result, using optional bound parameters. * * @see query() * * @param string $query Query * @param array $parameters Parameters to bind * * @return array|false */ public function fetch($query, $parameters = array()) { try { if (self::$profiling) { $timer = $this->initProfiler(); }
list($stmt, $fields) = $this->executeQuery($query, $parameters);
$row = $this->fetchResult($stmt, $fields);
$stmt->free_result(); $stmt->close();
if (self::$profiling && isset($timer)) { $this->recordQueryProfile($query, $timer); } if ($row === null) { $row = false; } return $row; } catch (Exception $e) { throw new DbException("Error query: " . $e->getMessage()); } }
/** * Executes a query, using optional bound parameters. * * @param string $query Query * @param array|string $parameters Parameters to bind array('idsite'=> 1) * * @return \mysqli_stmt|false false if failed */ public function query($query, $parameters = array()) { if (is_null($this->connection)) { return false; }
try { if (self::$profiling) { $timer = $this->initProfiler(); }
list($stmt, $fields) = $this->executeQuery($query, $parameters);
if (self::$profiling && isset($timer)) { $this->recordQueryProfile($query, $timer); } return $stmt; } catch (Exception $e) { throw new DbException("Error query: " . $e->getMessage() . " In query: $query Parameters: " . var_export($parameters, true), $e->getCode()); } }
/** * Returns the last inserted ID in the DB * * @return int */ public function lastInsertId() { return mysqli_insert_id($this->connection); }
private function executeQuery($sql, $bind) {
$stmt = mysqli_prepare($this->connection, $sql);
if (!$stmt) { throw new DbException('preparing query failed: ' . mysqli_error($this->connection) . ' : ' . $sql); }
if (!is_array($bind)) { $bind = array($bind); }
if (!empty($bind)) { array_unshift($bind, str_repeat('s', count($bind))); $refs = array(); foreach ($bind as $key => $value) { $refs[$key] = &$bind[$key]; }
call_user_func_array(array($stmt, 'bind_param'), $refs); }
$stmtResult = $stmt->execute();
if ($stmtResult === false) { throw new DbException("Mysqli statement execute error : " . $stmt->error, $stmt->errno); }
if (!empty($stmt->error)) { throw new DbException('executeQuery() failed: ' . mysqli_error($this->connection) . ' : ' . $sql); }
$metaResults = $stmt->result_metadata();
if ($stmt->errno) { throw new DbException("Mysqli statement metadata error: " . $stmt->error, $stmt->errno); }
$fields = array(); if ($metaResults) { $fetchedFields = $metaResults->fetch_fields(); foreach ($fetchedFields as $fetchedField) { $fields[] = $fetchedField->name; } $stmt->store_result(); }
return array($stmt, $fields); } /** * Input is a prepared SQL statement and parameters * Returns the SQL statement * * @param string $query * @param array $parameters * @return string */ private function prepare($query, $parameters) { if (!$parameters) { $parameters = array(); } elseif (!is_array($parameters)) { $parameters = array($parameters); } $this->paramNb = 0; $this->params = & $parameters; $query = preg_replace_callback('/\?/', array($this, 'replaceParam'), $query); return $query; }
public function replaceParam($match) { $param = & $this->params[$this->paramNb]; $this->paramNb++; if ($param === null) { return 'NULL'; } else { return "'" . addslashes($param) . "'"; } }
public function isErrNo($e, $errno) { return \Piwik\Db\Adapter\Mysqli::isMysqliErrorNumber($e, $this->connection, $errno); }
/** * Return number of affected rows in last query * * @param mixed $queryResult Result from query() * @return int */ public function rowCount($queryResult) { if (!empty($queryResult) && is_object($queryResult) && $queryResult instanceof \mysqli_stmt) { return $queryResult->affected_rows; } return mysqli_affected_rows($this->connection); }
/** * Start Transaction * @return ?string TransactionID */ public function beginTransaction() { if ($this->activeTransaction !== null) { return null; }
if ($this->connection->autocommit(false)) { $this->activeTransaction = uniqid(); return $this->activeTransaction; }
return null; }
/** * Commit Transaction * @param $xid */ public function commit($xid) { if ($this->activeTransaction != $xid || $this->activeTransaction === null) { return; }
$this->activeTransaction = null;
if (!$this->connection->commit()) { throw new DbException("Commit failed"); }
$this->connection->autocommit(true); }
/** * Rollback Transaction * @param $xid */ public function rollBack($xid) { if ($this->activeTransaction != $xid || $this->activeTransaction === null) { return; }
$this->activeTransaction = null;
if (!$this->connection->rollback()) { throw new DbException("Rollback failed"); }
$this->connection->autocommit(true); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438<?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\Db\Pdo;
use Exception;use PDO;use PDOException;use PDOStatement;use Piwik\Tracker\Db;use Piwik\Tracker\Db\DbException;
/** * PDO MySQL wrapper * */class Mysql extends Db{ /** * @var PDO|null */ protected $connection = null;
/** * @var string */ protected $dsn;
/** * @var string */ private $username;
/** * @var string */ private $password;
/** * @var string|null */ protected $charset;
/** * @var string|null */ private $collation;
protected $mysqlOptions = [];
protected $activeTransaction = null;
/** * Builds the DB object * * @param array $dbInfo * @param string $driverName */ public function __construct($dbInfo, $driverName = 'mysql') { if (isset($dbInfo['unix_socket']) && substr($dbInfo['unix_socket'], 0, 1) == '/') { $this->dsn = $driverName . ':dbname=' . $dbInfo['dbname'] . ';unix_socket=' . $dbInfo['unix_socket']; } elseif (!empty($dbInfo['port']) && substr($dbInfo['port'], 0, 1) == '/') { $this->dsn = $driverName . ':dbname=' . $dbInfo['dbname'] . ';unix_socket=' . $dbInfo['port']; } else { $this->dsn = $driverName . ':dbname=' . $dbInfo['dbname'] . ';host=' . $dbInfo['host'] . ';port=' . $dbInfo['port']; }
$this->username = $dbInfo['username']; $this->password = $dbInfo['password'];
if (isset($dbInfo['charset'])) { $this->charset = $dbInfo['charset']; $this->dsn .= ';charset=' . $this->charset;
if (!empty($dbInfo['collation'])) { $this->collation = $dbInfo['collation']; } }
if (isset($dbInfo['enable_ssl']) && $dbInfo['enable_ssl']) { if (!empty($dbInfo['ssl_key'])) { $this->mysqlOptions[PDO::MYSQL_ATTR_SSL_KEY] = $dbInfo['ssl_key']; } if (!empty($dbInfo['ssl_cert'])) { $this->mysqlOptions[PDO::MYSQL_ATTR_SSL_CERT] = $dbInfo['ssl_cert']; } if (!empty($dbInfo['ssl_ca'])) { $this->mysqlOptions[PDO::MYSQL_ATTR_SSL_CA] = $dbInfo['ssl_ca']; } if (!empty($dbInfo['ssl_ca_path'])) { $this->mysqlOptions[PDO::MYSQL_ATTR_SSL_CAPATH] = $dbInfo['ssl_ca_path']; } if (!empty($dbInfo['ssl_cipher'])) { $this->mysqlOptions[PDO::MYSQL_ATTR_SSL_CIPHER] = $dbInfo['ssl_cipher']; } if (!empty($dbInfo['ssl_no_verify']) && defined('PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT')) { $this->mysqlOptions[PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT] = false; } } }
public function __destruct() { $this->connection = null; }
/** * Connects to the DB * * @throws Exception if there was an error connecting the DB */ public function connect() { if (self::$profiling) { $timer = $this->initProfiler(); }
// Make sure MySQL returns all matched rows on update queries including // rows that actually didn't have to be updated because the values didn't // change. This matches common behaviour among other database systems. // See #6296 why this is important in tracker $this->mysqlOptions[PDO::MYSQL_ATTR_FOUND_ROWS] = true; $this->mysqlOptions[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
try { $this->establishConnection(); } catch (Exception $e) { if ($this->isMysqlServerHasGoneAwayError($e)) { // mysql may return a MySQL server has gone away error when trying to establish the connection. // in that case we want to retry establishing the connection once after a short sleep $this->reconnect($e); } else { throw $e; } }
if (self::$profiling && isset($timer)) { $this->recordQueryProfile('connect', $timer); } }
/** * @internal tests only * @return bool */ public function isMysqlServerHasGoneAwayError(Exception $e) { return $this->isErrNo($e, \Piwik\Updater\Migration\Db::ERROR_CODE_MYSQL_SERVER_HAS_GONE_AWAY) || stripos($e->getMessage(), 'MySQL server has gone away') !== false; }
/** * Disconnects from the server */ public function disconnect() { $this->connection = null; }
/** * Returns an array containing all the rows of a query result, using optional bound parameters. * * @param string $query Query * @param array $parameters Parameters to bind * @return array|bool * @see query() * @throws Exception|DbException if an exception occurred */ public function fetchAll($query, $parameters = array()) { try { $sth = $this->query($query, $parameters); if ($sth === false) { return false; } return $sth->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $e) { throw new DbException("Error query: " . $e->getMessage()); } }
/** * Fetches the first column of all SQL result rows as an array. * * @param string $sql An SQL SELECT statement. * @param mixed $bind Data to bind into SELECT placeholders. * @return array|false */ public function fetchCol($sql, $bind = array()) { try { $sth = $this->query($sql, $bind); if ($sth === false) { return false; } $result = $sth->fetchAll(PDO::FETCH_COLUMN, 0); return $result; } catch (PDOException $e) { throw new DbException("Error query: " . $e->getMessage()); } }
/** * Returns the first row of a query result, using optional bound parameters. * * @param string $query Query * @param array $parameters Parameters to bind * @return bool|mixed * @see query() * @throws Exception|DbException if an exception occurred */ public function fetch($query, $parameters = array()) { try { $sth = $this->query($query, $parameters); if ($sth === false) { return false; } return $sth->fetch(PDO::FETCH_ASSOC); } catch (PDOException $e) { throw new DbException("Error query: " . $e->getMessage()); } }
/** * Executes a query, using optional bound parameters. * * @param string $query Query * @param array|string $parameters Parameters to bind array('idsite'=> 1) * @return PDOStatement|bool PDOStatement or false if failed * @throws DbException if an exception occurred */ public function query($query, $parameters = array()) { try { return $this->executeQuery($query, $parameters); } catch (Exception $e) { $isSelectQuery = stripos(trim($query), 'select ') === 0;
if ( $isSelectQuery && null === $this->activeTransaction && $this->isMysqlServerHasGoneAwayError($e) ) { // mysql may return a MySQL server has gone away error when trying to execute the query // in that case we want to retry establishing the connection once after a short sleep // we're only retrying SELECT queries to prevent updating or inserting records twice for some reason // when transactions are used, then we just want it to fail as we'd be only writing partial data $this->reconnect($e); return $this->executeQuery($query, $parameters); } else { $message = $e->getMessage() . " In query: $query Parameters: " . var_export($parameters, true); throw new DbException("Error query: " . $message, (int) $e->getCode()); } } }
/** * @internal for tests only * @throws Exception */ public function reconnect(Exception $e) { $this->disconnect(); usleep(100 * 1000); // wait for 100ms try { $this->establishConnection(); } catch (Exception $exceptionReconnect) { // forward the original exception so we get a better stack trace of where this error happens // and what happened originally throw $e; } }
/** * Executes a query, using optional bound parameters. * * @param string $query Query * @param array|string $parameters Parameters to bind array('idsite'=> 1) * @return PDOStatement|bool PDOStatement or false if failed * @throws DbException if an exception occurred */ private function executeQuery($query, $parameters = array()) { if (is_null($this->connection)) { return false; }
try { if (self::$profiling) { $timer = $this->initProfiler(); }
if (!is_array($parameters)) { $parameters = array($parameters); } $sth = $this->connection->prepare($query); $sth->execute($parameters);
if (self::$profiling && isset($timer)) { $this->recordQueryProfile($query, $timer); } return $sth; } catch (PDOException $e) { $message = $e->getMessage() . " In query: $query Parameters: " . var_export($parameters, true); throw new DbException("Error query: " . $message, (int) $e->getCode()); } }
/** * Returns the last inserted ID in the DB * Wrapper of PDO::lastInsertId() * * @return int */ public function lastInsertId() { return $this->connection->lastInsertId(); }
/** * Test error number * * @param Exception $e * @param string $errno * @return bool */ public function isErrNo($e, $errno) { return \Piwik\Db\Adapter\Pdo\Mysql::isPdoErrorNumber($e, $errno); }
/** * Return number of affected rows in last query * * @param mixed $queryResult Result from query() * @return int */ public function rowCount($queryResult) { return $queryResult->rowCount(); }
/** * Start Transaction * @return ?string TransactionID */ public function beginTransaction() { if ($this->activeTransaction !== null) { return null; }
try { $success = $this->connection->beginTransaction(); } catch (Exception $e) { if ($this->isMysqlServerHasGoneAwayError($e)) { // mysql may return a MySQL server has gone away error when trying begin transaction, in that case we // want to retry this once $this->reconnect($e); $success = $this->connection->beginTransaction(); } else { throw $e; } }
if ($success) { $this->activeTransaction = uniqid(); return $this->activeTransaction; }
return null; }
/** * Commit Transaction * @param $xid */ public function commit($xid) { if ($this->activeTransaction != $xid || $this->activeTransaction === null) { return; }
$this->activeTransaction = null;
if (!$this->connection->commit()) { throw new DbException("Commit failed"); } }
/** * Rollback Transaction * @param $xid */ public function rollBack($xid) { if ($this->activeTransaction != $xid || $this->activeTransaction === null) { return; }
$this->activeTransaction = null;
if (!$this->connection->rollBack()) { throw new DbException("Rollback failed"); } }
private function establishConnection(): void { $this->connection = @new PDO($this->dsn, $this->username, $this->password, $this->mysqlOptions);
// we may want to setAttribute(PDO::ATTR_TIMEOUT ) to a few seconds (default is 60) in case the DB is locked // the matomo.php would stay waiting for the database... bad!
/* * Lazy initialization via MYSQL_ATTR_INIT_COMMAND depends * on mysqlnd support, PHP version, and OS. * see ZF-7428 and https://bugs.php.net/bug.php?id=47224 */ if (!empty($this->charset)) { $sql = "SET NAMES '" . $this->charset . "'";
if (!empty($this->collation)) { $sql .= " COLLATE '" . $this->collation . "'"; }
$this->connection->exec($sql); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200<?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\Common;use Piwik\Date;use Piwik\Exception\InvalidRequestParameterException;use Piwik\Exception\UnexpectedWebsiteFoundException;use Piwik\Piwik;use Piwik\Site;use Piwik\Db as PiwikDb;use Piwik\Url;
class Failures{ public const CLEANUP_OLD_FAILURES_DAYS = 2; public const FAILURE_ID_INVALID_SITE = 1; public const FAILURE_ID_NOT_AUTHENTICATED = 2;
private $table = 'tracking_failure'; private $tablePrefixed; private $now;
public function __construct() { $this->tablePrefixed = Common::prefixTable($this->table); }
public function setNow(Date $now) { $this->now = $now; }
private function getNow() { if (isset($this->now)) { return $this->now; } return Date::now(); }
public function logFailure($idFailure, Request $request) { $isVisitExcluded = $request->getMetadata('CoreHome', 'isVisitExcluded');
if ($isVisitExcluded === null) { try { $visitExcluded = new VisitExcluded($request); $isVisitExcluded = $visitExcluded->isExcluded(); } catch (InvalidRequestParameterException $e) { // we ignore this error and assume visit is not excluded... happens eg when using `cip` and request was // not authenticated... $isVisitExcluded = false; } }
if ($isVisitExcluded) { return; }
$idSite = (int) $request->getIdSiteUnverified(); $idFailure = (int) $idFailure;
if ($idSite > 9999999 || $idSite < 0 || $this->hasLoggedFailure($idSite, $idFailure)) { return; // we prevent creating huge amount of entries in the cache }
$params = $this->getParamsWithTokenAnonymized($request); $sql = sprintf('INSERT INTO `%s` (`idsite`, `idfailure`, `date_first_occurred`, `request_url`) VALUES(?,?,?,?) ON DUPLICATE KEY UPDATE idsite=idsite;', $this->tablePrefixed);
PiwikDb::get()->query($sql, array($idSite, $idFailure, $this->getNow()->getDatetime(), http_build_query($params))); }
private function hasLoggedFailure($idSite, $idFailure) { $sql = sprintf('SELECT idsite FROM `%s` WHERE idsite = ? and idfailure = ?', $this->tablePrefixed); $row = PiwikDb::fetchRow($sql, array($idSite, $idFailure));
return !empty($row); }
private function getParamsWithTokenAnonymized(Request $request) { // eg if there is a typo in the token auth we want to replace it as well to not accidentally leak a token // eg imagine a super user tries to issue an API request for a site and sending the wrong parameter for a token... // an admin may have view access for this and can see the super users token $token = $request->getTokenAuth(); $params = $request->getRawParams(); foreach (array('token_auth', 'token', 'tokenauth', 'token__auth') as $key) { if (isset($params[$key])) { $params[$key] = '__TOKEN_AUTH__'; } } foreach ($params as $key => $value) { if (!empty($token) && $value === $token) { $params[$key] = '__TOKEN_AUTH__'; // user accidentally posted the token in a wrong field } elseif ( !empty($value) && is_string($value) && mb_strlen($value) >= 29 && mb_strlen($value) <= 36 && ctype_xdigit($value) ) { $params[$key] = '__TOKEN_AUTH__'; // user maybe posted a token in a different field... it looks like it might be a token } }
return $params; }
public function removeFailuresOlderThanDays($days) { $minutesAgo = $this->getNow()->subDay($days)->getDatetime();
PiwikDb::query(sprintf('DELETE FROM `%s` WHERE date_first_occurred < ?', $this->tablePrefixed), [$minutesAgo]); }
public function getAllFailures() { $failures = PiwikDb::fetchAll(sprintf('SELECT * FROM `%s`', $this->tablePrefixed)); return $this->enrichFailures($failures); }
public function getFailuresForSites($idSites) { if (empty($idSites)) { return array(); } $idSites = array_map('intval', $idSites); $idSites = implode(',', $idSites); $failures = PiwikDb::fetchAll(sprintf('SELECT * FROM `%s` WHERE idsite IN (%s)', $this->tablePrefixed, $idSites)); return $this->enrichFailures($failures); }
public function deleteTrackingFailure($idSite, $idFailure) { PiwikDb::query(sprintf('DELETE FROM `%s` WHERE idsite = ? and idfailure = ?', $this->tablePrefixed), [$idSite, $idFailure]); }
public function deleteTrackingFailures($idSites) { if (!empty($idSites)) { $idSites = array_map('intval', $idSites); $idSites = implode(',', $idSites); PiwikDb::query(sprintf('DELETE FROM `%s` WHERE idsite IN(%s)', $this->tablePrefixed, $idSites)); } }
public function deleteAllTrackingFailures() { PiwikDb::query(sprintf('DELETE FROM `%s`', $this->tablePrefixed)); }
private function enrichFailures($failures) { foreach ($failures as &$failure) { try { $failure['site_name'] = Site::getNameFor($failure['idsite']); } catch (UnexpectedWebsiteFoundException $e) { $failure['site_name'] = Piwik::translate('General_Unknown'); } $failure['pretty_date_first_occurred'] = Date::factory($failure['date_first_occurred'])->getLocalized(Date::DATETIME_FORMAT_SHORT); parse_str($failure['request_url'], $params); if (empty($params['url'])) { $params['url'] = ' ';// workaround it using the default provider in request constructor } $request = new Request($params); $failure['url'] = trim($request->getParam('url')); $failure['problem'] = ''; $failure['solution'] = ''; $failure['solution_url'] = '';
switch ($failure['idfailure']) { case self::FAILURE_ID_INVALID_SITE: $failure['problem'] = Piwik::translate('CoreAdminHome_TrackingFailureInvalidSiteProblem'); $failure['solution'] = Piwik::translate('CoreAdminHome_TrackingFailureInvalidSiteSolution'); $failure['solution_url'] = Url::addCampaignParametersToMatomoLink('https://matomo.org/faq/how-to/faq_30838/'); break; case self::FAILURE_ID_NOT_AUTHENTICATED: $failure['problem'] = Piwik::translate('CoreAdminHome_TrackingFailureAuthenticationProblem'); $failure['solution'] = Piwik::translate('CoreAdminHome_TrackingFailureAuthenticationSolution'); $failure['solution_url'] = Url::addCampaignParametersToMatomoLink('https://matomo.org/faq/how-to/faq_30835/'); break; } }
/** * @ignore * internal use only */ Piwik::postEvent('Tracking.makeFailuresHumanReadable', array(&$failures));
return $failures; }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182<?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\Common;use Piwik\Date;use Piwik\Option;
class FingerprintSalt{ public const OPTION_PREFIX = 'fingerprint_salt_'; public const DELETE_FINGERPRINT_OLDER_THAN_SECONDS = 432000; // 5 days in seconds
public function generateSalt() { return Common::getRandomString(32); }
public function deleteOldSalts() { // we want to make sure to delete salts that were created more than five days ago as they are likely not in // use anymore. We should delete them to ensure the fingerprint is truly random for each day because if we used // eg the regular salt then it would technically still be possible to try and regenerate the fingerprint based // on certain information. // Typically, only the salts for today and yesterday are used. However, if someone was to import historical data // for the same day and this takes more than five days, then it could technically happen that we delete a // fingerprint that is still in use now and as such after deletion a few visitors would have a new configId // within one visit and such a new visit would be created. That should be very much edge case though. $deleteSaltsCreatedBefore = Date::getNowTimestamp() - self::DELETE_FINGERPRINT_OLDER_THAN_SECONDS; $options = Option::getLike(self::OPTION_PREFIX . '%'); $deleted = array(); foreach ($options as $name => $value) { $value = $this->decode($value); if (empty($value['time']) || $value['time'] < $deleteSaltsCreatedBefore) { Option::delete($name); $deleted[] = $name; } }
return $deleted; }
public function getDateString(Date $date, $timezone) { $dateString = Date::factory($date->getTimestampUTC(), $timezone)->toString(); return $dateString; }
private function encode($value) { return json_encode($value); }
private function decode($value) { return @json_decode($value, true); }
public function getSalt($dateString, $idSite) { $fingerprintSaltKey = self::OPTION_PREFIX . (int) $idSite . '_' . $dateString; $salt = Option::get($fingerprintSaltKey); if (!empty($salt)) { $salt = $this->decode($salt); } if (empty($salt['value'])) { $salt = array( 'value' => $this->generateSalt(), 'time' => Date::getNowTimestamp(), ); Option::set($fingerprintSaltKey, $this->encode($salt)); } return $salt['value']; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002<?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 Exception;use Piwik\Common;use Piwik\Container\StaticContainer;use Piwik\Date;use Piwik\Exception\InvalidRequestParameterException;use Piwik\Log\LoggerInterface;use Piwik\Piwik;use Piwik\Plugin\Dimension\ConversionDimension;use Piwik\Plugin\Dimension\VisitDimension;use Piwik\Plugin\Manager;use Piwik\Plugins\CustomVariables\CustomVariables;use Piwik\Plugins\Events\Actions\ActionEvent;use Piwik\Tracker\Visit\VisitProperties;
class GoalManager{ // log_visit.visit_goal_buyer public const TYPE_BUYER_OPEN_CART = 2; public const TYPE_BUYER_ORDERED_AND_OPEN_CART = 3;
// log_conversion.idorder is NULLable, but not log_conversion_item which defaults to zero for carts public const ITEM_IDORDER_ABANDONED_CART = 0;
// log_conversion.idgoal special values public const IDGOAL_CART = -1; public const IDGOAL_ORDER = 0;
public const REVENUE_PRECISION = 2;
/** * Upper sanity limit for a single tracked ecommerce money value (item price, order * revenue, tax, shipping, discount, subtotal). Values whose absolute value exceeds * this are rejected at tracking time. * * No legitimate single transaction is this large, and such values corrupt revenue * reports. Rejecting them also removes the archiving overflow vector: quantity is * bounded by its INT UNSIGNED column (<= ~4.29e9), so quantity * price can no longer * exceed the MySQL DOUBLE range and abort archiving with error 1690. */ public const MAX_ALLOWED_REVENUE = 1000000000000;
public const MAXIMUM_PRODUCT_CATEGORIES = 5;
// In the GET items parameter, each item has the following array of information public const INDEX_ITEM_SKU = 0; public const INDEX_ITEM_NAME = 1; public const INDEX_ITEM_CATEGORY = 2; public const INDEX_ITEM_PRICE = 3; public const INDEX_ITEM_QUANTITY = 4;
// Used in the array of items, internally to this class public const INTERNAL_ITEM_SKU = 0; public const INTERNAL_ITEM_NAME = 1; public const INTERNAL_ITEM_CATEGORY = 2; public const INTERNAL_ITEM_CATEGORY2 = 3; public const INTERNAL_ITEM_CATEGORY3 = 4; public const INTERNAL_ITEM_CATEGORY4 = 5; public const INTERNAL_ITEM_CATEGORY5 = 6; public const INTERNAL_ITEM_PRICE = 7; public const INTERNAL_ITEM_QUANTITY = 8;
public static $NUMERIC_MATCH_ATTRIBUTES = [ 'visit_duration', ];
/** * TODO: should remove this, but it is used by getGoalColumn which is used by dimensions. should replace w/ value object. * * @var array */ private $currentGoal = array();
public function detectIsThereExistingCartInVisit($visitInformation) { if (empty($visitInformation['visit_goal_buyer'])) { return false; }
$goalBuyer = $visitInformation['visit_goal_buyer']; $types = array(GoalManager::TYPE_BUYER_OPEN_CART, GoalManager::TYPE_BUYER_ORDERED_AND_OPEN_CART);
// Was there a Cart for this visit prior to the order? return in_array($goalBuyer, $types); }
public static function getGoalDefinitions($idSite) { $websiteAttributes = Cache::getCacheWebsiteAttributes($idSite);
if (isset($websiteAttributes['goals'])) { return $websiteAttributes['goals']; }
return array(); }
public static function getGoalDefinition($idSite, $idGoal) { $goals = self::getGoalDefinitions($idSite);
foreach ($goals as $goal) { if ($goal['idgoal'] == $idGoal) { return $goal; } }
throw new Exception('Goal not found'); }
public static function getGoalIds($idSite) { $goals = self::getGoalDefinitions($idSite); $goalIds = array();
foreach ($goals as $goal) { $goalIds[] = $goal['idgoal']; }
return $goalIds; }
/** * Look at the URL or Page Title and sees if it matches any existing Goal definition * * @param int $idSite * @param Action $action * @throws Exception * @return array[] Goals matched */ public function detectGoalsMatchingUrl($idSite, $action, VisitProperties $visitor, Request $request) { if (!Common::isGoalPluginEnabled()) { return array(); }
$goals = $this->getGoalDefinitions($idSite);
$convertedGoals = array(); foreach ($goals as $goal) { $convertedUrl = $this->detectGoalMatch($goal, $action, $visitor, $request); if (!is_null($convertedUrl)) { $convertedGoals[] = array('url' => $convertedUrl) + $goal; } } return $convertedGoals; }
/** * Detects if an Action matches a given goal. If it does, the URL that triggered the goal * is returned. Otherwise null is returned. * * @param array $goal * @return string|null The Action URL that triggered the goal, or null if no goal was matched */ public function detectGoalMatch($goal, Action $action, VisitProperties $visitor, Request $request) { $actionType = $action->getActionType();
$attribute = $goal['match_attribute'];
// handle numeric match attributes specifically if (in_array($attribute, self::$NUMERIC_MATCH_ATTRIBUTES)) { return $this->detectNumericGoalMatch($goal, $action, $visitor, $request); }
// if the attribute to match is not the type of the current action if ( (($attribute == 'url' || $attribute == 'title') && $actionType != Action::TYPE_PAGE_URL) || ($attribute == 'file' && $actionType != Action::TYPE_DOWNLOAD) || ($attribute == 'external_website' && $actionType != Action::TYPE_OUTLINK) || ($attribute == 'manually') || self::isEventMatchingGoal($goal) && $actionType != Action::TYPE_EVENT ) { return null; }
switch ($attribute) { case 'title': // Matching on Page Title $actionToMatch = $action->getActionName(); break; case 'event_action': $actionToMatch = $action->getEventAction(); break; case 'event_name': $actionToMatch = $action->getEventName(); break; case 'event_category': $actionToMatch = $action->getEventCategory(); break; // url, external_website, file, manually... default: $actionToMatch = $action->getActionUrlRaw(); break; }
$pattern_type = $goal['pattern_type'];
$match = $this->isUrlMatchingGoal($goal, $pattern_type, $actionToMatch); if (!$match) { return null; }
return $action->getActionUrl(); }
private function detectNumericGoalMatch($goal, Action $action, VisitProperties $visitProperties, Request $request) { switch ($goal['match_attribute']) { case 'visit_duration': $firstActionTime = $visitProperties->getProperty('visit_first_action_time'); if (empty($firstActionTime)) { return null; }
$visitDurationInSecs = $request->getCurrentTimestamp() - ((int) $firstActionTime); $valueToMatchAgainst = $visitDurationInSecs / 60; break; default: return null; }
$pattern = (float) $goal['pattern'];
Common::printDebug("Matching {$goal['match_attribute']} (current value = $valueToMatchAgainst, idGoal = {$goal['idgoal']}) {$goal['pattern_type']} $pattern.");
switch ($goal['pattern_type']) { case 'greater_than': $matches = $valueToMatchAgainst > $pattern; break; default: return null; }
if ($matches) { Common::printDebug("Conversion detected for idGoal = , idGoal = {$goal['idgoal']}."); return $action->getActionUrl(); } else { return null; } }
public function detectGoalId($idSite, Request $request) { if (!Common::isGoalPluginEnabled()) { return null; }
$idGoal = $request->getParam('idgoal');
$goals = $this->getGoalDefinitions($idSite);
if (!isset($goals[$idGoal])) { throw new InvalidRequestParameterException('idGoal ' . $idGoal . ' does not exist'); }
$goal = $goals[$idGoal];
$url = $request->getParam('url'); $goal['url'] = PageUrl::excludeQueryParametersFromUrl($url, $idSite); return $goal; }
/** * Records one or several goals matched in this request. */ public function recordGoals(VisitProperties $visitProperties, Request $request) { $visitorInformation = $visitProperties->getProperties();
/** @var Action $action */ $action = $request->getMetadata('Actions', 'action');
$goal = $this->getGoalFromVisitor($visitProperties, $request, $action);
if (Manager::getInstance()->isPluginActivated('CustomVariables')) { // @todo move this to CustomVariables plugin if possible // Copy Custom Variables from Visit row to the Goal conversion // Otherwise, set the Custom Variables found in the cookie sent with this request $visitCustomVariables = $request->getMetadata('CustomVariables', 'visitCustomVariables') ?: array(); $goal += $visitCustomVariables; $maxCustomVariables = CustomVariables::getNumUsableCustomVariables();
for ($i = 1; $i <= $maxCustomVariables; $i++) { if ( isset($visitorInformation['custom_var_k' . $i]) && strlen($visitorInformation['custom_var_k' . $i]) ) { $goal['custom_var_k' . $i] = $visitorInformation['custom_var_k' . $i]; } if ( isset($visitorInformation['custom_var_v' . $i]) && strlen($visitorInformation['custom_var_v' . $i]) ) { $goal['custom_var_v' . $i] = $visitorInformation['custom_var_v' . $i]; } } }
// some goals are converted, so must be ecommerce Order or Cart Update $isRequestEcommerce = $request->getMetadata('Ecommerce', 'isRequestEcommerce'); if ($isRequestEcommerce) { $this->recordEcommerceGoal($visitProperties, $request, $goal, $action); } else { $this->recordStandardGoals($visitProperties, $request, $goal, $action); } }
/** * Returns rounded decimal revenue, or if revenue is integer, then returns as is. * * @param int|float $revenue * @return int|float */ protected function getRevenue($revenue) { // Reject out-of-range values (see self::MAX_ALLOWED_REVENUE); treat as no revenue. if (abs((float) $revenue) > self::MAX_ALLOWED_REVENUE) { StaticContainer::get(LoggerInterface::class)->debug( "Ecommerce value ({$revenue}) exceeds the allowed maximum of " . self::MAX_ALLOWED_REVENUE . " and was rejected (treated as no revenue)." );
return 0; }
if (round($revenue) != $revenue) { $revenue = round($revenue, self::REVENUE_PRECISION); }
$revenue = Common::forceDotAsSeparatorForDecimalPoint($revenue);
return $revenue; }
/** * Records an Ecommerce conversion in the DB. Deals with Items found in the request. * Will deal with 2 types of conversions: Ecommerce Order and Ecommerce Cart update (Add to cart, Update Cart etc). * * @param array $conversion * @param Action|null $action */ protected function recordEcommerceGoal(VisitProperties $visitProperties, Request $request, $conversion, $action) { $isThereExistingCartInVisit = $request->getMetadata('Goals', 'isThereExistingCartInVisit'); if ($isThereExistingCartInVisit) { Common::printDebug("There is an existing cart for this visit"); }
$visitor = Visitor::makeFromVisitProperties($visitProperties, $request);
$isGoalAnOrder = $request->getMetadata('Ecommerce', 'isGoalAnOrder'); if ($isGoalAnOrder) { $debugMessage = 'The conversion is an Ecommerce order';
$orderId = $request->getParam('ec_id');
$conversion['idorder'] = $orderId; $conversion['idgoal'] = self::IDGOAL_ORDER; $conversion['buster'] = Common::hashStringToInt($orderId);
$conversionDimensions = ConversionDimension::getAllDimensions(); $conversion = $this->triggerHookOnDimensions($request, $conversionDimensions, 'onEcommerceOrderConversion', $visitor, $action, $conversion); } else { // If Cart update, select current items in the previous Cart $debugMessage = 'The conversion is an Ecommerce Cart Update';
$conversion['buster'] = 0; $conversion['idgoal'] = self::IDGOAL_CART;
$conversionDimensions = ConversionDimension::getAllDimensions(); $conversion = $this->triggerHookOnDimensions($request, $conversionDimensions, 'onEcommerceCartUpdateConversion', $visitor, $action, $conversion); }
Common::printDebug($debugMessage . ':' . var_export($conversion, true));
// INSERT or Sync items in the Cart / Order for this visit & order $items = $this->getEcommerceItemsFromRequest($request);
if (false === $items) { return; }
$itemsCount = 0; foreach ($items as $item) { $itemsCount += $item[GoalManager::INTERNAL_ITEM_QUANTITY]; }
$conversion['items'] = $itemsCount;
if ($isThereExistingCartInVisit) { $recorded = $this->getModel()->updateConversion( $visitProperties->getProperty('idvisit'), self::IDGOAL_CART, $conversion ); } else { $recorded = $this->insertNewConversion($conversion, $visitProperties->getProperties(), $request, $action); }
if ($recorded) { $this->recordEcommerceItems($conversion, $items); } }
/** * Returns Items read from the request string * @return array|bool */ private function getEcommerceItemsFromRequest(Request $request) { $items = $request->getParam('ec_items');
if (empty($items)) { Common::printDebug("There are no Ecommerce items in the request"); // we still record an Ecommerce order without any item in it return array(); }
if (!is_array($items)) { Common::printDebug("Error while json_decode the Ecommerce items = " . var_export($items, true)); return false; }
$items = Common::unsanitizeInputValues($items);
$cleanedItems = $this->getCleanedEcommerceItems($items); return $cleanedItems; }
/** * Loads the Ecommerce items from the request and records them in the DB * * @param array $goal * @param array $items * @throws Exception */ protected function recordEcommerceItems($goal, $items) { $itemInCartBySku = array(); foreach ($items as $item) { $itemInCartBySku[$item[0]] = $item; }
$itemsInDb = $this->getModel()->getAllItemsCurrentlyInTheCart($goal, self::ITEM_IDORDER_ABANDONED_CART);
// Look at which items need to be deleted, which need to be added or updated, based on the SKU $skuFoundInDb = $itemsToUpdate = array();
foreach ($itemsInDb as $itemInDb) { $skuFoundInDb[] = $itemInDb['idaction_sku'];
// Ensure price comparisons will have the same assumption $itemInDb['price'] = $this->getRevenue($itemInDb['price']); $itemInDbOriginal = $itemInDb; $itemInDb = array_values($itemInDb);
// Cast all as string, because what comes out of the fetchAll() are strings $itemInDb = $this->getItemRowCast($itemInDb);
//Item in the cart in the DB, but not anymore in the cart if (!isset($itemInCartBySku[$itemInDb[0]])) { $itemToUpdate = array_merge( $itemInDb, array('deleted' => 1, 'idorder_original_value' => $itemInDbOriginal['idorder_original_value'], ) );
$itemsToUpdate[] = $itemToUpdate; Common::printDebug("Item found in the previous Cart, but no in the current cart/order"); Common::printDebug($itemToUpdate); continue; }
$newItem = $itemInCartBySku[$itemInDb[0]]; $newItem = $this->getItemRowCast($newItem);
if (count($itemInDb) != count($newItem)) { Common::printDebug("ERROR: Different format in items from cart and DB"); throw new Exception(" Item in DB and Item in cart have a different format, this is not expected... " . var_export($itemInDb, true) . var_export($newItem, true)); } Common::printDebug("Item has changed since the last cart. Previous item stored in cart in database:"); Common::printDebug($itemInDb); Common::printDebug("New item to UPDATE the previous row:"); $newItem['idorder_original_value'] = $itemInDbOriginal['idorder_original_value']; Common::printDebug($newItem); $itemsToUpdate[] = $newItem; }
// Items to UPDATE $this->updateEcommerceItems($goal, $itemsToUpdate);
// Items to INSERT $itemsToInsert = array(); foreach ($items as $item) { if (!in_array($item[0], $skuFoundInDb)) { $itemsToInsert[] = $item; } }
$this->insertEcommerceItems($goal, $itemsToInsert); }
/** * Reads items from the request, then looks up the names from the lookup table * and returns a clean array of items ready for the database. * * @param array $items * @return array $cleanedItems */ private function getCleanedEcommerceItems($items) { // Clean up the items array $cleanedItems = array(); foreach ($items as $item) { $name = $category = $category2 = $category3 = $category4 = $category5 = false; $price = 0; $quantity = 1;
// items are passed in the request as an array: ( $sku, $name, $category, $price, $quantity ) if (empty($item[self::INDEX_ITEM_SKU])) { continue; }
$sku = $item[self::INDEX_ITEM_SKU]; if (!empty($item[self::INDEX_ITEM_NAME])) { $name = $item[self::INDEX_ITEM_NAME]; }
if (!empty($item[self::INDEX_ITEM_CATEGORY])) { $category = $item[self::INDEX_ITEM_CATEGORY]; }
if ( isset($item[self::INDEX_ITEM_PRICE]) && is_numeric($item[self::INDEX_ITEM_PRICE]) ) { $price = $this->getRevenue($item[self::INDEX_ITEM_PRICE]); } if ( !empty($item[self::INDEX_ITEM_QUANTITY]) && is_numeric($item[self::INDEX_ITEM_QUANTITY]) ) { $quantity = (int)$item[self::INDEX_ITEM_QUANTITY]; }
// self::INDEX_ITEM_* are in order $cleanedItems[] = array( self::INTERNAL_ITEM_SKU => $sku, self::INTERNAL_ITEM_NAME => $name, self::INTERNAL_ITEM_CATEGORY => $category, self::INTERNAL_ITEM_CATEGORY2 => $category2, self::INTERNAL_ITEM_CATEGORY3 => $category3, self::INTERNAL_ITEM_CATEGORY4 => $category4, self::INTERNAL_ITEM_CATEGORY5 => $category5, self::INTERNAL_ITEM_PRICE => $price, self::INTERNAL_ITEM_QUANTITY => $quantity, ); }
// Lookup Item SKUs, Names & Categories Ids $actionsToLookupAllItems = array();
// Each item has 7 potential "ids" to lookup in the lookup table $columnsInEachRow = 1 + 1 + self::MAXIMUM_PRODUCT_CATEGORIES;
foreach ($cleanedItems as $item) { $actionsToLookup = array(); [$sku_check, $name_check, $category, $price, $quantity] = $item; $sku = is_array($sku_check) ? join(',', $sku_check) : $sku_check; $actionsToLookup[] = array(trim($sku), Action::TYPE_ECOMMERCE_ITEM_SKU); $name = is_array($name_check) ? join(',', $name_check) : $name_check; $actionsToLookup[] = array(trim($name), Action::TYPE_ECOMMERCE_ITEM_NAME);
// Only one category if (!is_array($category)) { $actionsToLookup[] = array(trim($category), Action::TYPE_ECOMMERCE_ITEM_CATEGORY); } else { // Multiple categories $countCategories = 0; foreach ($category as $productCategory) { $productCategory = trim($productCategory); if (empty($productCategory)) { continue; } $countCategories++; if ($countCategories > self::MAXIMUM_PRODUCT_CATEGORIES) { break; } $actionsToLookup[] = array($productCategory, Action::TYPE_ECOMMERCE_ITEM_CATEGORY); } } // Ensure that each row has the same number of columns, fill in the blanks for ($i = count($actionsToLookup); $i < $columnsInEachRow; $i++) { $actionsToLookup[] = array(false, Action::TYPE_ECOMMERCE_ITEM_CATEGORY); } $actionsToLookupAllItems = array_merge($actionsToLookupAllItems, $actionsToLookup); }
$actionsLookedUp = TableLogAction::loadIdsAction($actionsToLookupAllItems);
// Replace SKU, name & category by their ID action foreach ($cleanedItems as $index => &$item) { // SKU $item[0] = $actionsLookedUp[$index * $columnsInEachRow + 0]; // Name $item[1] = $actionsLookedUp[$index * $columnsInEachRow + 1]; // Categories $item[2] = $actionsLookedUp[$index * $columnsInEachRow + 2]; $item[3] = $actionsLookedUp[$index * $columnsInEachRow + 3]; $item[4] = $actionsLookedUp[$index * $columnsInEachRow + 4]; $item[5] = $actionsLookedUp[$index * $columnsInEachRow + 5]; $item[6] = $actionsLookedUp[$index * $columnsInEachRow + 6]; }
return $cleanedItems; }
/** * Updates the cart items in the DB * that have been modified since the last cart update * * @param array $goal * @param array $itemsToUpdate * * @return void */ protected function updateEcommerceItems($goal, $itemsToUpdate) { if (empty($itemsToUpdate)) { return; }
Common::printDebug("Goal data used to update ecommerce items:"); Common::printDebug($goal);
foreach ($itemsToUpdate as $item) { $newRow = $this->getItemRowEnriched($goal, $item); Common::printDebug($newRow);
$this->getModel()->updateEcommerceItem($item['idorder_original_value'], $newRow); } }
private function getModel() { return new Model(); }
/** * Inserts in the cart in the DB the new items * that were not previously in the cart * * @param array $goal * @param array $itemsToInsert * * @return void */ protected function insertEcommerceItems($goal, $itemsToInsert) { if (empty($itemsToInsert)) { return; }
Common::printDebug("Ecommerce items that are added to the cart/order"); Common::printDebug($itemsToInsert);
$items = array();
foreach ($itemsToInsert as $item) { $items[] = $this->getItemRowEnriched($goal, $item); }
$this->getModel()->createEcommerceItems($items); }
protected function getItemRowEnriched($goal, $item) { $newRow = array( 'idaction_sku' => (int)$item[self::INTERNAL_ITEM_SKU], 'idaction_name' => (int)$item[self::INTERNAL_ITEM_NAME], 'idaction_category' => (int)$item[self::INTERNAL_ITEM_CATEGORY], 'idaction_category2' => (int)$item[self::INTERNAL_ITEM_CATEGORY2], 'idaction_category3' => (int)$item[self::INTERNAL_ITEM_CATEGORY3], 'idaction_category4' => (int)$item[self::INTERNAL_ITEM_CATEGORY4], 'idaction_category5' => (int)$item[self::INTERNAL_ITEM_CATEGORY5], 'price' => Common::forceDotAsSeparatorForDecimalPoint($item[self::INTERNAL_ITEM_PRICE]), 'quantity' => $item[self::INTERNAL_ITEM_QUANTITY], 'deleted' => isset($item['deleted']) ? $item['deleted'] : 0, //deleted 'idorder' => isset($goal['idorder']) ? $goal['idorder'] : self::ITEM_IDORDER_ABANDONED_CART, //idorder = 0 in log_conversion_item for carts 'idsite' => $goal['idsite'], 'idvisitor' => $goal['idvisitor'], 'server_time' => $goal['server_time'], 'idvisit' => $goal['idvisit'], ); return $newRow; }
public function getGoalColumn($column) { if (array_key_exists($column, $this->currentGoal)) { return $this->currentGoal[$column]; }
return false; }
/** * Records a standard non-Ecommerce goal in the DB (URL/Title matching), * linking the conversion to the action that triggered it * @param array $goal * @param Action|null $action */ protected function recordStandardGoals(VisitProperties $visitProperties, Request $request, $goal, $action) { $visitor = Visitor::makeFromVisitProperties($visitProperties, $request);
$convertedGoals = $request->getMetadata('Goals', 'goalsConverted') ?: array(); foreach ($convertedGoals as $convertedGoal) { $this->currentGoal = $convertedGoal; Common::printDebug("- Goal " . $convertedGoal['idgoal'] . " matched. Recording..."); $conversion = $goal; $conversion['idgoal'] = $convertedGoal['idgoal']; $conversion['url'] = $convertedGoal['url'];
if (!is_null($action)) { $conversion['idaction_url'] = $action->getIdActionUrl(); $conversion['idlink_va'] = $action->getIdLinkVisitAction(); }
// If multiple Goal conversions per visit, set a cache buster if ($convertedGoal['allow_multiple'] == 0) { $conversion['buster'] = 0; } else { $lastActionTime = $visitProperties->getProperty('visit_last_action_time'); if (empty($lastActionTime)) { $conversion['buster'] = $this->makeRandomMySqlUnsignedInt(10); } else { $conversion['buster'] = $this->makeRandomMySqlUnsignedInt(2) . mb_substr($visitProperties->getProperty('visit_last_action_time'), 2); } }
$conversionDimensions = ConversionDimension::getAllDimensions(); $conversion = $this->triggerHookOnDimensions($request, $conversionDimensions, 'onGoalConversion', $visitor, $action, $conversion);
$this->insertNewConversion($conversion, $visitProperties->getProperties(), $request, $action, $convertedGoal); } }
private function makeRandomMySqlUnsignedInt($length) { // mysql int unsgined max value is 4294967295 so we want to allow max 39999... $randomInt = Common::getRandomString(1, '123'); $randomInt .= Common::getRandomString($length - 1, '0123456789'); return $randomInt; }
/** * Helper function used by other record* methods which will INSERT the conversion in the DB * * @param array $conversion * @param array $visitInformation * @param Action|null $action * @param array|null $convertedGoal * @return bool */ protected function insertNewConversion($conversion, $visitInformation, Request $request, $action, $convertedGoal = null) { /** * Triggered before persisting a new [conversion entity](/guides/persistence-and-the-mysql-backend#conversions). * * This event can be used to modify conversion information or to add new information to be persisted. * * This event is deprecated, use [Dimensions](https://developer.matomo.org/guides/dimensions) instead. * * @param array $conversion The conversion entity. Read [this](/guides/persistence-and-the-mysql-backend#conversions) * to see what it contains. * @param array $visitInformation The visit entity that we are tracking a conversion for. See what * information it contains [here](/guides/persistence-and-the-mysql-backend#visits). * @param \Piwik\Tracker\Request $request An object describing the tracking request being processed. * @param Action|null $action An action object like ActionPageView or ActionDownload, or null if no action is * supposed to be processed. * @deprecated * @ignore */ Piwik::postEvent('Tracker.newConversionInformation', array(&$conversion, $visitInformation, $request, $action));
if ( !empty($convertedGoal) && $this->isEventMatchingGoal($convertedGoal) && !empty($convertedGoal['event_value_as_revenue']) ) { $eventValue = ActionEvent::getEventValue($request); if ($eventValue != '') { $conversion['revenue'] = $eventValue; } }
$newGoalDebug = $conversion; $newGoalDebug['idvisitor'] = bin2hex($newGoalDebug['idvisitor']); Common::printDebug($newGoalDebug);
$idorder = $request->getParam('ec_id');
$wasInserted = $this->getModel()->createConversion($conversion); if ( !$wasInserted ) { if (!empty($idorder)) { $idSite = $request->getIdSite(); throw new InvalidRequestParameterException("Invalid non-unique idsite/idorder combination ($idSite, $idorder), conversion was not inserted."); } elseif ($conversion['buster'] > 0) { // Note: The buster is set to 0 for goals that can only be triggered once per visit. // It's expected behaviour that creating additional conversion fail, so we don't log failures in that case. StaticContainer::get(LoggerInterface::class)->warning("Failed to insert goal due to duplicate idvisit/idgoal/buster combination ({$conversion['idvisit']}, {$conversion['idgoal']}, {$conversion['buster']})"); } }
return $wasInserted; }
/** * Casts the item array so that array comparisons work nicely * @param array $row * @return array */ protected function getItemRowCast($row) { return array( (string)(int)$row[self::INTERNAL_ITEM_SKU], (string)(int)$row[self::INTERNAL_ITEM_NAME], (string)(int)$row[self::INTERNAL_ITEM_CATEGORY], (string)(int)$row[self::INTERNAL_ITEM_CATEGORY2], (string)(int)$row[self::INTERNAL_ITEM_CATEGORY3], (string)(int)$row[self::INTERNAL_ITEM_CATEGORY4], (string)(int)$row[self::INTERNAL_ITEM_CATEGORY5], (string)$row[self::INTERNAL_ITEM_PRICE], (string)$row[self::INTERNAL_ITEM_QUANTITY], ); }
/** * @param $goal * @param $pattern_type * @param $url * @return bool * @throws \Exception */ protected function isUrlMatchingGoal($goal, $pattern_type, $url) { $url = Common::unsanitizeInputValue($url); $goal['pattern'] = Common::unsanitizeInputValue($goal['pattern']);
$match = $this->isGoalPatternMatchingUrl($goal, $pattern_type, $url);
if (!$match) { // Users may set Goal matching URL as URL encoded $goal['pattern'] = urldecode($goal['pattern']);
$match = $this->isGoalPatternMatchingUrl($goal, $pattern_type, $url); } return $match; }
/** * @param ConversionDimension[] $dimensions * @param string $hook * @param Visitor $visitor * @param Action|null $action * @param array|null $valuesToUpdate * * @return array|null The updated $valuesToUpdate or null if no $valuesToUpdate given */ private function triggerHookOnDimensions(Request $request, $dimensions, $hook, $visitor, $action, $valuesToUpdate) { foreach ($dimensions as $dimension) { $value = $dimension->$hook($request, $visitor, $action, $this);
if (false !== $value) { if (is_float($value)) { $value = Common::forceDotAsSeparatorForDecimalPoint($value); }
$fieldName = $dimension->getColumnName(); $visitor->setVisitorColumn($fieldName, $value);
$valuesToUpdate[$fieldName] = $value; } }
return $valuesToUpdate; }
private function getGoalFromVisitor(VisitProperties $visitProperties, Request $request, $action) { $lastVisitTime = $visitProperties->getProperty('visit_last_action_time'); if (!$lastVisitTime) { $lastVisitTime = $request->getCurrentTimestamp(); // fallback in case visit_last_action_time is not set }
if (!empty($lastVisitTime) && is_numeric($lastVisitTime)) { // visit last action time might be 2020-05-05 00:00:00 // we want it to prevent this being converted to a timestamp of 2020 // resulting in some day in 1970 $lastVisitTime = Date::getDatetimeFromTimestamp($lastVisitTime); }
$goal = array( 'idvisit' => $visitProperties->getProperty('idvisit'), 'idvisitor' => $visitProperties->getProperty('idvisitor'), 'server_time' => $lastVisitTime, );
$visitDimensions = VisitDimension::getAllDimensions();
$visit = Visitor::makeFromVisitProperties($visitProperties, $request); foreach ($visitDimensions as $dimension) { $value = $dimension->onAnyGoalConversion($request, $visit, $action); if (false !== $value) { $goal[$dimension->getColumnName()] = $value; } }
return $goal; }
/** * @param $goal * @param $pattern_type * @param $url * @return bool */ protected function isGoalPatternMatchingUrl($goal, $pattern_type, $url) { switch ($pattern_type) { case 'regex': $pattern = self::formatRegex($goal['pattern']); if (!$goal['case_sensitive']) { $pattern .= 'i'; } $match = (@preg_match($pattern, $url) == 1); break; case 'contains': if ($goal['case_sensitive']) { $matched = strpos($url, $goal['pattern']); } else { $matched = stripos($url, $goal['pattern']); } $match = ($matched !== false); break; case 'exact': if ($goal['case_sensitive']) { $matched = strcmp($goal['pattern'], $url); } else { $matched = strcasecmp($goal['pattern'], $url); } $match = ($matched == 0); break; default: try { StaticContainer::get(LoggerInterface::class)->warning(Piwik::translate('General_ExceptionInvalidGoalPattern', array($pattern_type))); } catch (\Exception $e) { } $match = false; break; } return $match; }
/** * Formats a goal regex pattern to a usable regex * * @param string $pattern * @return string */ public static function formatRegex($pattern) { if ( strpos($pattern, '/') !== false && strpos($pattern, '\\/') === false ) { $pattern = str_replace('/', '\\/', $pattern); } return '/' . $pattern . '/'; }
public static function isEventMatchingGoal($goal) { return in_array($goal['match_attribute'], array('event_action', 'event_name', 'event_category')); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121<?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\Container\StaticContainer;use Piwik\Exception\InvalidRequestParameterException;use Piwik\Exception\UnexpectedWebsiteFoundException;use Piwik\Tracker;use Exception;use Piwik\Log\LoggerInterface;
class Handler{ /** * @var Response */ private $response;
/** * @var ScheduledTasksRunner */ private $tasksRunner;
/** * @var LoggerInterface */ private $logger;
public function __construct() { $this->setResponse(new Response()); $this->logger = StaticContainer::get(LoggerInterface::class); }
public function setResponse($response) { $this->response = $response; }
public function init(Tracker $tracker, RequestSet $requestSet) { $this->response->init($tracker); }
public function process(Tracker $tracker, RequestSet $requestSet) { foreach ($requestSet->getRequests() as $request) { $tracker->trackRequest($request); } }
public function onStartTrackRequests(Tracker $tracker, RequestSet $requestSet) { }
public function onAllRequestsTracked(Tracker $tracker, RequestSet $requestSet) { $tasks = $this->getScheduledTasksRunner(); if ($tasks->shouldRun($tracker)) { $tasks->runScheduledTasks(); } }
private function getScheduledTasksRunner() { if (is_null($this->tasksRunner)) { $this->tasksRunner = new ScheduledTasksRunner(); }
return $this->tasksRunner; }
/** * @internal */ public function setScheduledTasksRunner(ScheduledTasksRunner $runner) { $this->tasksRunner = $runner; }
public function onException(Tracker $tracker, RequestSet $requestSet, Exception $e) { $statusCode = 500; if ($e instanceof UnexpectedWebsiteFoundException) { $statusCode = 400; } elseif ($e instanceof InvalidRequestParameterException) { $statusCode = 400; }
// if an internal server error, log as a real error, otherwise it's just malformed input if ($statusCode == 500) { $this->logger->error('Exception: {exception}', [ 'exception' => $e, ]); } else { $this->logger->debug('Exception: {exception}', [ 'exception' => $e, ]); }
$this->response->outputException($tracker, $e, $statusCode); }
public function finish(Tracker $tracker, RequestSet $requestSet) { $this->response->outputResponse($tracker); return $this->response->getOutput(); }
public function getResponse() { return $this->response; }}123456789101112131415161718192021222324252627282930313233343536373839404142<?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\Handler;
use Exception;use Piwik\Piwik;use Piwik\Tracker\Handler;
class Factory{ public static function make() { $handler = null;
/** * Triggered before a new **handler tracking object** is created. Subscribers to this * event can force the use of a custom handler tracking object that extends from * {@link Piwik\Tracker\Handler} and customize any tracking behavior. * * @param \Piwik\Tracker\Handler &$handler Initialized to null, but can be set to * a new handler object. If it isn't modified * Piwik uses the default class. * @ignore This event is not public yet as the Handler API is not really stable yet */ Piwik::postEvent('Tracker.newHandler', array(&$handler));
if (is_null($handler)) { $handler = new Handler(); } elseif (!($handler instanceof Handler)) { throw new Exception("The Handler object set in the plugin must be an instance of Piwik\\Tracker\\Handler"); }
return $handler; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103<?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\Config;use Piwik\Cookie;use Piwik\ProxyHttp;
/** * Tracking cookies. * */class IgnoreCookie{ /** * Get tracking cookie * * @return Cookie */ private static function getTrackingCookie() { $cookie_name = @Config::getInstance()->Tracker['cookie_name']; $cookie_path = @Config::getInstance()->Tracker['cookie_path'];
$cookie = new Cookie($cookie_name, null, $cookie_path);
$domain = @Config::getInstance()->Tracker['cookie_domain']; if (!empty($domain)) { $cookie->setDomain($domain); }
return $cookie; }
public static function deleteThirdPartyCookieUIDIfExists() { $trackingCookie = self::getTrackingCookie(); if ($trackingCookie->isCookieFound()) { $trackingCookie->delete(); } }
/** * Get ignore (visit) cookie * * @return Cookie * @throws \Exception */ public static function getIgnoreCookie() { $cookie_name = @Config::getInstance()->Tracker['ignore_visits_cookie_name']; $cookie_path = @Config::getInstance()->Tracker['cookie_path'];
$cookie = new Cookie($cookie_name, "+ 30 years", $cookie_path, false);
$domain = @Config::getInstance()->Tracker['cookie_domain']; if (!empty($domain)) { $cookie->setDomain($domain); }
return $cookie; }
/** * Set ignore (visit) cookie or deletes it if already present */ public static function setIgnoreCookie() { $ignoreCookie = self::getIgnoreCookie(); if ($ignoreCookie->isCookieFound()) { $ignoreCookie->delete(); } else { $ignoreCookie->set('ignore', '*'); if (ProxyHttp::isHttps()) { $ignoreCookie->setSecure(true); $ignoreCookie->save('None'); } else { $ignoreCookie->save('Lax'); } }
self::deleteThirdPartyCookieUIDIfExists(); }
/** * Returns true if ignore (visit) cookie is present * * @return bool True if ignore cookie found; false otherwise */ public static function isIgnoreCookieFound() { $cookie = self::getIgnoreCookie(); return $cookie->isCookieFound() && $cookie->get('ignore') === '*'; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133<?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;
/** * Base class for LogTables. You need to create a log table eg if you want to be able to create a segment for a custom * log table. */abstract class LogTable{ /** * Get the unprefixed database table name. For example 'log_visit' or 'log_action'. * @return string */ abstract public function getName();
/** * Get the name of the column that represents the primary key. For example "idvisit" or "idlink_va". If the table * does not have a unique ID for each row, you may choose a column that comes closest to it, for example "idvisit". * @return string */ public function getIdColumn() { return ''; }
/** * Get the name of the column that can be used to join a visit with another table. This is the name of the column * that represents the "idvisit". * @return string */ public function getColumnToJoinOnIdVisit() { return ''; }
/** * Get the name of the column that can be used to join an action with another table. This is the name of the column * that represents the "idaction". * * This could be more generic eg by specifying "$this->joinableOn = array('action' => 'idaction') and this * would allow to also add more complex structures in the future but not needed for now I'd say. Let's go with * simpler, more clean and expressive solution for now until needed. * * @return string */ public function getColumnToJoinOnIdAction() { return ''; }
/** * If a table can neither be joined via idVisit nor idAction, it should be given a way to join with other tables * so the log table can be joined via idvisit through a different table joins. * * For this to work it requires the same column to be present in two tables. If for example you have a table * `log_foo_bar (idlogfoobar, idlogfoo)` and a table `log_foo(idlogfoo, idsite, idvisit)`, then you can in the * log table instance for `log_foo_bar` return `array('log_foo' => 'idlogfoo')`. This tells the core that a join * with that other log table is possible using the specified column. * @return array */ public function getWaysToJoinToOtherLogTables() { return array(); }
/** * Defines whether this table should be joined via a subselect. Return true if a complex join is needed. (eg when * having visits and needing actions, or when having visits and needing conversions, or vice versa). * @return bool */ public function shouldJoinWithSubSelect() { return false; }
/** * Defines a column that stores the date/time at which time an entry was written or updated. Setting this * can help improve the performance of some archive queries. For example the log_link_visit_action table would define * server_time while log_visit would define visit_last_action_time * @return string */ public function getDateTimeColumn() { return ''; }
/** * Returns the name of a log table that allows to join on a visit. Eg if there is a table "action", and it is not * joinable with "visit" table, it can return "log_link_visit_action" to be able to join the action table on visit * via this link table. * * In theory there could be case where it may be needed to join via two tables, so it could be needed at some * point to return an array of tables here. not sure if we should handle this case just yet. Alternatively, * once needed eg in LogQueryBuilder, we should maybe better call instead ->getLinkTableToBeAbleToJoinOnVisit() * again on the returned table until we have found a table that can be joined with visit. * * @return string */ public function getLinkTableToBeAbleToJoinOnVisit() { return; }
/** * Get the names of the columns that represents the primary key. For example "idvisit" or "idlink_va". If the table * defines the primary key based on multiple columns, you must specify them all * (eg array('idvisit', 'idgoal', 'buster')). * * @return array */ public function getPrimaryKey() { return array(); }
/** * Defines if the log table holds an `idvisitor` column. * If set to yes, existing records are automatically updated when the visitor id changes during a visit * */ public function hasIdVisitorColumn(): bool { return false; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728<?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 Exception;use Piwik\Common;use Piwik\Container\StaticContainer;use Piwik\Tracker;use Piwik\Log\LoggerInterface;
class Model{ public const CACHE_KEY_INDEX_IDSITE_IDVISITOR_TIME = 'log_visit_has_index_idsite_idvisitor_time';
/** * Write a visit action record to the database * * @param array $visitAction * * @return int */ public function createAction($visitAction) { $fields = implode(", ", array_keys($visitAction)); $values = Common::getSqlStringFieldsArray($visitAction); $table = Common::prefixTable('log_link_visit_action');
$sql = "INSERT INTO $table ($fields) VALUES ($values)"; $bind = array_values($visitAction);
$db = $this->getDb(); $db->query($sql, $bind);
$id = $db->lastInsertId();
return $id; }
/** * Write a goal conversion to the database * * @param array $conversion * * @return bool * @throws Db\DbException */ public function createConversion($conversion) {
$fields = implode(", ", array_keys($conversion)); $bindFields = Common::getSqlStringFieldsArray($conversion); $table = Common::prefixTable('log_conversion');
$sql = "INSERT IGNORE INTO $table ($fields) VALUES ($bindFields) "; $bind = array_values($conversion);
$db = $this->getDb(); $result = $db->query($sql, $bind);
// If a record was inserted, we return true return $db->rowCount($result) > 0; }
/** * Update an existing goal conversion in the database * * @param int $idVisit * @param int $idGoal * @param array $newConversion * * @return bool * @throws \DI\DependencyException * @throws \DI\NotFoundException */ public function updateConversion($idVisit, $idGoal, $newConversion) { $updateWhere = [ 'idvisit' => $idVisit, 'idgoal' => $idGoal, 'buster' => 0, ];
$updateParts = $sqlBind = $updateWhereParts = [];
foreach ($newConversion as $name => $value) { $updateParts[] = $name . " = ?"; $sqlBind[] = $value; }
foreach ($updateWhere as $name => $value) { $updateWhereParts[] = $name . " = ?"; $sqlBind[] = $value; }
$parts = implode(', ', $updateParts); $table = Common::prefixTable('log_conversion');
$sql = "UPDATE $table SET $parts WHERE " . implode(' AND ', $updateWhereParts);
try { $this->getDb()->query($sql, $sqlBind); } catch (Exception $e) { StaticContainer::get(LoggerInterface::class)->error("There was an error while updating the Conversion: {exception}", [ 'exception' => $e, ]);
return false; }
return true; }
/** * Returns the ecommerce items currently stored in the cart/order for the given visit. * * @param array $goal * @param int $defaultIdOrder * @return array */ public function getAllItemsCurrentlyInTheCart($goal, $defaultIdOrder) { $sql = "SELECT idaction_sku, idaction_name, idaction_category, idaction_category2, idaction_category3, idaction_category4, idaction_category5, price, quantity, deleted, idorder AS idorder_original_value FROM `" . Common::prefixTable('log_conversion_item') . "` WHERE idvisit = ? AND (idorder = ? OR idorder = ?)";
$bind = [ $goal['idvisit'], isset($goal['idorder']) ? $goal['idorder'] : $defaultIdOrder, $defaultIdOrder, ];
$itemsInDb = $this->getDb()->fetchAll($sql, $bind);
Common::printDebug("Items found in current cart, for conversion_item (visit,idorder)=" . var_export($bind, true)); Common::printDebug($itemsInDb);
return $itemsInDb; }
/** * Write ecommerce item to the conversion item table * * @param array $ecommerceItems * * @throws Db\DbException */ public function createEcommerceItems($ecommerceItems) { $sql = "INSERT IGNORE INTO " . Common::prefixTable('log_conversion_item'); $i = 0; $bind = [];
foreach ($ecommerceItems as $item) { if ($i === 0) { $fields = implode(', ', array_keys($item)); $sql .= ' (' . $fields . ') VALUES '; } elseif ($i > 0) { $sql .= ','; }
$newRow = array_values($item); $sql .= " ( " . Common::getSqlStringFieldsArray($newRow) . " ) "; $bind = array_merge($bind, $newRow); $i++; }
Common::printDebug($sql); Common::printDebug($bind);
try { $this->getDb()->query($sql, $bind); } catch (Exception $e) { if ( $e->getCode() == 23000 || false !== strpos($e->getMessage(), 'Duplicate entry') || false !== strpos($e->getMessage(), 'Integrity constraint violation') ) { Common::printDebug('Did not create ecommerce item as item was already created'); } else { throw $e; } } }
/** * Inserts a new action into the log_action table. If there is an existing action that was inserted * due to another request pre-empting this one, the newly inserted action is deleted. * * @param string $name * @param int $type * @param int $urlPrefix * @return int The ID of the action (can be for an existing action or new action). */ public function createNewIdAction($name, $type, $urlPrefix) { $newActionId = $this->insertNewAction($name, $type, $urlPrefix);
$realFirstActionId = $this->getIdActionMatchingNameAndType($name, $type);
// if the inserted action ID is not the same as the queried action ID, then that means we inserted // a duplicate, so remove it now if ($realFirstActionId != $newActionId) { $this->deleteDuplicateAction($newActionId); }
return $realFirstActionId; }
/** * Insert a new action into the DB * * @param string $name * @param int $type * @param string $urlPrefix * * @return int * @throws Db\DbException */ private function insertNewAction($name, $type, $urlPrefix) { $table = Common::prefixTable('log_action'); $sql = "INSERT INTO $table (name, hash, type, url_prefix) VALUES (?,CRC32(?),?,?)";
$db = $this->getDb(); $db->query($sql, [$name, $name, $type, $urlPrefix]);
$actionId = $db->lastInsertId();
return $actionId; }
/** * Get an idaction key from the DB * * @return string */ private function getSqlSelectActionId() { // it is possible for multiple actions to exist in the DB (due to rare concurrency issues), so the ORDER BY and // LIMIT are important $sql = "SELECT idaction, type, name FROM `" . Common::prefixTable('log_action') . "`" . " WHERE " . $this->getSqlConditionToMatchSingleAction() . " " . "ORDER BY idaction ASC LIMIT 1";
return $sql; }
/** * Get an idaction key from the DB by name and type * * @param string $name * @param int $type * * @return bool|mixed|string * @throws Exception */ public function getIdActionMatchingNameAndType($name, $type) { $sql = $this->getSqlSelectActionId(); $bind = [$name, $name, $type];
$idAction = $this->getDb()->fetchOne($sql, $bind);
return $idAction; }
/** * Returns the IDs for multiple actions based on name + type values. * * @param array $actionsNameAndType Array like `[ ['name' => '...', 'type' => 1], ... ]` * @return array|false Array of DB rows w/ columns: **idaction**, **type**, **name**. */ public function getIdsAction($actionsNameAndType) { $sql = "SELECT `idaction`, `type`, `name` FROM `" . Common::prefixTable('log_action') . "` WHERE"; $bind = [];
$i = 0; foreach ($actionsNameAndType as $actionNameType) { $name = $actionNameType['name'];
if (empty($name)) { continue; }
if ($i > 0) { $sql .= " OR"; }
$sql .= " " . $this->getSqlConditionToMatchSingleAction() . " ";
$bind[] = $name; $bind[] = $name; $bind[] = $actionNameType['type']; $i++; }
// Case URL & Title are empty if (empty($bind)) { return false; }
$rows = $this->getDb()->fetchAll($sql, $bind);
$actionsPerType = [];
foreach ($rows as $row) { $name = $row['name']; $type = $row['type'];
if (!isset($actionsPerType[$type])) { $actionsPerType[$type] = []; }
if (!isset($actionsPerType[$type][$name])) { $actionsPerType[$type][$name] = $row; } elseif ($row['idaction'] < $actionsPerType[$type][$name]['idaction']) { // keep the lowest idaction for this type, name $actionsPerType[$type][$name] = $row; } }
$actionsToReturn = []; foreach ($actionsPerType as $type => $actionsPerName) { foreach ($actionsPerName as $actionPerName) { $actionsToReturn[] = $actionPerName; } }
return $actionsToReturn; }
/** * Update an existing ecommerce item in the conversion items table * * @param string $originalIdOrder * @param array $newItem * * @throws Db\DbException */ public function updateEcommerceItem($originalIdOrder, $newItem) { $updateParts = $sqlBind = []; foreach ($newItem as $name => $value) { $updateParts[] = $name . " = ?"; $sqlBind[] = $value; }
$parts = implode(', ', $updateParts); $table = Common::prefixTable('log_conversion_item');
$sql = "UPDATE $table SET $parts WHERE idvisit = ? AND idorder = ? AND idaction_sku = ?";
$sqlBind[] = $newItem['idvisit']; $sqlBind[] = $originalIdOrder; $sqlBind[] = $newItem['idaction_sku'];
$this->getDb()->query($sql, $sqlBind); }
/** * Create new visit in the DB * * @param array $visit * * @return int * @throws Db\DbException */ public function createVisit($visit) { $fields = array_keys($visit); $fields = implode(", ", $fields); $values = Common::getSqlStringFieldsArray($visit); $table = Common::prefixTable('log_visit');
$sql = "INSERT INTO $table ($fields) VALUES ($values)"; $bind = array_values($visit);
$db = $this->getDb(); $db->query($sql, $bind);
return $db->lastInsertId(); }
/** * Update an existing visit in the DB * * @param int $idSite * @param int $idVisit * @param $valuesToUpdate * * @return bool * @throws Db\DbException */ public function updateVisit($idSite, $idVisit, $valuesToUpdate) { [$updateParts, $sqlBind] = $this->fieldsToQuery($valuesToUpdate);
$parts = implode(', ', $updateParts); $table = Common::prefixTable('log_visit');
$sqlQuery = "UPDATE $table SET $parts WHERE idsite = ? AND idvisit = ?";
$sqlBind[] = $idSite; $sqlBind[] = $idVisit;
$db = $this->getDb(); $result = $db->query($sqlQuery, $sqlBind); $wasInserted = $db->rowCount($result) != 0;
if (!$wasInserted) { Common::printDebug("Visitor with this idvisit wasn't found in the DB."); Common::printDebug("$sqlQuery --- "); Common::printDebug($sqlBind); }
return $wasInserted; }
/** * Update an existing action in the database * * @param $idLinkVa * @param $valuesToUpdate * * @return bool|void * @throws Db\DbException */ public function updateAction($idLinkVa, $valuesToUpdate) { if (empty($idLinkVa)) { return; }
[$updateParts, $sqlBind] = $this->fieldsToQuery($valuesToUpdate);
$parts = implode(', ', $updateParts); $table = Common::prefixTable('log_link_visit_action');
$sqlQuery = "UPDATE $table SET $parts WHERE idlink_va = ?";
$sqlBind[] = $idLinkVa;
$db = $this->getDb(); $result = $db->query($sqlQuery, $sqlBind); $wasInserted = $db->rowCount($result) != 0;
if (!$wasInserted) { Common::printDebug("Action with this idLinkVa wasn't found in the DB."); Common::printDebug("$sqlQuery --- "); Common::printDebug($sqlBind); }
return $wasInserted; }
public function updateIdVisitorInLogTable(string $logTable, string $idVisitor, array $conditions): bool { if (empty($idVisitor) || empty($conditions)) { return false; }
$table = Common::prefixTable($logTable);
$sqlQuery = "UPDATE `$table` SET `idvisitor` = ? WHERE "; $sqlConditions = []; $sqlBind = [$idVisitor];
foreach ($conditions as $name => $value) { $sqlConditions[] = $name . " = ?"; $sqlBind[] = $value; }
$sqlQuery .= implode(' AND ', $sqlConditions);
$db = $this->getDb(); $result = $db->query($sqlQuery, $sqlBind); return $db->rowCount($result) != 0; }
/** * Attempt to find an existing visit record in the database * * @param int $idSite * @param string $configId * @param string $idVisitor * @param string $userId * @param array $fieldsToRead * @param bool $shouldMatchOneFieldOnly * @param bool $isVisitorIdToLookup * @param string $timeLookBack * @param string $timeLookAhead * * @return array|bool|mixed */ public function findVisitor( $idSite, $configId, $idVisitor, $userId, $fieldsToRead, $shouldMatchOneFieldOnly, $isVisitorIdToLookup, $timeLookBack, $timeLookAhead ) { $selectFields = implode(', ', $fieldsToRead);
$select = "SELECT $selectFields "; $from = "FROM `" . Common::prefixTable('log_visit') . "`";
// Two use cases: // 1) there is no visitor ID so we try to match only on config_id (heuristics) // Possible causes of no visitor ID: no browser cookie support, direct Tracking API request without visitor ID passed, // importing server access logs with import_logs.py, etc. // In this case we use config_id heuristics to try find the visitor in tahhhe past. There is a risk to assign // this page view to the wrong visitor, but this is better than creating artificial visits. // 2) there is a visitor ID and we trust it (config setting trust_visitors_cookies, OR it was set using &cid= in tracking API), // and in these cases, we force to look up this visitor id $configIdWhere = "visit_last_action_time >= ? AND visit_last_action_time <= ? AND idsite = ?"; $configIdbindSql = [ $timeLookBack, $timeLookAhead, $idSite, ];
$visitorIdWhere = 'idsite = ? AND visit_last_action_time <= ?'; $visitorIdbindSql = [$idSite, $timeLookAhead];
if ($shouldMatchOneFieldOnly && $isVisitorIdToLookup) { $visitRow = $this->findVisitorByVisitorId($idVisitor, $select, $from, $visitorIdWhere, $visitorIdbindSql); } elseif ($shouldMatchOneFieldOnly) { $visitRow = $this->findVisitorByConfigId($configId, $select, $from, $configIdWhere, $configIdbindSql); } else { if (!empty($idVisitor)) { $visitRow = $this->findVisitorByVisitorId($idVisitor, $select, $from, $visitorIdWhere, $visitorIdbindSql); } else { $visitRow = false; }
if (empty($visitRow)) { if (!empty($userId)) { $configIdWhere .= ' AND ( user_id IS NULL OR user_id = ? )'; $configIdbindSql[] = $userId; } $visitRow = $this->findVisitorByConfigId($configId, $select, $from, $configIdWhere, $configIdbindSql); } }
return $visitRow; }
/** * Return true if a visit record exists for the idvisit key and site * * @param int $idSite * @param int $idVisit * * @return bool * @throws Exception */ public function hasVisit($idSite, $idVisit) { // will use INDEX index_idsite_idvisitor_time (idsite, idvisitor, visit_last_action_time) $sql = 'SELECT idsite FROM `' . Common::prefixTable('log_visit') . '` WHERE idvisit = ? LIMIT 1'; $bindSql = [$idVisit];
$val = $this->getDb()->fetchOne($sql, $bindSql); return $val == $idSite; }
/** * Attempt to find an existing visit record in the database by visitor id and passed query fragments * * @param string $idVisitor * @param string $select * @param string $from * @param string $where * @param array $bindSql * * @return array|bool|mixed */ private function findVisitorByVisitorId($idVisitor, $select, $from, $where, $bindSql) { $cache = Cache::getCacheGeneral();
// use INDEX index_idsite_idvisitor_time (idsite, idvisitor, visit_last_action_time) if available if ( array_key_exists(self::CACHE_KEY_INDEX_IDSITE_IDVISITOR_TIME, $cache) && true === $cache[self::CACHE_KEY_INDEX_IDSITE_IDVISITOR_TIME] ) { $from .= ' FORCE INDEX (index_idsite_idvisitor_time) '; }
$where .= ' AND idvisitor = ?'; $bindSql[] = $idVisitor;
return $this->fetchVisitor($select, $from, $where, $bindSql); }
/** * Attempt to find an existing visit record in the database by config id and passed query fragments * * @param string $configId * @param string $select * @param string $from * @param string $where * @param array $bindSql * * @return array|bool|mixed */ private function findVisitorByConfigId($configId, $select, $from, $where, $bindSql) { // will use INDEX index_idsite_config_datetime (idsite, config_id, visit_last_action_time) $where .= ' AND config_id = ?'; $bindSql[] = $configId;
return $this->fetchVisitor($select, $from, $where, $bindSql); }
/** * Retrieve a visit row from the database using the passed query fragments * * @param string $select * @param string $from * @param string $where * @param array $bindSql * * @return array|bool|mixed * @throws Db\DbException */ private function fetchVisitor($select, $from, $where, $bindSql) { $sql = "$select $from WHERE " . $where . " ORDER BY visit_last_action_time DESC LIMIT 1";
$visitRow = $this->getDb()->fetch($sql, $bindSql);
return $visitRow; }
/** * Returns true if the site doesn't have raw data. * * @param int $siteId * @return bool */ public function isSiteEmpty($siteId) { $sql = sprintf('SELECT idsite FROM `%s` WHERE idsite = ? limit 1', Common::prefixTable('log_visit'));
$result = \Piwik\Db::fetchOne($sql, [$siteId]);
return $result == null; }
/** * Build an array of fields and bind values * * @param array $valuesToUpdate * * @return array[] */ private function fieldsToQuery($valuesToUpdate) { $updateParts = []; $sqlBind = [];
foreach ($valuesToUpdate as $name => $value) { // Case where bind parameters don't work if ($value === $name . ' + 1') { //$name = 'visit_total_events' //$value = 'visit_total_events + 1'; $updateParts[] = " $name = $value "; } else { $updateParts[] = $name . " = ?"; $sqlBind[] = $value; } }
return [$updateParts, $sqlBind]; }
/** * Delete an action record by key * * @param int $newActionId * * @throws Db\DbException */ private function deleteDuplicateAction($newActionId) { $sql = "DELETE FROM `" . Common::prefixTable('log_action') . "` WHERE idaction = ?";
$db = $this->getDb(); $db->query($sql, [$newActionId]); }
/** * Get the tracker DB object * * @return \Piwik\Db|Db\Mysqli|Db\Pdo\Mysql|null * @throws Db\DbException */ private function getDb() { return Tracker::getDatabase(); }
/** * Get sql query where clauses used to match a single action * * @return string */ private function getSqlConditionToMatchSingleAction() { return "( hash = CRC32(?) AND name = ? AND type = ? )"; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440<?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();
$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 browsers do not strtolower the hostname), * and deal with 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; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979<?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 Exception;use Piwik\Request\AuthenticationToken;use Piwik\Common;use Piwik\Container\StaticContainer;use Piwik\Cookie;use Piwik\Exception\InvalidRequestParameterException;use Piwik\Exception\UnexpectedWebsiteFoundException;use Piwik\Http;use Piwik\IP;use Matomo\Network\IPUtils;use Piwik\Piwik;use Piwik\Plugins\UsersManager\UsersManager;use Piwik\ProxyHttp;use Piwik\Segment\SegmentExpression;use Piwik\Tracker;use Piwik\Cache as PiwikCache;use Piwik\Tracker\Cache as TrackerCache;use Piwik\Plugins\UserId\Settings\UserIdDisabled;
/** * The Request object holding the http parameters for this tracking request. Use getParam() to fetch a named parameter. * */class Request{ private $cdtCache; private $idSiteCache; private $paramsCache = array();
/** * @var array */ protected $params; protected $rawParams;
protected $isAuthenticated = null; private $isEmptyRequest = false;
protected $tokenAuth;
protected $timestamp;
/** * Stores plugin specific tracking request metadata. RequestProcessors can store * whatever they want in this array, and other RequestProcessors can modify these * values to change tracker behavior. * * @var array<string, array<string, mixed>> Keyed by plugin name, then metadata key. */ private $requestMetadata = array();
public const UNKNOWN_RESOLUTION = 'unknown';
private $customTimestampDoesNotRequireTokenauthWhenNewerThan;
/** * @param $params * @param string $tokenAuth */ public function __construct( $params, #[\SensitiveParameter] $tokenAuth = '' ) { if (!is_array($params)) { $params = array(); } $this->params = $params; $this->rawParams = $params; $this->tokenAuth = $tokenAuth; $this->timestamp = time(); $this->isEmptyRequest = empty($params);
// When the 'url' and referrer url parameter are not given, we might be in the 'Simple Image Tracker' mode. // The URL can default to the Referrer, which will be in this case // the URL of the page containing the Simple Image beacon if ( empty($this->params['urlref']) && empty($this->params['url']) && array_key_exists('HTTP_REFERER', $_SERVER) ) { $url = $_SERVER['HTTP_REFERER']; if (!empty($url)) { $this->params['url'] = $url; } }
// check for 4byte utf8 characters in all tracking params and replace them with � if not support by database $this->params = $this->replaceUnsupportedUtf8Chars($this->params);
$this->customTimestampDoesNotRequireTokenauthWhenNewerThan = TrackerConfig::getIntegerConfigValue( 'tracking_requests_require_authentication_when_custom_timestamp_newer_than', 0, $this->getIdSiteIfExists() ); }
protected function replaceUnsupportedUtf8Chars($value, $key = false) { $dbSettings = new \Piwik\Db\Settings(); $charset = $dbSettings->getUsedCharset();
if ('utf8mb4' === $charset) { return $value; // no need to replace anything if utf8mb4 is supported }
if (is_string($value) && preg_match('/[\x{10000}-\x{10FFFF}]/u', $value)) { Common::printDebug("Unsupported character detected in $key. Replacing with \xEF\xBF\xBD"); return preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value); }
if (is_array($value)) { array_walk_recursive($value, function (&$value, $key) { $value = $this->replaceUnsupportedUtf8Chars($value, $key); }); }
return $value; }
/** * Get the params that were originally passed to the instance. These params do not contain any params that were added * within this object. * @return array */ public function getRawParams() { return $this->rawParams; }
public function getTokenAuth() { return $this->tokenAuth; }
/** * @return bool */ public function isAuthenticated() { if (is_null($this->isAuthenticated)) { $this->authenticateTrackingApi($this->tokenAuth); }
return $this->isAuthenticated; }
/** * This method allows to set custom IP + server time + visitor ID, when using Tracking API. * These two attributes can be only set by the Super User (passing token_auth). */ protected function authenticateTrackingApi( #[\SensitiveParameter] $tokenAuth ) { $shouldAuthenticate = TrackerConfig::getConfigValue('tracking_requests_require_authentication', $this->getIdSiteIfExists());
if ($shouldAuthenticate) { try { $idSite = $this->getIdSite(); } catch (Exception $e) { Common::printDebug("failed to authenticate: invalid idSite"); $this->isAuthenticated = false; return; }
if (empty($tokenAuth) && !empty($this->params)) { $tokenAuth = StaticContainer::get(AuthenticationToken::class)->getAuthToken($this->params); }
if (empty($tokenAuth)) { $tokenAuth = StaticContainer::get(AuthenticationToken::class)->getAuthToken(); }
$cache = PiwikCache::getTransientCache(); $cacheKey = 'tracker_request_authentication_' . $idSite . '_' . $tokenAuth;
if ($cache->contains($cacheKey)) { Common::printDebug("token_auth is authenticated in cache!"); $this->isAuthenticated = $cache->fetch($cacheKey); return; }
try { $this->isAuthenticated = self::authenticateSuperUserOrAdminOrWrite($tokenAuth, $idSite); $cache->save($cacheKey, $this->isAuthenticated); } catch (Exception $e) { Common::printDebug("could not authenticate, caught exception: " . $e->getMessage());
$this->isAuthenticated = false; }
if ($this->isAuthenticated) { Common::printDebug("token_auth is authenticated!"); } else { if (preg_match('/^\w{28,36}$/', $tokenAuth) || empty($tokenAuth)) { // only log a failure if the token auth looks partial valid or is completely missing StaticContainer::get('Piwik\Tracker\Failures')->logFailure(Failures::FAILURE_ID_NOT_AUTHENTICATED, $this); } } } else { $this->isAuthenticated = true; Common::printDebug("token_auth authentication not required"); } }
public static function authenticateSuperUserOrAdminOrWrite( #[\SensitiveParameter] $tokenAuth, $idSite ) { if (empty($tokenAuth)) { return false; }
// Now checking the list of admin token_auth cached in the Tracker config file if (!empty($idSite) && $idSite > 0) { $website = Cache::getCacheWebsiteAttributes($idSite); $userModel = new \Piwik\Plugins\UsersManager\Model(); $tokenAuthHashed = $userModel->hashTokenAuth($tokenAuth); $hashedToken = UsersManager::hashTrackingToken((string) $tokenAuthHashed, $idSite);
if ( array_key_exists('tracking_token_auth', $website) && in_array($hashedToken, $website['tracking_token_auth'], true) ) { return true; } }
Piwik::postEvent('Request.initAuthenticationObject');
/** @var \Piwik\Auth $auth */ $auth = StaticContainer::get('Piwik\Auth'); $auth->setTokenAuth($tokenAuth); $auth->setLogin(null); $auth->setPassword(null); $auth->setPasswordHash(null); $access = $auth->authenticate();
if (!empty($access) && $access->hasSuperUserAccess()) { return true; }
Common::printDebug("WARNING! token_auth = $tokenAuth is not valid, Super User / Admin / Write was NOT authenticated");
/** * @ignore * @internal */ Piwik::postEvent('Tracker.Request.authenticate.failed');
return false; }
public function isRequestExcluded() { $excludedRequests = TrackerConfig::getConfigValue('exclude_requests', $this->getIdSiteIfExists());
if (!empty($excludedRequests)) { $excludedRequests = explode(',', $excludedRequests); $pattern = '/^(.+?)(' . SegmentExpression::MATCH_EQUAL . '|' . SegmentExpression::MATCH_NOT_EQUAL . '|' . SegmentExpression::MATCH_CONTAINS . '|' . SegmentExpression::MATCH_DOES_NOT_CONTAIN . '|' . preg_quote(SegmentExpression::MATCH_STARTS_WITH) . '|' . preg_quote(SegmentExpression::MATCH_ENDS_WITH) . '){1}(.*)/'; foreach ($excludedRequests as $excludedRequest) { $match = preg_match($pattern, $excludedRequest, $matches);
if (!empty($match)) { $leftMember = $matches[1]; $operation = $matches[2]; if (!isset($matches[3])) { $valueRightMember = ''; } else { $valueRightMember = urldecode($matches[3]); } $actual = Common::getRequestVar($leftMember, '', 'string', $this->params); $actual = mb_strtolower($actual); $valueRightMember = mb_strtolower($valueRightMember); switch ($operation) { case SegmentExpression::MATCH_EQUAL: if ($actual === $valueRightMember) { return true; } break; case SegmentExpression::MATCH_NOT_EQUAL: if ($actual !== $valueRightMember) { return true; } break; case SegmentExpression::MATCH_CONTAINS: if (stripos($actual, $valueRightMember) !== false) { return true; } break; case SegmentExpression::MATCH_DOES_NOT_CONTAIN: if (stripos($actual, $valueRightMember) === false) { return true; } break; case SegmentExpression::MATCH_STARTS_WITH: if (stripos($actual, $valueRightMember) === 0) { return true; } break; case SegmentExpression::MATCH_ENDS_WITH: if (Common::stringEndsWith($actual, $valueRightMember)) { return true; } break; } } } }
return false; } /** * Returns the language the visitor is viewing. * * @return string browser language code, eg. "en-gb,en;q=0.5" */ public function getBrowserLanguage() { $parameterValue = Common::getRequestVar('lang', '', 'string', $this->params); return Common::getBrowserLanguage($parameterValue ?: null); }
/** * @return string */ public function getLocalTime() { $localTimes = array( 'h' => (string)Common::getRequestVar('h', $this->getCurrentDate("H"), 'int', $this->params), 'i' => (string)Common::getRequestVar('m', $this->getCurrentDate("i"), 'int', $this->params), 's' => (string)Common::getRequestVar('s', $this->getCurrentDate("s"), 'int', $this->params), ); if ($localTimes['h'] < 0 || $localTimes['h'] > 23) { $localTimes['h'] = 0; } if ($localTimes['i'] < 0 || $localTimes['i'] > 59) { $localTimes['i'] = 0; } if ($localTimes['s'] < 0 || $localTimes['s'] > 59) { $localTimes['s'] = 0; } foreach ($localTimes as $k => $time) { if (strlen($time) == 1) { $localTimes[$k] = '0' . $time; } } $localTime = $localTimes['h'] . ':' . $localTimes['i'] . ':' . $localTimes['s']; return $localTime; }
/** * Returns the current date in the "Y-m-d" PHP format * * @param string $format * @return string */ protected function getCurrentDate($format = "Y-m-d") { return date($format, $this->getCurrentTimestamp()); }
public function getGoalRevenue($defaultGoalRevenue) { return Common::getRequestVar('revenue', $defaultGoalRevenue, 'float', $this->params); }
public function getParam($name) { static $supportedParams = array( // Name => array( defaultValue, type ) '_refts' => array(0, 'int'), '_ref' => array('', 'string'), '_rcn' => array('', 'string'), '_rck' => array('', 'string'), 'url' => array('', 'string'), 'urlref' => array('', 'string'), 'res' => array(self::UNKNOWN_RESOLUTION, 'string'), 'idgoal' => array(-1, 'int'), 'ping' => array(0, 'int'),
// other 'bots' => array(0, 'int'), 'dp' => array(0, 'int'), 'rec' => array(0, 'int'), 'new_visit' => array(0, 'int'),
// Ecommerce 'ec_id' => array('', 'string'), 'ec_st' => array(false, 'float'), 'ec_tx' => array(false, 'float'), 'ec_sh' => array(false, 'float'), 'ec_dt' => array(false, 'float'), 'ec_items' => array('', 'json'),
// ecommerce product/category view '_pkc' => array('', 'string'), '_pks' => array('', 'string'), '_pkn' => array('', 'string'), '_pkp' => array(false, 'float'),
// Events 'e_c' => array('', 'string'), 'e_a' => array('', 'string'), 'e_n' => array('', 'string'), 'e_v' => array(false, 'float'),
// some visitor attributes can be overwritten 'cip' => array('', 'string'), 'cdt' => array('', 'string'), 'cdo' => array('', 'int'), 'cid' => array('', 'string'), 'uid' => array('', 'string'),
// Actions / pages 'cs' => array('', 'string'), 'download' => array('', 'string'), 'link' => array('', 'string'), 'action_name' => array('', 'string'), 'search' => array('', 'string'), 'search_cat' => array('', 'string'), 'pv_id' => array('', 'string'), 'search_count' => array(-1, 'int'), 'pf_net' => array(-1, 'int'), 'pf_srv' => array(-1, 'int'), 'pf_tfr' => array(-1, 'int'), 'pf_dm1' => array(-1, 'int'), 'pf_dm2' => array(-1, 'int'), 'pf_onl' => array(-1, 'int'),
// Content 'c_p' => array('', 'string'), 'c_n' => array('', 'string'), 'c_t' => array('', 'string'), 'c_i' => array('', 'string'),
// custom action request. Recommended when a plugin declares its own action handler/requestprocessor // refs https://github.com/matomo-org/matomo/issues/16569 'ca' => array(0, 'int'), );
if (isset($this->paramsCache[$name])) { return $this->paramsCache[$name]; }
if (!isset($supportedParams[$name])) { throw new Exception("Requested parameter $name is not a known Tracking API Parameter."); }
$paramDefaultValue = $supportedParams[$name][0]; $paramType = $supportedParams[$name][1];
if ($this->hasParam($name)) { $this->paramsCache[$name] = $this->replaceUnsupportedUtf8Chars(Common::getRequestVar($name, $paramDefaultValue, $paramType, $this->params), $name); } else { $this->paramsCache[$name] = $paramDefaultValue; }
return $this->paramsCache[$name]; }
public function setParam($name, $value) { $this->params[$name] = $value; unset($this->paramsCache[$name]);
if ($name === 'cdt') { $this->cdtCache = null; } }
public function hasParam($name) { return isset($this->params[$name]); }
public function getParams() { return $this->params; }
public function getCurrentTimestamp() { if (!isset($this->cdtCache)) { $this->cdtCache = $this->getCustomTimestamp(); }
if (!empty($this->cdtCache)) { return $this->cdtCache; }
return $this->timestamp; }
public function setCurrentTimestamp($timestamp) { $this->timestamp = $timestamp; }
protected function getCustomTimestamp() { if (!$this->hasParam('cdt') && !$this->hasParam('cdo')) { return false; }
$cdt = $this->getParam('cdt'); $cdo = $this->getParam('cdo');
if (empty($cdt) && $cdo) { $cdt = $this->timestamp; }
if (empty($cdt)) { return false; }
if (!is_numeric($cdt)) { $cdt = strtotime($cdt, $this->timestamp); }
if (!empty($cdo)) { $cdt = $cdt - abs($cdo); }
if (!$this->isTimestampValid($cdt, $this->timestamp)) { Common::printDebug(sprintf("Datetime %s is not valid", date("Y-m-d H:i:m", $cdt))); return false; }
// If timestamp in the past, token_auth is required $timeFromNow = $this->timestamp - $cdt; $isTimestampRecent = $timeFromNow < $this->customTimestampDoesNotRequireTokenauthWhenNewerThan;
if (!$isTimestampRecent) { if (!$this->isAuthenticated()) { $message = sprintf("Custom timestamp is %s seconds old, requires &token_auth...", $timeFromNow); Common::printDebug($message); Common::printDebug("WARN: Tracker API 'cdt' was used with invalid token_auth"); throw new InvalidRequestParameterException($message); } }
$cache = Tracker\Cache::getCacheGeneral(); if (!empty($cache['delete_logs_enable']) && !empty($cache['delete_logs_older_than'])) { $scheduleInterval = $cache['delete_logs_schedule_lowest_interval']; $maxLogAge = $cache['delete_logs_older_than']; $logEntryCutoff = time() - (($maxLogAge + $scheduleInterval) * 60 * 60 * 24); if ($cdt < $logEntryCutoff) { $message = "Custom timestamp is older than the configured 'deleted old raw data' value of $maxLogAge days"; Common::printDebug($message); throw new InvalidRequestParameterException($message); } }
return (int) $cdt; }
/** * Returns true if the timestamp is valid ie. timestamp is sometime in the last 20 years and is not in the future. * * @param $time int Timestamp to test * @param $now int Current timestamp * @return bool */ protected function isTimestampValid($time, $now = null) { if (empty($now)) { $now = $this->getCurrentTimestamp(); }
return $time <= $now && $time > $now - 20 * 365 * 86400; }
/** * @internal * @ignore */ public function getIdSiteUnverified() { $idSite = Common::getRequestVar('idsite', 0, 'int', $this->params);
/** * Triggered when obtaining the ID of the site we are tracking a visit for. * * This event can be used to change the site ID so data is tracked for a different * website. * * @param int &$idSite Initialized to the value of the **idsite** query parameter. If a * subscriber sets this variable, the value it uses must be greater * than 0. * @param array $params The entire array of request parameters in the current tracking * request. */ Piwik::postEvent('Tracker.Request.getIdSite', array(&$idSite, $this->params)); return $idSite; }
public function getIdSiteIfExists() { try { return $this->getIdSite(); } catch (UnexpectedWebsiteFoundException $ex) { return null; } }
public function getIdSite() { if (isset($this->idSiteCache)) { return $this->idSiteCache; }
$idSite = $this->getIdSiteUnverified();
if ($idSite <= 0) { throw new UnexpectedWebsiteFoundException('Invalid idSite: \'' . $idSite . '\''); }
// check site actually exists, should throw UnexpectedWebsiteFoundException directly $site = Cache::getCacheWebsiteAttributes($idSite);
if (empty($site)) { // fallback just in case exception wasn't thrown... throw new UnexpectedWebsiteFoundException('Invalid idSite: \'' . $idSite . '\''); }
$this->idSiteCache = $idSite;
return $idSite; }
public function getUserAgent() { $default = false;
if (array_key_exists('HTTP_USER_AGENT', $_SERVER)) { $default = $_SERVER['HTTP_USER_AGENT']; }
return Common::getRequestVar('ua', $default, 'string', $this->params); }
public function getClientHints(): array { // use headers as default if no data was send with the tracking request $default = Http::getClientHintsFromServerVariables();
$clientHints = Common::getRequestVar('uadata', $default, 'json', $this->params);
return is_array($clientHints) ? $clientHints : []; }
public function shouldUseThirdPartyCookie() { return TrackerConfig::getConfigValue('use_third_party_id_cookie', $this->getIdSiteIfExists()); }
public function getThirdPartyCookieVisitorId() { $cookie = $this->makeThirdPartyCookieUID(); $idVisitor = $cookie->get(0); if ( $idVisitor !== false && strlen($idVisitor) == Tracker::LENGTH_HEX_ID_STRING ) { return $idVisitor; } return null; }
/** * Update the cookie information. */ public function setThirdPartyCookie($idVisitor) { if (!$this->shouldUseThirdPartyCookie()) { return; }
if (\Piwik\Tracker\IgnoreCookie::isIgnoreCookieFound()) { return; }
$cookie = $this->makeThirdPartyCookieUID(); $idVisitor = bin2hex($idVisitor); $cookie->set(0, $idVisitor); if (ProxyHttp::isHttps()) { $cookie->setSecure(true); $cookie->save('None'); } else { $cookie->save('Lax'); }
Common::printDebug(sprintf("We set the visitor ID to %s in the 3rd party cookie...", $idVisitor)); }
protected function makeThirdPartyCookieUID() { $cookie = new Cookie( $this->getCookieName(), $this->getCookieExpire(), $this->getCookiePath() );
$domain = $this->getCookieDomain(); if (!empty($domain)) { $cookie->setDomain($domain); }
Common::printDebug($cookie);
return $cookie; }
protected function getCookieName() { return TrackerConfig::getConfigValue('cookie_name', $this->getIdSiteIfExists()); }
protected function getCookieExpire() { return $this->getCurrentTimestamp() + TrackerConfig::getConfigValue('cookie_expire', $this->getIdSiteIfExists()); }
protected function getCookiePath() { return TrackerConfig::getConfigValue('cookie_path', $this->getIdSiteIfExists()); }
protected function getCookieDomain() { return TrackerConfig::getConfigValue('cookie_domain', $this->getIdSiteIfExists()); }
/** * Returns the ID from the request in this order: * return from a given User ID, * or from a Tracking API forced Visitor ID, * or from a Visitor ID from 3rd party (optional) cookies, * or from a given Visitor Id from 1st party? * * @throws Exception */ public function getVisitorId() { $found = false;
if (TrackerConfig::getConfigValue('enable_userid_overwrites_visitorid', $this->getIdSiteIfExists())) { // If User ID is set it takes precedence $userId = $this->getForcedUserId(); if ($userId) { $userIdHashed = $this->getUserIdHashed($userId); $idVisitor = $this->truncateIdAsVisitorId($userIdHashed); Common::printDebug("Request will be recorded for this user_id = " . $userId . " (idvisitor = $idVisitor)"); $found = true; } }
// Was a Visitor ID "forced" (@see Tracking API setVisitorId()) for this request? if (!$found) { $idVisitor = $this->getForcedVisitorId(); if (!empty($idVisitor)) { if (strlen($idVisitor) != Tracker::LENGTH_HEX_ID_STRING) { throw new InvalidRequestParameterException("Visitor ID (cid) $idVisitor must be " . Tracker::LENGTH_HEX_ID_STRING . " characters long"); } Common::printDebug("Request will be recorded for this idvisitor = " . $idVisitor); $found = true; } }
$privacyConfig = new \Piwik\Plugins\PrivacyManager\Config();
// Only check for cookie values if cookieless tracking is NOT forced if (!$privacyConfig->forceCookielessTracking) { // - If set to use 3rd party cookies for Visit ID, read the cookie if (!$found) { $useThirdPartyCookie = $this->shouldUseThirdPartyCookie(); if ($useThirdPartyCookie) { $idVisitor = $this->getThirdPartyCookieVisitorId(); if (!empty($idVisitor)) { $found = true; } } }
// If a third party cookie was not found, we default to the first party cookie if (!$found) { $idVisitor = Common::getRequestVar('_id', '', 'string', $this->params); $found = strlen($idVisitor) >= Tracker::LENGTH_HEX_ID_STRING; } }
if ($found) { return $this->getVisitorIdAsBinary($idVisitor); }
return false; }
/** * When creating a third party cookie, we want to ensure that the original value set in this 3rd party cookie * sticks and is not overwritten later. */ public function getVisitorIdForThirdPartyCookie() { $found = false;
// For 3rd party cookies, priority is on re-using the existing 3rd party cookie value if (!$found) { $useThirdPartyCookie = $this->shouldUseThirdPartyCookie(); if ($useThirdPartyCookie) { $idVisitor = $this->getThirdPartyCookieVisitorId(); if (!empty($idVisitor)) { $found = true; } } }
// If a third party cookie was not found, we default to the first party cookie if (!$found) { $idVisitor = Common::getRequestVar('_id', '', 'string', $this->params); $found = strlen($idVisitor) >= Tracker::LENGTH_HEX_ID_STRING; }
if ($found) { return $this->getVisitorIdAsBinary($idVisitor); }
return false; }
public function getIp() { return IPUtils::stringToBinaryIP($this->getIpString()); }
public function getForcedUserId() { $userId = $this->getParam('uid'); if (strlen($userId) === 0) { return false; }
try { $idSite = $this->getIdSite(); if (!empty($idSite) && $idSite > 0) { $cache = TrackerCache::getCacheWebsiteAttributes($idSite); $cacheKey = UserIdDisabled::class; if (($cache[$cacheKey] ?? false) === true) { return false; } } } catch (\Exception $e) { // Might fail for e.g. not existing sites, but we do not want to throw an exception at this stage }
return $userId; }
public function getForcedVisitorId() { return $this->getParam('cid'); }
public function getPlugins() { static $pluginsInOrder = array('fla', 'java', 'qt', 'realp', 'pdf', 'wma', 'ag', 'cookie'); $plugins = array(); foreach ($pluginsInOrder as $param) { $plugins[] = Common::getRequestVar($param, 0, 'int', $this->params); } return $plugins; }
public function isEmptyRequest() { return $this->isEmptyRequest; }
/** * @param $idVisitor * @return string */ private function truncateIdAsVisitorId($idVisitor) { return substr($idVisitor, 0, Tracker::LENGTH_HEX_ID_STRING); }
/** * Matches implementation of MatomoTracker::getUserIdHashed * * @param $userId * @return string */ public function getUserIdHashed($userId) { return substr(sha1($userId), 0, 16); }
/** * @return mixed|string * @throws Exception */ public function getIpString() { $cip = $this->getParam('cip');
if (empty($cip)) { return IP::getIpFromHeader(); }
if (!$this->isAuthenticated()) { Common::printDebug("WARN: Tracker API 'cip' was used with invalid token_auth"); throw new InvalidRequestParameterException("Tracker API 'cip' was used, requires valid token_auth"); }
return $cip; }
/** * Set a request metadata value. * * @param string $pluginName eg, `'Actions'`, `'Goals'`, `'YourPlugin'` * @param string $key * @param mixed $value */ public function setMetadata($pluginName, $key, $value) { $this->requestMetadata[$pluginName][$key] = $value; }
/** * Get a request metadata value. Returns `null` if none exists. * * @param string $pluginName eg, `'Actions'`, `'Goals'`, `'YourPlugin'` * @param string $key * @return mixed */ public function getMetadata($pluginName, $key) { return isset($this->requestMetadata[$pluginName][$key]) ? $this->requestMetadata[$pluginName][$key] : null; }
/** * @param $idVisitor * @return bool|string */ private function getVisitorIdAsBinary($idVisitor) { $truncated = $this->truncateIdAsVisitorId($idVisitor); $binVisitorId = @Common::hex2bin($truncated); if (!empty($binVisitorId)) { return $binVisitorId; } return false; }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192<?php
/** * Matomo - free/libre analytics platform * * @link https://matomo.org * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */
declare(strict_types=1);
namespace Piwik\Tracker;
use Piwik\Container\StaticContainer;use Piwik\Date;use Piwik\Exception\UnexpectedWebsiteFoundException;use Piwik\Plugins\UserCountry\Columns\Base;
trait RequestHandlerTrait{ protected $fieldsThatRequireAuth = [ 'city', 'region', 'country', 'lat', 'long', ];
protected function checkSiteExists(Request $request): void { try { $request->getIdSite(); } catch (UnexpectedWebsiteFoundException $e) { $idSite = $request->getRawParams()['idsite'] ?? null; if (is_numeric($idSite) && (string)(int)$idSite === (string)$idSite && (int)$idSite >= 0) { // only log a failure in case the provided idsite was valid positive integer StaticContainer::get(Failures::class)->logFailure(Failures::FAILURE_ID_INVALID_SITE, $request); }
throw $e; } }
protected function validateRequest(Request $request): void { // Check for params that aren't allowed to be included unless the request is authenticated foreach ($this->fieldsThatRequireAuth as $field) { Base::getValueFromUrlParamsIfAllowed($field, $request); }
// Special logic for timestamp as some overrides are OK without auth and others aren't $request->getCurrentTimestamp(); }
protected function markArchivedReportsAsInvalidIfArchiveAlreadyFinished(Request $request): void { $idSite = (int)$request->getIdSite(); $time = $request->getCurrentTimestamp();
$timezone = $this->getTimezoneForSite($idSite);
if (!isset($timezone)) { return; }
$date = Date::factory((int)$time, $timezone);
// $date->isToday() is buggy when server and website timezones don't match - so we'll do our own checking $startOfToday = Date::factoryInTimezone('yesterday', $timezone)->addDay(1); $isLaterThanYesterday = $date->getTimestamp() >= $startOfToday->getTimestamp(); if ($isLaterThanYesterday) { return; // don't try to invalidate archives for today or later }
StaticContainer::get('Piwik\Archive\ArchiveInvalidator')->rememberToInvalidateArchivedReportsLater($idSite, $date); }
private function getTimezoneForSite(int $idSite): ?string { try { $site = Cache::getCacheWebsiteAttributes($idSite); } catch (UnexpectedWebsiteFoundException $e) { return null; }
if (!empty($site['timezone'])) { return $site['timezone']; }
return null; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165<?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\Tracker\Visit\VisitProperties;
/** * Base class for all tracker RequestProcessors. RequestProcessors handle and respond to tracking * requests. * * ## Concept: Request Metadata * * RequestProcessors take a Tracker\Request object and based on its information, set request metadata. * * Request metadata is information about the current tracking request, for example, whether * the request is for an existing visit or new visit, or whether the current visitor is a known * visitor, etc. It is used to control tracking behavior. * * Request metadata is shared between RequestProcessors, so RequestProcessors can tweak each others * behavior, and thus, the behavior of the Tracker. Request metadata can be set and get using the * {@link Request::setMetadata()} and {@link Request::getMetadata()} * methods. * * Each RequestProcessor lists the request metadata it computes and exposes in its class * documentation. * * ## The Tracking Process * * When Piwik handles a single tracking request, it gathers all available RequestProcessors and * invokes their methods in sequence. * * The first method called is {@link self::manipulateRequest()}. By default this is a no-op, but * RequestProcessors can use it to manipulate tracker requests before they are processed. * * The second method called is {@link self::processRequestParams()}. RequestProcessors should use * this method to compute request metadata and set visit properties using the tracking request. * An example includes the ActionRequestProcessor, which uses this method to determine the action * being tracked. * * The third method called is {@link self::afterRequestProcessed()}. RequestProcessors should * use this method to either compute request metadata/visit properties using other plugins' * request metadata, OR override other plugins' request metadata to tweak tracker behavior. * An example of the former can be seen in the GoalsRequestProcessor which uses the action * detected by the ActionsRequestProcessor to see if there are any action-matching goal * conversions. An example of the latter can be seen in the PingRequestProcessor, which on * ping requests, aborts conversion recording and new visit recording. * * After these methods are called, either {@link self::onNewVisit()} or {@link self::onExistingVisit()} * is called. Generally, plugins should favor defining Dimension classes instead of using these methods, * however sometimes it is not possible (as is the case with the CustomVariables plugin). * * Finally, the {@link self::recordLogs()} method is called. In this method, RequestProcessors * should use the request metadata that was set (and maybe overridden) to insert whatever log data * they want. * * ## Extending The Piwik Tracker * * Plugins that want to change the tracking process in order to track new data or change how * existing data is tracked can create RequestProcessors to accomplish. * * _Note: If you only want to add tracked data to visits, actions or conversions, you should create * a {@link Dimension} class._ * * To create a new RequestProcessor, create a new class that derives from this one, and implement the * methods you need. Then put this class inside the `Tracker` directory of your plugin. * * Final note: RequestProcessors are shared between tracking requests, and so, should ideally be * stateless. They are stored in DI, so they can contain references to other objects in DI, but * they shouldn't contain data that might change between tracking requests. */abstract class RequestProcessor{ /** * This is the first method called when processing a tracker request. * * Derived classes can use this method to manipulate a tracker request before the request * is handled. Plugins could change the URL, add custom variables, etc. */ public function manipulateRequest(Request $request) { // empty }
/** * This is the second method called when processing a tracker request. * * Derived classes should use this method to set request metadata based on the tracking * request alone. They should not try to access request metadata from other plugins, * since they may not be set yet. * * When this method is called, `$visitProperties->visitorInfo` will be empty. * * @return bool If `true` the tracking request will be aborted. */ public function processRequestParams(VisitProperties $visitProperties, Request $request) { return false; }
/** * This is the third method called when processing a tracker request. * * Derived classes should use this method to set request metadata that needs request metadata * from other plugins, or to override request metadata from other plugins to change * tracking behavior. * * When this method is called, you can assume all available request metadata from all plugins * will be initialized (but not at their final value). Also, `$visitProperties->visitorInfo` * will contain the values of the visitor's last known visit (if any). * * @return bool If `true` the tracking request will be aborted. */ public function afterRequestProcessed(VisitProperties $visitProperties, Request $request) { return false; }
/** * This method is called before recording a new visit. You can set/change visit information here * to change what gets inserted into `log_visit`. * * Only implement this method if you cannot use a Dimension for the same thing. * * Please note that the `onNewAction` hook in an action dimension is executed after this method. */ public function onNewVisit(VisitProperties $visitProperties, Request $request) { // empty }
/** * This method is called before updating an existing visit. You can set/change visit information * here to change what gets recorded in `log_visit`. * * Only implement this method if you cannot use a Dimension for the same thing. * * Please note that the `onNewAction` hook in an action dimension is executed before this method. * * @param array &$valuesToUpdate */ public function onExistingVisit(&$valuesToUpdate, VisitProperties $visitProperties, Request $request) { // empty }
/** * This method is called last. Derived classes should use this method to insert log data. They * should also only read request metadata, and not set it. * * When this method is called, you can assume all request metadata have their final values. Also, * `$visitProperties->visitorInfo` will contain the properties of the visitor's current visit (in * other words, the values in the array were persisted to the DB before this method was called). */ public function recordLogs(VisitProperties $visitProperties, Request $request) { // empty }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215<?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\Request\AuthenticationToken;use Piwik\Container\StaticContainer;use Piwik\Piwik;
class RequestSet{ /** * The set of visits to track. * * @var Request[] */ private $requests = null;
/** * The token auth supplied with a bulk visits POST. * * @var string */ private $tokenAuth = null;
private $env = array();
public function setRequests($requests) { $this->requests = array();
if (empty($requests) || !is_array($requests)) { return; }
foreach ($requests as $request) { if (empty($request) && !is_array($request)) { continue; }
if (!$request instanceof Request) { $request = new Request($request, $this->getTokenAuth()); } $this->requests[] = $request; } }
public function setTokenAuth( #[\SensitiveParameter] $tokenAuth ) { $this->tokenAuth = $tokenAuth; }
public function getNumberOfRequests() { if (is_array($this->requests)) { return count($this->requests); }
return 0; }
public function getRequests() { if (!$this->areRequestsInitialized()) { return array(); }
return $this->requests; }
public function getTokenAuth() { if (!is_null($this->tokenAuth)) { return $this->tokenAuth; }
return StaticContainer::get(AuthenticationToken::class)->getAuthToken(); }
private function areRequestsInitialized() { return !is_null($this->requests); }
public function initRequestsAndTokenAuth() { if ($this->areRequestsInitialized()) { return; }
/** * Triggered when detecting tracking requests. A plugin can use this event to set * requests that should be tracked by calling the {@link RequestSet::setRequests()} method. * For example the BulkTracking plugin uses this event to detect tracking requests and auth token based on * a sent JSON instead of default $_GET+$_POST. It would allow you for example to track requests based on * XML or you could import tracking requests stored in a file. * * @param \Piwik\Tracker\RequestSet &$requestSet Call {@link setRequests()} to initialize requests and * {@link setTokenAuth()} to set a detected auth token. * * @ignore This event is not public yet as the RequestSet API is not really stable yet */ Piwik::postEvent('Tracker.initRequestSet', array($this));
if (!$this->areRequestsInitialized()) { $this->requests = array();
if (!empty($_GET) || !empty($_POST)) { $this->setRequests(array($_GET + $_POST)); } } }
public function hasRequests() { return !empty($this->requests); }
protected function getAllSiteIdsWithinRequest() { if (empty($this->requests)) { return array(); }
$siteIds = array(); foreach ($this->requests as $request) { $siteIds[] = (int) $request->getIdSite(); }
return array_values(array_unique($siteIds)); }
public function getState() { $requests = array( 'requests' => array(), 'env' => $this->getEnvironment(), 'tokenAuth' => $this->getTokenAuth(), 'time' => time(), );
foreach ($this->getRequests() as $request) { $requests['requests'][] = $request->getRawParams(); }
return $requests; }
public function restoreState($state) { $backupEnv = $this->getCurrentEnvironment();
$this->setEnvironment($state['env']); $this->setTokenAuth($state['tokenAuth']);
$this->restoreEnvironment(); $this->setRequests($state['requests']);
foreach ($this->getRequests() as $request) { $request->setCurrentTimestamp($state['time']); }
$this->resetEnvironment($backupEnv); }
public function rememberEnvironment() { $this->setEnvironment($this->getEnvironment()); }
public function setEnvironment($env) { $this->env = $env; }
protected function getEnvironment() { if (!empty($this->env)) { return $this->env; }
return $this->getCurrentEnvironment(); }
public function restoreEnvironment() { if (empty($this->env)) { return; }
$this->resetEnvironment($this->env); }
private function resetEnvironment($env) { $_SERVER = $env['server']; $_COOKIE = isset($env['cookie']) ? $env['cookie'] : array(); }
private function getCurrentEnvironment() { return array( 'server' => $_SERVER, 'cookie' => $_COOKIE, ); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231<?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 Exception;use Piwik\Common;use Piwik\Config;use Piwik\Profiler;use Piwik\Timer;use Piwik\Tracker;use Piwik\Tracker\Db as TrackerDb;use Piwik\Url;
class Response{ private $timer;
private $content;
public function init(Tracker $tracker) { ob_start(); // we use ob_start only because of Common::printDebug, we should actually not really use ob_start
if ($tracker->isDebugModeEnabled() && TrackerConfig::getConfigValue('enable_sql_profiler')) { $this->timer = new Timer();
TrackerDb::enableProfiling(); } }
public function getOutput() { $this->outputAccessControlHeaders();
if (is_null($this->content) && ob_get_level() > 0) { $this->content = ob_get_clean(); }
return $this->content; }
/** * Echos an error message & other information, then exits. * * @param int $statusCode eg 500 */ public function outputException(Tracker $tracker, Exception $e, $statusCode) { Common::sendResponseCode($statusCode); $this->logExceptionToErrorLog($e);
if ($tracker->isDebugModeEnabled()) { echo "\nAn exception occurred: " . $this->getMessageFromException($e) . "\n\n"; } else { $this->outputApiResponse($tracker); } }
public function outputResponse(Tracker $tracker) { if (!$tracker->shouldRecordStatistics()) { Common::sendResponseCode(503); $this->outputApiResponse($tracker); Common::printDebug("Logging disabled, display transparent logo"); } elseif (!$tracker->hasLoggedRequests()) { if (!$this->isHttpGetRequest() || !empty($_GET) || !empty($_POST)) { Common::sendResponseCode(400); } Common::printDebug("Empty request => Matomo page"); echo "This resource is part of Matomo. Keep full control of your data with the leading free and open source <a href='https://matomo.org' target='_blank' rel='noopener noreferrer nofollow'>web analytics & conversion optimisation platform</a>.<br>\n"; echo "This file is the endpoint for the Matomo tracking API. If you want to access the Matomo UI or use the Reporting API, please use <a href='index.php'>index.php</a> instead.\n"; } else { $this->outputApiResponse($tracker); Common::printDebug("Nothing to notice => default behaviour"); }
Common::printDebug("End of the page.");
if ( $tracker->isDebugModeEnabled() && $tracker->isDatabaseConnected() && TrackerDb::isProfilingEnabled() ) { $db = Tracker::getDatabase(); $db->recordProfiling(); Profiler::displayDbTrackerProfile($db); }
if ($tracker->isDebugModeEnabled()) { Common::printDebug($_COOKIE); Common::printDebug((string)$this->timer); } }
private function outputAccessControlHeaders() { if (!$this->isHttpGetRequest()) { $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*'; Common::sendHeader('Access-Control-Allow-Origin: ' . $origin); Common::sendHeader('Access-Control-Allow-Credentials: true'); } }
private function isHttpGetRequest() { $requestMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
return strtoupper($requestMethod) === 'GET'; }
private function getOutputBuffer() { return ob_get_contents(); }
protected function hasAlreadyPrintedOutput() { return strlen($this->getOutputBuffer()) > 0; }
private function outputApiResponse(Tracker $tracker) { if ($tracker->isDebugModeEnabled()) { return; }
if ($this->hasAlreadyPrintedOutput()) { return; }
$request = $_GET + $_POST;
if ($this->isHttpGetRequest()) { Common::sendHeader('Cache-Control: no-store'); }
if (array_key_exists('send_image', $request) && $request['send_image'] === '0') { Common::sendResponseCode(204); return; }
// Check for a custom tracking image $customImage = Config::getInstance()->Tracker['custom_image']; if (!empty($customImage) && $this->outputCustomImage($customImage)) { return; }
// No custom image defined, so output the default 1x1 base64 transparent gif $this->outputTransparentGif(); }
/** * Output a 1px x 1px transparent gif */ private function outputTransparentGif() { $transGifBase64 = "R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="; Common::sendHeader('Content-Type: image/gif');
echo base64_decode($transGifBase64); }
/** * Output a custom tracking image * * @param string $customImage The custom image setting specified in the config * * @return bool True if the custom image was successfully output, else false */ private function outputCustomImage(string $customImage): bool { $supportedMimeTypes = ['image/png', 'image/gif', 'image/jpeg'];
$img = null; $size = null;
if (strlen($customImage) > 2 && substr($customImage, -2) == '==') { // Base64 image string $img = base64_decode($customImage); $size = getimagesizefromstring($img); } elseif (is_file($customImage) && is_readable($customImage)) { // Image file $img = file_get_contents($customImage); $size = getimagesize($customImage); // imagesize is used to get the mime type }
// Must have valid image data and a valid mime type to proceed if ($img && $size && isset($size['mime']) && in_array($size['mime'], $supportedMimeTypes)) { Common::sendHeader('Content-Type: ' . $size['mime']); echo $img; return true; }
return false; }
/** * Gets the error message to output when a tracking request fails. * * @param Exception $e * @return string */ protected function getMessageFromException($e) { // Note: duplicated from FormDatabaseSetup.isAccessDenied // Avoid leaking the username/db name when access denied if ($e->getCode() == 1044 || $e->getCode() == 42000) { return "Error while connecting to the Matomo database - please check your credentials in config/config.ini.php file"; }
if (Common::isPhpCliMode()) { return $e->getMessage() . "\n" . $e->getTraceAsString(); }
return $e->getMessage(); }
protected function logExceptionToErrorLog($e) { $hostname = Url::getRFCValidHostname(); $hostStr = $hostname ? "[$hostname]" : '-'; error_log(sprintf("$hostStr Error in Matomo (tracker): %s", str_replace("\n", " ", $this->getMessageFromException($e)))); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687<?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\CliMulti;use Piwik\Common;use Piwik\Option;use Piwik\Tracker;
class ScheduledTasksRunner{ public function shouldRun(Tracker $tracker) { if (Common::isPhpCliMode()) { // don't run scheduled tasks in CLI mode from Tracker, this is the case // where we bulk load logs & don't want to lose time with tasks return false; }
return $tracker->shouldRecordStatistics(); }
/** * Tracker requests will automatically trigger the Scheduled tasks. * This is useful for users who don't setup the cron, * but still want daily/weekly/monthly PDF reports emailed automatically. * * This is similar to calling the API CoreAdminHome.runScheduledTasks */ public function runScheduledTasks() { $now = time();
// Currently, there are no hourly tasks. When there are some, // this could be too aggressive minimum interval (some hours would be skipped in case of low traffic) $minimumInterval = TrackerConfig::getConfigValue('scheduled_tasks_min_interval');
// If the user disabled browser archiving, they have already setup a cron // To avoid parallel requests triggering the Scheduled Tasks, // Get last time tasks started executing $cache = Cache::getCacheGeneral();
if ( $minimumInterval <= 0 || empty($cache['isBrowserTriggerEnabled']) ) { Common::printDebug("-> Scheduled tasks not running in Tracker: Browser archiving is disabled."); return; }
$nextRunTime = $cache['lastTrackerCronRun'] + $minimumInterval;
if ( (defined('DEBUG_FORCE_SCHEDULED_TASKS') && DEBUG_FORCE_SCHEDULED_TASKS) || $cache['lastTrackerCronRun'] === false || $nextRunTime < $now ) { $cache['lastTrackerCronRun'] = $now; Cache::setCacheGeneral($cache);
Option::set('lastTrackerCronRun', $cache['lastTrackerCronRun']); Common::printDebug('-> Scheduled Tasks: Starting...');
$invokeScheduledTasksUrl = "?module=API&format=csv&convertToUnicode=0&method=CoreAdminHome.runScheduledTasks&trigger=archivephp";
$cliMulti = new CliMulti(); $cliMulti->runAsSuperUser(); $responses = $cliMulti->request(array($invokeScheduledTasksUrl)); $resultTasks = reset($responses);
Common::printDebug($resultTasks);
Common::printDebug('Finished Scheduled Tasks.'); } else { Common::printDebug("-> Scheduled tasks not triggered."); }
Common::printDebug("Next run will be from: " . date('Y-m-d H:i:s', $nextRunTime) . ' UTC'); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191<?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\Config;use Piwik\Container\StaticContainer;use Piwik\Date;use Piwik\Tracker;use Piwik\DeviceDetector\DeviceDetectorFactory;use Piwik\SettingsPiwik;
class Settings // TODO: merge w/ visitor recognizer or make it it's own service. the class name is required for BC.{ public const OS_BOT = 'BOT';
/** * If `true`, the config ID for a visitor will be the same no matter what site is being tracked. * If `false`, the config ID will be different. * * @var bool */ private $isSameFingerprintsAcrossWebsites;
public function __construct($isSameFingerprintsAcrossWebsites) { $this->isSameFingerprintsAcrossWebsites = $isSameFingerprintsAcrossWebsites; }
public function getConfigId(Request $request, $ipAddress): string { list($plugin_Flash, $plugin_Java, $plugin_Quicktime, $plugin_RealPlayer, $plugin_PDF, $plugin_WindowsMedia, $plugin_Silverlight, $plugin_Cookie) = $request->getPlugins();
$userAgent = $request->getUserAgent();
$deviceDetector = StaticContainer::get(DeviceDetectorFactory::class)->makeInstance($userAgent, $request->getClientHints()); $aBrowserInfo = $deviceDetector->getClient();
if (empty($aBrowserInfo['type']) || 'browser' !== $aBrowserInfo['type']) { // for now only track browsers unset($aBrowserInfo); }
$browserName = !empty($aBrowserInfo['short_name']) ? $aBrowserInfo['short_name'] : 'UNK'; $browserVersion = !empty($aBrowserInfo['version']) ? $aBrowserInfo['version'] : '';
if ($deviceDetector->isBot()) { $os = self::OS_BOT; } else { $os = $deviceDetector->getOS(); $os = empty($os['short_name']) ? 'UNK' : $os['short_name']; }
$client = $deviceDetector->getClient(); if (!empty($client['name']) && $client['name'] === 'Internet Explorer') { // we assume cookies are disabled... when in tracker cookies are disabled, this ensures when upgrading to this version // that no fingerprint changes in the 30min window during the upgrade... // We don't include it anymore as it otherwise may cause new visits to be created when switching between // cookies disabled and enabled in IE11 or older. Before Matomo 3.13.7 when cookies were disabled, then // this value was set to 0. For people with cookies enabled the fingerprint is not as relevant as the visitorId // is used to identify a visitor $plugin_Cookie = '0'; }
$browserLang = substr($request->getBrowserLanguage(), 0, 20); // limit the length of this string to match db $trackerConfig = Config::getInstance()->Tracker;
$fingerprintSalt = '';
// fingerprint salt won't work when across multiple sites since all sites could have different timezones // also cant add fingerprint salt for a specific day when we dont create new visit after midnight if (!$this->isSameFingerprintsAcrossWebsites && !empty($trackerConfig['create_new_visit_after_midnight'])) { $cache = Cache::getCacheWebsiteAttributes($request->getIdSite()); $date = Date::factory((int) $request->getCurrentTimestamp()); $fingerprintSaltKey = new FingerprintSalt(); $dateString = $fingerprintSaltKey->getDateString($date, $cache['timezone']);
if (!empty($cache[FingerprintSalt::OPTION_PREFIX . $dateString])) { $fingerprintSalt = $cache[FingerprintSalt::OPTION_PREFIX . $dateString]; } else { // we query the DB directly for requests older than 2-3 days... $fingerprintSalt = $fingerprintSaltKey->getSalt($dateString, $request->getIdSite()); }
$fingerprintSalt .= $dateString;
if (defined('PIWIK_TEST_MODE') && PIWIK_TEST_MODE) { $fingerprintSalt = ''; // use fixed value so they don't change randomly in tests } }
return $this->getConfigHash( $request, $os, $browserName, $browserVersion, $plugin_Flash, $plugin_Java, $plugin_Quicktime, $plugin_RealPlayer, $plugin_PDF, $plugin_WindowsMedia, $plugin_Silverlight, $plugin_Cookie, $ipAddress, $browserLang, $fingerprintSalt ); }
public function getRandomConfigId(): string { return $this->getRandomConfigHash(); }
/** * Returns a 64-bit hash that attempts to identify a user. * Maintaining some privacy by default, eg. prevents the merging of several Piwik serve together for matching across instances.. * * @param $os * @param $browserName * @param $browserVersion * @param $plugin_Flash * @param $plugin_Java * @param $plugin_Quicktime * @param $plugin_RealPlayer * @param $plugin_PDF * @param $plugin_WindowsMedia * @param $plugin_Silverlight * @param $plugin_Cookie * @param $ip * @param $browserLang * @param $fingerprintHash */ protected function getConfigHash( Request $request, $os, $browserName, $browserVersion, $plugin_Flash, $plugin_Java, $plugin_Quicktime, $plugin_RealPlayer, $plugin_PDF, $plugin_WindowsMedia, $plugin_Silverlight, $plugin_Cookie, $ip, $browserLang, $fingerprintHash ): string { // prevent the config hash from being the same, across different Piwik instances // (limits ability of different Piwik instances to cross-match users) $salt = SettingsPiwik::getSalt();
$configString = $os . $browserName . $browserVersion . $plugin_Flash . $plugin_Java . '0' . $plugin_Quicktime . $plugin_RealPlayer . $plugin_PDF . $plugin_WindowsMedia . '0' . $plugin_Silverlight . $plugin_Cookie . $ip . $browserLang . $salt . $fingerprintHash;
if (!$this->isSameFingerprintsAcrossWebsites) { $configString .= $request->getIdSite(); }
return $this->createHashOfConfigString($configString); }
protected function getRandomConfigHash(): string { return $this->createHashOfConfigString(random_bytes(64)); }
private function createHashOfConfigString(string $configString): string { $hash = md5($configString, $raw_output = true);
return substr($hash, 0, Tracker::LENGTH_BINARY_ID); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335<?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\Common;use Piwik\Segment\SegmentExpression;
/** * This class is used to query Action IDs from the log_action table. * * A pageview, outlink, download or site search are made of several "Action IDs" * For example pageview is idaction_url and idaction_name. * */class TableLogAction{ /** * This function will find the idaction from the lookup table log_action, * given an Action name, type, and an optional URL Prefix. * * This is used to record Page URLs, Page Titles, Ecommerce items SKUs, item names, item categories * * If the action name does not exist in the lookup table, it will INSERT it * @param array $actionsNameAndType Array of one or many (name,type) * @return array Returns the an array (Field name => idaction) */ public static function loadIdsAction($actionsNameAndType) { // Add url prefix if not set foreach ($actionsNameAndType as &$action) { if (2 == count($action)) { $action[] = null; } }
$actionIds = self::queryIdsAction($actionsNameAndType);
[$queriedIds, $fieldNamesToInsert] = self::processIdsToInsert($actionsNameAndType, $actionIds);
$insertedIds = self::insertNewIdsAction($actionsNameAndType, $fieldNamesToInsert); $queriedIds = $queriedIds + $insertedIds;
return $queriedIds; }
/** * @param $matchType * @param $actionType * @return string * @throws \Exception */ private static function getSelectQueryWhereNameContains($matchType, $actionType) { // now, we handle the cases =@ (contains) and !@ (does not contain) // build the expression based on the match type $sql = 'SELECT idaction FROM `' . Common::prefixTable('log_action') . '` WHERE %s AND type = ' . $actionType . ' )';
switch ($matchType) { case SegmentExpression::MATCH_CONTAINS: // use concat to make sure, no %s occurs because some plugins use %s in their sql $where = '( name LIKE CONCAT(\'%\', ?, \'%\') '; break; case SegmentExpression::MATCH_DOES_NOT_CONTAIN: $where = '( name NOT LIKE CONCAT(\'%\', ?, \'%\') '; break; case SegmentExpression::MATCH_STARTS_WITH: // use concat to make sure, no %s occurs because some plugins use %s in their sql $where = '( name LIKE CONCAT(?, \'%\') '; break; case SegmentExpression::MATCH_ENDS_WITH: // use concat to make sure, no %s occurs because some plugins use %s in their sql $where = '( name LIKE CONCAT(\'%\', ?) '; break; default: throw new \Exception("This match type $matchType is not available for action-segments."); break; }
$sql = sprintf($sql, $where);
return $sql; }
private static function insertNewIdsAction($actionsNameAndType, $fieldNamesToInsert) { // Then, we insert all new actions in the lookup table $inserted = array();
foreach ($fieldNamesToInsert as $fieldName) { [$name, $type, $urlPrefix] = $actionsNameAndType[$fieldName];
$actionId = self::getModel()->createNewIdAction($name, $type, $urlPrefix);
Common::printDebug("Recorded a new action (" . Action::getTypeAsString($type) . ") in the lookup table: " . $name . " (idaction = " . $actionId . ")");
$inserted[$fieldName] = $actionId; }
return $inserted; }
private static function getModel() { return new Model(); }
private static function queryIdsAction($actionsNameAndType) { $toQuery = array(); foreach ($actionsNameAndType as &$actionNameType) { [$name, $type, $urlPrefix] = $actionNameType; $toQuery[] = array('name' => $name, 'type' => $type); }
$actionIds = self::getModel()->getIdsAction($toQuery);
return $actionIds; }
private static function processIdsToInsert($actionsNameAndType, $actionIds) { // For the Actions found in the lookup table, add the idaction in the array, // If not found in lookup table, queue for INSERT $fieldNamesToInsert = $fieldNameToActionId = array();
foreach ($actionsNameAndType as $fieldName => &$actionNameType) { @list($name, $type, $urlPrefix) = $actionNameType; if (empty($name)) { $fieldNameToActionId[$fieldName] = false; continue; }
$found = false; foreach ($actionIds as $row) { if ( $name == $row['name'] && $type == $row['type'] ) { $found = true;
$fieldNameToActionId[$fieldName] = $row['idaction']; continue; } } if (!$found) { $fieldNamesToInsert[] = $fieldName; } }
return array($fieldNameToActionId, $fieldNamesToInsert); }
/** * Convert segment expression to an action ID or an SQL expression. * * This method is used as a sqlFilter-callback for the segments of this plugin. * Usually, these callbacks only return a value that should be compared to the * column in the database. In this case, that doesn't work since multiple IDs * can match an expression (e.g. "pageUrl=@foo"). * @param string $valueToMatch * @param string $sqlField * @param string $matchType * @param string $segmentName * @return array|int|string|null */ public static function getIdActionFromSegment($valueToMatch, $sqlField, $matchType, $segmentName) { if ($segmentName === 'actionType') { $actionType = (int) $valueToMatch; $valueToMatch = array(); $sql = 'SELECT idaction FROM `' . Common::prefixTable('log_action') . '` WHERE type = ' . $actionType . ' )'; } else { $actionType = self::guessActionTypeFromSegment($segmentName); $valueToMatch = self::removeProtocolIfSegmentStoredWithoutIt($valueToMatch, $actionType, $segmentName);
$unsanitizedValue = $valueToMatch; $valueToMatch = self::normaliseActionString($actionType, $valueToMatch); if ( $matchType == SegmentExpression::MATCH_EQUAL || $matchType == SegmentExpression::MATCH_NOT_EQUAL ) { $idAction = self::getModel()->getIdActionMatchingNameAndType($valueToMatch, $actionType); // If action can't be found normalized try search for it with original value // This can eg happen for outlinks that contain a & see https://github.com/matomo-org/matomo/issues/11806 if (empty($idAction)) { $idAction = self::getModel()->getIdActionMatchingNameAndType($unsanitizedValue, $actionType); // Action is not found (eg. &segment=pageTitle==Větrnásssssss) if (empty($idAction)) { $idAction = null; } } return $idAction; }
// "name contains $string" match can match several idaction so we cannot return yet an idaction // special case $sql = self::getSelectQueryWhereNameContains($matchType, $actionType); }
return array( // mark that the returned value is an sql-expression instead of a literal value 'SQL' => $sql, 'bind' => $valueToMatch, ); }
/** * @param $segmentName * @return int * @throws \Exception */ private static function guessActionTypeFromSegment($segmentName) { $exactMatch = array( 'outlinkUrl' => Action::TYPE_OUTLINK, 'downloadUrl' => Action::TYPE_DOWNLOAD, 'eventUrl' => Action::TYPE_EVENT, 'eventAction' => Action::TYPE_EVENT_ACTION, 'eventCategory' => Action::TYPE_EVENT_CATEGORY, 'eventName' => Action::TYPE_EVENT_NAME, 'contentPiece' => Action::TYPE_CONTENT_PIECE, 'contentTarget' => Action::TYPE_CONTENT_TARGET, 'contentName' => Action::TYPE_CONTENT_NAME, 'contentInteraction' => Action::TYPE_CONTENT_INTERACTION, 'productName' => Action::TYPE_ECOMMERCE_ITEM_NAME, 'productSku' => Action::TYPE_ECOMMERCE_ITEM_SKU, 'productViewName' => Action::TYPE_ECOMMERCE_ITEM_NAME, 'productViewSku' => Action::TYPE_ECOMMERCE_ITEM_SKU, );
if (!empty($exactMatch[$segmentName])) { return $exactMatch[$segmentName]; }
if (stripos($segmentName, 'pageurl') !== false) { return Action::TYPE_PAGE_URL; } elseif (stripos($segmentName, 'pagetitle') !== false) { return Action::TYPE_PAGE_TITLE; } elseif (stripos($segmentName, 'sitesearch') !== false) { return Action::TYPE_SITE_SEARCH; } elseif ( stripos($segmentName, 'productcategory') !== false || stripos($segmentName, 'productviewcategory') !== false ) { return Action::TYPE_ECOMMERCE_ITEM_CATEGORY; } else { throw new \Exception("We cannot guess the action type from the segment $segmentName."); } }
/** * This function will sanitize or not if it's needed for the specified action type * * URLs (Download URL, Outlink URL) are stored raw (unsanitized) * while other action types are stored Sanitized * * @param $actionType * @param $actionString * @return string */ private static function normaliseActionString($actionType, $actionString) { $actionString = Common::unsanitizeInputValue($actionString);
if (self::isActionTypeStoredUnsanitized($actionType)) { return $actionString; }
return Common::sanitizeInputValue($actionString); }
/** * @param $actionType * @return bool */ private static function isActionTypeStoredUnsanitized($actionType) { $actionsTypesStoredUnsanitized = array( Action::TYPE_DOWNLOAD, Action::TYPE_OUTLINK, Action::TYPE_PAGE_URL, Action::TYPE_CONTENT, );
return in_array($actionType, $actionsTypesStoredUnsanitized); }
public static function removeProtocolIfSegmentStoredWithoutIt($url, $actionType, $segmentName) { if ($actionType == Action::TYPE_PAGE_URL || $segmentName == 'eventUrl') { // for urls trim protocol and www because it is not recorded in the db $url = preg_replace('@^http[s]?://(www\.)?@i', '', $url); } return $url; }
/** * Returns an idaction value to match an idaction column by searching log_action, if $matchType is * SegmentExpression::MATCH_EQUAL or SegmentExpression::MATCH_NOT_EQUAL. This method is used * to optimize segment conditions involving idaction queries, avoiding a join by querying the log_action * table beforehand. * * Should be used as the $sqlFilter property for idaction dimensions that use `ActionNameJoin`. * * @param string $value the value in the segment condition * @param string $sqlField the table column of the segment condition * @param string $matchType the SegmentExpression match type, eg, `SegmentExpression::MATCH_NOT_EQUAL` * @param string $segmentName the name of the segment, ie, `pageUrl` * @return array|null|string */ public static function getOptimizedIdActionSqlMatch($value, $sqlField, $matchType, $segmentName) { if ($matchType == SegmentExpression::MATCH_EQUAL || $matchType == SegmentExpression::MATCH_NOT_EQUAL) { $result = self::getIdActionFromSegment($value, $sqlField, $matchType, $segmentName);
if (is_numeric($result)) { return ['value' => $result, 'joinTable' => false]; }
return $result; }
$actionType = self::guessActionTypeFromSegment($segmentName); $value = self::removeProtocolIfSegmentStoredWithoutIt($value, $actionType, $segmentName);
return $value; }}core/Settings/Settings.phpAdded+124
core/Settings/Storage/Backend/BackendInterface.phpAdded+47
core/Settings/Storage/Backend/BaseSettingsTable.phpAdded+41
core/Settings/Storage/Backend/Cache.phpAdded+77
core/Settings/Storage/Backend/Config.phpAdded+75
core/Settings/Storage/Backend/MeasurableSettingsTable.phpAdded+194
core/Settings/Storage/Backend/NullBackend.phpAdded+42
core/Settings/Storage/Backend/PluginSettingsTable.phpAdded+403
core/Settings/Storage/Backend/SitesTable.phpAdded+145
core/Settings/Storage/Factory.phpAdded+139
core/Settings/Storage/LegacyUserSettingsMigration.phpAdded+316
core/Settings/Storage/Storage.phpAdded+117
core/Settings/Storage/UserScopedSettingsAccessManager.phpAdded+102
core/SettingsPiwik.phpAdded+491
core/SettingsServer.phpAdded+275
core/Singleton.phpAdded+74
core/Site.phpAdded+674
core/SiteContentDetector.phpAdded+402
core/SupportedBrowser.phpAdded+71
core/TCPDF.phpAdded+87
core/Theme.phpAdded+166
core/Timer.phpAdded+126
core/Tracker.phpAdded+402
core/Tracker/Action.phpAdded+465
core/Tracker/ActionPageview.phpAdded+95
core/Tracker/BotRequest.phpAdded+91
core/Tracker/BotRequestProcessor.phpAdded+38
core/Tracker/Cache.phpAdded+321
core/Tracker/Config/ThirdPartyCookies.phpAdded+114
core/Tracker/Db.phpAdded+305
core/Tracker/Db/DbException.phpAdded+20
core/Tracker/Db/Mysqli.phpAdded+473
core/Tracker/Db/Pdo/Mysql.phpAdded+438
core/Tracker/Failures.phpAdded+200
core/Tracker/FingerprintSalt.phpAdded+82
core/Tracker/GoalManager.phpAdded+1002
core/Tracker/Handler.phpAdded+121
core/Tracker/Handler/Factory.phpAdded+42
core/Tracker/IgnoreCookie.phpAdded+103
core/Tracker/LogTable.phpAdded+133
core/Tracker/Model.phpAdded+728
core/Tracker/PageUrl.phpAdded+440
core/Tracker/Request.phpAdded+979
core/Tracker/RequestHandlerTrait.phpAdded+92
core/Tracker/RequestProcessor.phpAdded+165
core/Tracker/RequestSet.phpAdded+215
core/Tracker/Response.phpAdded+231
core/Tracker/ScheduledTasksRunner.phpAdded+87
core/Tracker/Settings.phpAdded+191
core/Tracker/TableLogAction.phpAdded+335