diff --git a/core/Settings/Settings.php b/core/Settings/Settings.php new file mode 100644 index 0000000000000000000000000000000000000000..7b8a5ecfc201b125b31b19af19d4f96b0bba6caf --- /dev/null +++ b/core/Settings/Settings.php @@ -0,0 +1,124 @@ + [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(); + } + } +} diff --git a/core/Settings/Storage/Backend/BackendInterface.php b/core/Settings/Storage/Backend/BackendInterface.php new file mode 100644 index 0000000000000000000000000000000000000000..6890e9503d73349cc87aabb9f878bb5c345db9ea --- /dev/null +++ b/core/Settings/Storage/Backend/BackendInterface.php @@ -0,0 +1,47 @@ + $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(); +} diff --git a/core/Settings/Storage/Backend/BaseSettingsTable.php b/core/Settings/Storage/Backend/BaseSettingsTable.php new file mode 100644 index 0000000000000000000000000000000000000000..5a360681db648f51ff0568c046abead647f66735 --- /dev/null +++ b/core/Settings/Storage/Backend/BaseSettingsTable.php @@ -0,0 +1,41 @@ +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(); + } + } +} diff --git a/core/Settings/Storage/Backend/Cache.php b/core/Settings/Storage/Backend/Cache.php new file mode 100644 index 0000000000000000000000000000000000000000..ac39704e1136b9bf6756a394c2f3c02e96b724bd --- /dev/null +++ b/core/Settings/Storage/Backend/Cache.php @@ -0,0 +1,77 @@ +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(); + } +} diff --git a/core/Settings/Storage/Backend/Config.php b/core/Settings/Storage/Backend/Config.php new file mode 100644 index 0000000000000000000000000000000000000000..556638f8929ae2bc17d8e4ae518779561f696e49 --- /dev/null +++ b/core/Settings/Storage/Backend/Config.php @@ -0,0 +1,75 @@ +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(); + } +} diff --git a/core/Settings/Storage/Backend/MeasurableSettingsTable.php b/core/Settings/Storage/Backend/MeasurableSettingsTable.php new file mode 100644 index 0000000000000000000000000000000000000000..b548fb7038ef420617eb5215b2b4a15740645bc8 --- /dev/null +++ b/core/Settings/Storage/Backend/MeasurableSettingsTable.php @@ -0,0 +1,194 @@ +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; + } + } + } +} diff --git a/core/Settings/Storage/Backend/NullBackend.php b/core/Settings/Storage/Backend/NullBackend.php new file mode 100644 index 0000000000000000000000000000000000000000..4f7806d05f3c65578c2e4de8da1338152342d5bc --- /dev/null +++ b/core/Settings/Storage/Backend/NullBackend.php @@ -0,0 +1,42 @@ +storageId = $storageId; + } + + public function load() + { + return array(); + } + + public function getStorageId() + { + return $this->storageId; + } + + public function delete() + { + } + + public function save($values) + { + } +} diff --git a/core/Settings/Storage/Backend/PluginSettingsTable.php b/core/Settings/Storage/Backend/PluginSettingsTable.php new file mode 100644 index 0000000000000000000000000000000000000000..f87d03093e0f2db61210a30d988ca18007f495c7 --- /dev/null +++ b/core/Settings/Storage/Backend/PluginSettingsTable.php @@ -0,0 +1,403 @@ +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> + */ + 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 + */ + 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; + } +} diff --git a/core/Settings/Storage/Backend/SitesTable.php b/core/Settings/Storage/Backend/SitesTable.php new file mode 100644 index 0000000000000000000000000000000000000000..8018360944e5b6ed432b8eb39db326982d16a382 --- /dev/null +++ b/core/Settings/Storage/Backend/SitesTable.php @@ -0,0 +1,145 @@ +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() + { + } +} diff --git a/core/Settings/Storage/Factory.php b/core/Settings/Storage/Factory.php new file mode 100644 index 0000000000000000000000000000000000000000..25858e5c048ef36005afd179d2f696bdf53be686 --- /dev/null +++ b/core/Settings/Storage/Factory.php @@ -0,0 +1,139 @@ +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); + } +} diff --git a/core/Settings/Storage/LegacyUserSettingsMigration.php b/core/Settings/Storage/LegacyUserSettingsMigration.php new file mode 100644 index 0000000000000000000000000000000000000000..0ff587f2cab4ee0766aa6b4f3619454ec6df1e91 --- /dev/null +++ b/core/Settings/Storage/LegacyUserSettingsMigration.php @@ -0,0 +1,316 @@ +store = $store; + } + + /** + * @return array + */ + 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 $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 $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 $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 $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 + */ + 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 + */ + 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 $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); + } +} diff --git a/core/Settings/Storage/Storage.php b/core/Settings/Storage/Storage.php new file mode 100644 index 0000000000000000000000000000000000000000..6d83cb9f2bede137489f49bf07b93a5960b9ba40 --- /dev/null +++ b/core/Settings/Storage/Storage.php @@ -0,0 +1,117 @@ + [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(); + } +} diff --git a/core/Settings/Storage/UserScopedSettingsAccessManager.php b/core/Settings/Storage/UserScopedSettingsAccessManager.php new file mode 100644 index 0000000000000000000000000000000000000000..08e5b3fb15b5f36031538b265afef54d7a066594 --- /dev/null +++ b/core/Settings/Storage/UserScopedSettingsAccessManager.php @@ -0,0 +1,102 @@ + + */ + 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> + */ + 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]; + } +} diff --git a/core/SettingsPiwik.php b/core/SettingsPiwik.php new file mode 100644 index 0000000000000000000000000000000000000000..4eaadcbe8fe3b0d23e90310dcbfa32b6c48d5740 --- /dev/null +++ b/core/SettingsPiwik.php @@ -0,0 +1,491 @@ +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']; + } +} diff --git a/core/SettingsServer.php b/core/SettingsServer.php new file mode 100644 index 0000000000000000000000000000000000000000..eb27137968f9c955b5d75d8e50f43fa4c372a4ef --- /dev/null +++ b/core/SettingsServer.php @@ -0,0 +1,275 @@ += 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'; + } +} diff --git a/core/Singleton.php b/core/Singleton.php new file mode 100644 index 0000000000000000000000000000000000000000..4956b8c7ae2500064d6c19538dd1a740e2c68b63 --- /dev/null +++ b/core/Singleton.php @@ -0,0 +1,74 @@ +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 $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 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'); + } +} diff --git a/core/SiteContentDetector.php b/core/SiteContentDetector.php new file mode 100644 index 0000000000000000000000000000000000000000..1342094a750a94163a57df7ce5da5a63d60c3c11 --- /dev/null +++ b/core/SiteContentDetector.php @@ -0,0 +1,402 @@ +detectContent([GoogleAnalytics3::getId()]); + * if ($contentDetector->ga3) { + * // site is using GA3 + * } + * + * @api + */ +class SiteContentDetector +{ + /** + * @var array> + */ + 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 + */ + 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; + } +} diff --git a/core/SupportedBrowser.php b/core/SupportedBrowser.php new file mode 100644 index 0000000000000000000000000000000000000000..b0842957b0d437cde082c02bd7eac2782702e5be --- /dev/null +++ b/core/SupportedBrowser.php @@ -0,0 +1,71 @@ + 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 = "

" . Piwik::translate('General_ExceptionNotSupportedBrowserTitle') . "

"; + $message .= "

" . Piwik::translate('General_ExceptionNotSupportedBrowserText') . "

"; + + $exception = new NotSupportedBrowserException($message); + $exception->setIsHtmlMessage(); + + throw $exception; + } +} diff --git a/core/TCPDF.php b/core/TCPDF.php new file mode 100644 index 0000000000000000000000000000000000000000..5d3fe1d56decd19fd1d8bdf5e12f5579fcc62d66 --- /dev/null +++ b/core/TCPDF.php @@ -0,0 +1,87 @@ +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; + } +} diff --git a/core/Theme.php b/core/Theme.php new file mode 100644 index 0000000000000000000000000000000000000000..d613ad50ef930e8441a2da1907df6f0a9fd37cf3 --- /dev/null +++ b/core/Theme.php @@ -0,0 +1,166 @@ +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 + '~'; + + /** + * @var Environment + */ + private $twig; + + /** + * @var Formatter + */ + private $formatter; + + public function __construct() + { + $loader = $this->getDefaultThemeLoader(); + $this->addPluginNamespaces($loader); + + //get current theme + $manager = Plugin\Manager::getInstance(); + $theme = $manager->getThemeEnabled(); + $loaders = []; + + $this->formatter = new Formatter(); + + //create loader for custom theme to overwrite twig templates + if ($theme && $theme->getPluginName() != \Piwik\Plugin\Manager::DEFAULT_THEME) { + $customLoader = $this->getCustomThemeLoader($theme); + if ($customLoader) { + //make it possible to overwrite plugin templates + $this->addCustomPluginNamespaces($customLoader, $theme->getPluginName()); + $loaders[] = $customLoader; + } + } + + $loaders[] = $loader; + + $chainLoader = new ChainLoader($loaders); + + // Create new Twig Environment and set cache dir + $cache = StaticContainer::get('twig.cache'); + + $this->twig = new Environment( + $chainLoader, + [ + 'debug' => true, // to use {{ dump(var) }} in twig templates + 'strict_variables' => true, // throw an exception if variables are invalid + 'cache' => $cache, + ] + ); + $this->twig->addExtension(new DebugExtension()); + + $this->addFilterTranslate(); + $this->addFilterListings(); + $this->addFilterUrlRewriteWithParameters(); + $this->addFilterSumTime(); + $this->addFilterMoney(); + $this->addFilterTruncate(); + $this->addFilterNotification(); + $this->addFilterPercent(); + $this->addFilterPercentage(); + $this->addFilterPercentEvolution(); + $this->addFilterPrettyDate(); + $this->addFilterSafeDecodeRaw(); + $this->addFilterNumber(); + $this->addFilterAnonymiseSystemInfo(); + $this->addFilterNonce(); + $this->addFilterMd5(); + $this->addFilterOnlyDomain(); + $this->addFilterSafelink(); + $this->addFilterTrackMatomoLink(); + $this->addFilterImplode(); + $this->addFilterPreventLinking(); + $this->twig->addFilter(new TwigFilter('ucwords', 'ucwords')); + $this->twig->addFilter(new TwigFilter('lcfirst', 'lcfirst')); + $this->twig->addFilter(new TwigFilter('ucfirst', 'ucfirst')); + $this->twig->addFilter(new TwigFilter('preg_replace', function ($subject, $pattern, $replacement) { + return preg_replace($pattern, $replacement, $subject); + })); + + $this->addFunctionExternalLink(); + $this->addFunctionExternalRawLink(); + $this->addFunctionIncludeAssets(); + $this->addFunctionLinkTo(); + $this->addFunctionSparkline(); + $this->addFunctionPostEvent(); + $this->addFunctionIsPluginLoaded(); + $this->addFunctionGetJavascriptTranslations(); + + $this->twig->addTokenParser(new RenderTokenParser()); + + $this->addTestFalse(); + $this->addTestTrue(); + $this->addTestEmptyString(); + $this->addTestIsNumeric(); + + $this->twig->addExtension(new EscapeFilter()); + } + + private function addTestFalse(): void + { + $test = new TwigTest( + 'false', + function ($value) { + return false === $value; + } + ); + $this->twig->addTest($test); + } + + private function addTestTrue(): void + { + $test = new TwigTest( + 'true', + function ($value) { + return true === $value; + } + ); + $this->twig->addTest($test); + } + + private function addTestEmptyString(): void + { + $test = new TwigTest( + 'emptyString', + function ($value) { + return '' === $value; + } + ); + $this->twig->addTest($test); + } + + protected function addFunctionGetJavascriptTranslations(): void + { + $getJavascriptTranslations = new TwigFunction( + 'getJavascriptTranslations', + [StaticContainer::get(Translator::class), 'getJavascriptTranslations'] + ); + $this->twig->addFunction($getJavascriptTranslations); + } + + protected function addFunctionIsPluginLoaded(): void + { + $isPluginLoadedFunction = new TwigFunction('isPluginLoaded', function ($pluginName) { + return \Piwik\Plugin\Manager::getInstance()->isPluginLoaded($pluginName); + }); + $this->twig->addFunction($isPluginLoadedFunction); + } + + protected function addFunctionIncludeAssets(): void + { + $includeAssetsFunction = new TwigFunction('includeAssets', function ($params) { + if (!isset($params['type'])) { + throw new Exception("The function includeAssets needs a 'type' parameter."); + } + + $assetType = strtolower($params['type']); + $deferJs = boolval($params['defer'] ?? false); + switch ($assetType) { + case 'css': + return AssetManager::getInstance()->getCssInclusionDirective(); + case 'js': + return AssetManager::getInstance()->getJsInclusionDirective($deferJs); + default: + throw new Exception("The twig function includeAssets 'type' parameter needs to be either 'css' or 'js'."); + } + }); + $this->twig->addFunction($includeAssetsFunction); + } + + protected function addFunctionPostEvent(): void + { + $postEventFunction = new TwigFunction('postEvent', function ($eventName) { + // get parameters to twig function + $params = func_get_args(); + // remove the first value (event name) + array_shift($params); + + // make the first value the string that will get output in the template + // plugins can modify this string + $str = ''; + $params = array_merge([&$str], $params); + + Piwik::postEvent($eventName, $params); + return $str; + }, ['is_safe' => ['html']]); + $this->twig->addFunction($postEventFunction); + } + + protected function addFunctionSparkline(): void + { + $twigEnv = $this->getTwigEnvironment(); + $sparklineFunction = new TwigFunction( + 'sparkline', + /** + * @param string $src + * @return string + */ + function ($src) use ($twigEnv) { + $width = Sparkline::DEFAULT_WIDTH; + $height = Sparkline::DEFAULT_HEIGHT; + return sprintf(Twig::SPARKLINE_TEMPLATE, piwik_escape_filter($twigEnv, $src, 'html_attr'), $width, $height); + }, + ['is_safe' => ['html']] + ); + $this->twig->addFunction($sparklineFunction); + } + + protected function addFunctionLinkTo(): void + { + $urlFunction = new TwigFunction( + 'linkTo', + /** + * @param array $params + * @return string + */ + function ($params) { + return 'index.php' . Url::getCurrentQueryStringWithParametersModified($params); + } + ); + $this->twig->addFunction($urlFunction); + } + + /** + * Build an external link for a URL + * + * Usage: + * externallink(url) + */ + private function addFunctionExternalLink(): void + { + $externalLink = new TwigFunction('externallink', function ($url) { + return Url::getExternalLinkTag($url); + }); + $this->twig->addFunction($externalLink); + } + + private function addFunctionExternalRawLink(): void + { + $externalRawLink = new TwigFunction('externalrawlink', function ($url) { + // Add tracking parameters if a matomo.org link + return Url::addCampaignParametersToMatomoLink($url); + }); + $this->twig->addFunction($externalRawLink); + } + + private function getDefaultThemeLoader(): FilesystemLoader + { + $themeDir = Manager::getPluginDirectory(\Piwik\Plugin\Manager::DEFAULT_THEME) . '/templates/'; + $themeLoader = new FilesystemLoader([$themeDir], PIWIK_DOCUMENT_ROOT . DIRECTORY_SEPARATOR); + + return $themeLoader; + } + + /** + * create template loader for a custom theme + */ + protected function getCustomThemeLoader(Plugin $theme): ?FilesystemLoader + { + $pluginsDir = Manager::getPluginDirectory($theme->getPluginName()); + $themeDir = $pluginsDir . '/templates/'; + + if (!file_exists($themeDir)) { + return null; + } + $themeLoader = new FilesystemLoader([$themeDir], PIWIK_DOCUMENT_ROOT . DIRECTORY_SEPARATOR); + + return $themeLoader; + } + + public function getTwigEnvironment(): Environment + { + return $this->twig; + } + + protected function addFilterNotification(): void + { + $twigEnv = $this->getTwigEnvironment(); + $notificationFunction = new TwigFilter('notification', function ($message, $options) use ($twigEnv) { + + $template = '
$value) { + if (ctype_alpha($key)) { + $template .= sprintf('data-%s="%s" ', $key, piwik_escape_filter($twigEnv, $value, 'html_attr')); + } + } + + $template .= '>'; + + if (!empty($options['raw'])) { + $template .= $message; + } else { + $template .= piwik_escape_filter($twigEnv, $message, 'html'); + } + + $template .= '
'; + + return $template; + }, ['is_safe' => ['html']]); + $this->twig->addFilter($notificationFunction); + } + + protected function addFilterSafeDecodeRaw(): void + { + $rawSafeDecoded = new TwigFilter( + 'rawSafeDecoded', + /** + * @param ?string $string + * @return string + */ + function ($string) { + if ($string === null) { + return ''; + } + + $string = str_replace('+', '%2B', $string); + $string = str_replace(' ', html_entity_decode(' ', ENT_COMPAT | ENT_HTML401, 'UTF-8'), $string); + + return SafeDecodeLabel::decodeLabelSafe($string); + }, + ['is_safe' => ['all']] + ); + $this->twig->addFilter($rawSafeDecoded); + } + + protected function addFilterPrettyDate(): void + { + $prettyDate = new TwigFilter('prettyDate', function ($dateString, $period) { + return Period\Factory::build($period, $dateString)->getLocalizedShortString(); + }); + $this->twig->addFilter($prettyDate); + } + + protected function addFilterPercentage(): void + { + $percentage = new TwigFilter('percentage', function ($string, $totalValue, $precision = 1) { + $formatter = NumberFormatter::getInstance(); + return $formatter->formatPercent(Piwik::getPercentageSafe($string, $totalValue, $precision), $precision); + }); + $this->twig->addFilter($percentage); + } + + protected function addFilterPercent(): void + { + $percentage = new TwigFilter('percent', function ($string, $precision = 1) { + $formatter = NumberFormatter::getInstance(); + return $formatter->formatPercent($string, $precision); + }); + $this->twig->addFilter($percentage); + } + + protected function addFilterPercentEvolution(): void + { + $percentage = new TwigFilter('percentEvolution', function ($string) { + $formatter = NumberFormatter::getInstance(); + return $formatter->formatPercentEvolution($string); + }); + $this->twig->addFilter($percentage); + } + + protected function addFilterNumber(): void + { + $formatter = new TwigFilter('number', function ($string, $minFractionDigits = 0, $maxFractionDigits = 0) { + return piwik_format_number($string, $minFractionDigits, $maxFractionDigits); + }); + $this->twig->addFilter($formatter); + } + + protected function addFilterAnonymiseSystemInfo(): void + { + $formatter = new TwigFilter( + 'anonymiseSystemInfo', + /** + * @param bool|string|null $string + */ + function ($string) { + if ($string === null) { + return ''; + } + if (is_bool($string)) { + return (int)$string; + } + $string = str_replace([PIWIK_DOCUMENT_ROOT, str_replace('/', '\/', PIWIK_DOCUMENT_ROOT)], '$DOC_ROOT', $string); + $string = str_replace([PIWIK_USER_PATH, str_replace('/', '\/', PIWIK_USER_PATH)], '$USER_PATH', $string); + $string = str_replace([PIWIK_INCLUDE_PATH, str_replace('/', '\/', PIWIK_INCLUDE_PATH)], '$INCLUDE_PATH', $string); + + // replace anything token like + $string = preg_replace('/[[:xdigit:]]{31,80}/', 'TOKEN_REPLACED', $string); + + // just in case it was somehow show in a text + if (SettingsPiwik::isMatomoInstalled()) { + $string = str_replace(SettingsPiwik::getPiwikUrl() ?: '', '$MATOMO_URL', $string); + $string = str_replace(SettingsPiwik::getSalt(), '$MATOMO_SALT', $string); + } + return $string; + } + ); + $this->twig->addFilter($formatter); + } + + protected function addFilterNonce(): void + { + $nonce = new TwigFilter('nonce', ['Piwik\\Nonce', 'getNonce']); + $this->twig->addFilter($nonce); + } + + private function addFilterMd5(): void + { + $md5 = new TwigFilter('md5', function ($value) { + return md5($value); + }); + $this->twig->addFilter($md5); + } + + private function addFilterOnlyDomain(): void + { + $domainOnly = new TwigFilter('domainOnly', function ($url) { + $parsed = parse_url($url); + return ($parsed['scheme'] ?? '') . '://' . ($parsed['host'] ?? ''); + }); + $this->twig->addFilter($domainOnly); + } + + protected function addFilterTruncate(): void + { + $truncateFilter = new TwigFilter('truncate', function ($string, $size) { + return piwik_filter_truncate($string, $size); + }); + $this->twig->addFilter($truncateFilter); + } + + protected function addFilterMoney(): void + { + $moneyFilter = new TwigFilter( + 'money', + /** + * @param number|string $amount + * @param string|int $idSite + */ + function ($amount, $idSite) { + return piwik_format_money($amount, $idSite); + } + ); + $this->twig->addFilter($moneyFilter); + } + + protected function addFilterSumTime(): void + { + $formatter = $this->formatter; + $sumtimeFilter = new TwigFilter('sumtime', function ($numberOfSeconds) use ($formatter) { + return $formatter->getPrettyTimeFromSeconds($numberOfSeconds, true); + }); + $this->twig->addFilter($sumtimeFilter); + } + + protected function addFilterUrlRewriteWithParameters(): void + { + $urlRewriteFilter = new TwigFilter('urlRewriteWithParameters', function ($parameters) { + $parameters['updated'] = null; + return Url::getCurrentQueryStringWithParametersModified($parameters); + }); + $this->twig->addFilter($urlRewriteFilter); + } + + protected function addFilterTranslate(): void + { + $translateFilter = new TwigFilter('translate', function ($stringToken) { + if (func_num_args() <= 1) { + $aValues = []; + } else { + $aValues = func_get_args(); + array_shift($aValues); + } + + try { + $stringTranslated = Piwik::translate($stringToken, $aValues); + } catch (Exception $e) { + $stringTranslated = $stringToken; + } + return $stringTranslated; + }); + $this->twig->addFilter($translateFilter); + } + + protected function addFilterListings(): void + { + $andListing = new TwigFilter('andListing', function ($items) { + if (!is_array($items)) { + return $items; // don't do anything if input data is incorrect + } + return StaticContainer::get(Translator::class)->createAndListing($items); + }); + $this->twig->addFilter($andListing); + + $orListing = new TwigFilter('orListing', function ($items) { + if (!is_array($items)) { + return $items; // don't do anything if input data is incorrect + } + return StaticContainer::get(Translator::class)->createOrListing($items); + }); + $this->twig->addFilter($orListing); + } + + private function addPluginNamespaces(FilesystemLoader $loader): void + { + $pluginManager = \Piwik\Plugin\Manager::getInstance(); + $plugins = $pluginManager->getAllPluginsNames(); + + foreach ($plugins as $name) { + $pluginsDir = Manager::getPluginDirectory($name); + $path = sprintf("%s/templates/", $pluginsDir); + if (is_dir($path)) { + $loader->addPath(rtrim($path, '/'), $name); + } + } + } + + /** + * Plugin-Templates can be overwritten by putting identically named templates in plugins/[theme]/templates/plugins/[plugin]/ + */ + private function addCustomPluginNamespaces(FilesystemLoader $loader, string $pluginName): void + { + $pluginManager = \Piwik\Plugin\Manager::getInstance(); + $plugins = $pluginManager->getAllPluginsNames(); + + $pluginsDir = Manager::getPluginDirectory($pluginName); + + foreach ($plugins as $name) { + $path = sprintf("%s/templates/plugins/%s/", $pluginsDir, $name); + if (is_dir($path)) { + $loader->addPath(rtrim($path, '/'), $name); + } + } + } + + private function addFilterSafelink(): void + { + $safelink = new TwigFilter('safelink', function ($url) { + if (!UrlHelper::isLookLikeSafeUrl($url)) { + return ''; + } + return $url; + }); + $this->twig->addFilter($safelink); + } + + /** + * Modify any links to matomo domains to add campaign tracking parameters + * + * Typical usage: + * + * Apply default campaign tracking parameters: + * {{ 'https://matomo.org/faq/123'|trackmatomolink }} + * + * Apply custom campaign tracking parameters: + * {{ 'https://matomo.org/faq/123'|trackmatomolink('SomeCampaign', 'SomeSource', 'SomeMedium') }} + */ + private function addFilterTrackMatomoLink(): void + { + $trackLink = new TwigFilter('trackmatomolink', function ($url, $campaign = null, $source = null, $medium = null) { + return Url::addCampaignParametersToMatomoLink($url, $campaign, $source, $medium); + }); + $this->twig->addFilter($trackLink); + } + + private function addFilterImplode(): void + { + $implode = new TwigFilter('implode', function ($value, $separator) { + return implode($separator, $value); + }); + $this->twig->addFilter($implode); + } + + private function addFilterPreventLinking(): void + { + $preventLinking = new TwigFilter('preventLinking', function ($string) { + while (preg_match('/\w+\.\w+/i', $string, $matches)) { + $string = str_replace($matches[0], str_replace('.', '.', $matches[0]), $string); + } + + return $string; + }, ['is_safe' => ['all']]); + $this->twig->addFilter($preventLinking); + } + + private function addTestIsNumeric(): void + { + $test = new TwigTest( + 'numeric', + function ($value) { + return is_numeric($value); + } + ); + $this->twig->addTest($test); + } +} diff --git a/core/Twig/Extension/EscapeFilter.php b/core/Twig/Extension/EscapeFilter.php new file mode 100644 index 0000000000000000000000000000000000000000..e07312ece84416600736cd267678abc7f41f6737 --- /dev/null +++ b/core/Twig/Extension/EscapeFilter.php @@ -0,0 +1,34 @@ + true, 'is_safe_callback' => 'twig_escape_filter_is_safe']), + new TwigFilter('escape', '\Piwik\piwik_escape_filter', ['needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe']), + ]; + } + + /** + * Returns the name of the extension. + * + * @return string The extension name + */ + public function getName() + { + return 'escaper2'; + } +} diff --git a/core/Unzip.php b/core/Unzip.php new file mode 100644 index 0000000000000000000000000000000000000000..77355d505758bdffb1fa88237c3569b1a1632f19 --- /dev/null +++ b/core/Unzip.php @@ -0,0 +1,57 @@ + $lastTimeChecked + ) { + // set the time checked first, so that parallel Piwik requests don't all trigger the http requests + Option::set(self::LAST_TIME_CHECKED, time(), $autoLoad = 1); + + $latestVersion = self::getLatestAvailableVersionNumber(); + $latestVersion = trim((string) $latestVersion); + if (!preg_match('~^[0-9][0-9a-zA-Z_.-]*$~D', $latestVersion)) { + $latestVersion = ''; + } + + $hasLastCheckFailed = '' === $latestVersion; + + Option::set(self::LAST_CHECK_FAILED, $hasLastCheckFailed); + + if ($hasLastCheckFailed) { + // retry check on next request if previous attempt failed + Option::set(self::LAST_TIME_CHECKED, $lastTimeChecked, $autoLoad = 1); + } else { + Option::set(self::LATEST_VERSION, $latestVersion); + } + } + } + + /** + * Get the latest available version number for the currently active release channel. Eg '2.15.0-b4' or '2.15.0'. + * Should return a semantic version number in format MAJOR.MINOR.PATCH (https://semver.org/). + * Returns an empty string in case one cannot connect to the remote server. + * @return string + */ + private static function getLatestAvailableVersionNumber() + { + $releaseChannels = StaticContainer::get('\Piwik\Plugin\ReleaseChannels'); + $channel = $releaseChannels->getActiveReleaseChannel(); + $url = $channel->getUrlToCheckForLatestAvailableVersion(); + + try { + $latestVersion = Http::sendHttpRequest($url, self::SOCKET_TIMEOUT); + } catch (\Exception $e) { + // e.g., disable_functions = fsockopen; allow_url_open = Off + $latestVersion = ''; + } + + return $latestVersion; + } + + /** + * Returns the latest available version number. Does not perform a check whether a later version is available. + * + * @return false|string + */ + public static function getLatestVersion() + { + return Option::get(self::LATEST_VERSION); + } + + /** + * Returns whether the last update check was flagged as having failed or not. + */ + public static function hasLastCheckFailed(): bool + { + return (bool) Option::get(self::LAST_CHECK_FAILED); + } + + /** + * Returns version number of a newer Piwik release. + * + * @return string|bool false if current version is the latest available, + * or the latest version number if a newest release is available + */ + public static function isNewestVersionAvailable() + { + $latestVersion = self::getLatestVersion(); + if ( + !empty($latestVersion) + && version_compare(Version::VERSION, $latestVersion) == -1 + ) { + return $latestVersion; + } + return false; + } +} diff --git a/core/UpdateCheck/ReleaseChannel.php b/core/UpdateCheck/ReleaseChannel.php new file mode 100644 index 0000000000000000000000000000000000000000..e93d1c80c8ab9abbecc89412ea963ba853e689f1 --- /dev/null +++ b/core/UpdateCheck/ReleaseChannel.php @@ -0,0 +1,89 @@ +pathUpdateFileCore = $pathUpdateFileCore ?: PIWIK_INCLUDE_PATH . '/core/Updates/'; + + if ($pathUpdateFilePlugins) { + $this->pathUpdateFilePlugins = $pathUpdateFilePlugins; + } else { + $this->pathUpdateFilePlugins = null; + } + + $this->columnsUpdater = $columnsUpdater ?: new Columns\Updater(); + + self::$activeInstance = $this; + } + + /** + * Adds an UpdateObserver to the internal list of listeners. + */ + public function addUpdateObserver(UpdateObserver $listener) + { + $this->updateObservers[] = $listener; + } + + /** + * Marks a component as successfully updated to a specific version in the database. Sets an option + * that looks like `"version_$componentName"`. + * + * @param string $name The component name. Eg, a plugin name, `'core'` or dimension column name. + * @param string $version The component version (should use semantic versioning). + * @param bool $isNew indicates if the component is a new one (for plugins) + */ + public function markComponentSuccessfullyUpdated($name, $version, $isNew = false) + { + try { + Option::set(self::getNameInOptionTable($name), $version, $autoLoad = 1); + } catch (\Exception $e) { + // case when the option table is not yet created (before 0.2.10) + } + + if ($isNew) { + + /** + * Event triggered after a new component has been installed. + * + * @param string $name The component that has been installed. + */ + Piwik::postEvent('Updater.componentInstalled', array($name)); + + return; + } + + /** + * Event triggered after a component has been updated. + * + * Can be used to handle logic that should be done after a component was updated + * + * **Example** + * + * Piwik::addAction('Updater.componentUpdated', function ($componentName, $updatedVersion) { + * $mail = new Mail(); + * $mail->setDefaultFromPiwik(); + * $mail->addTo('test@example.org'); + * $mail->setSubject('Component was updated); + * $message = sprintf( + * 'Component %1$s has been updated to version %2$s', + * $componentName, $updatedVersion + * ); + * $mail->setBodyText($message); + * $mail->send(); + * }); + * + * @param string $componentName 'core', plugin name or dimension name + * @param string $updatedVersion version updated to + */ + Piwik::postEvent('Updater.componentUpdated', array($name, $version)); + } + + /** + * Marks a component as successfully uninstalled. Deletes an option + * that looks like `"version_$componentName"`. + * + * @param string $name The component name. Eg, a plugin name, `'core'` or dimension column name. + */ + public function markComponentSuccessfullyUninstalled($name) + { + try { + Option::delete(self::getNameInOptionTable($name)); + } catch (\Exception $e) { + // case when the option table is not yet created (before 0.2.10) + } + + /** + * Event triggered after a component has been uninstalled. + * + * @param string $name The component that has been uninstalled. + */ + Piwik::postEvent('Updater.componentUninstalled', array($name)); + } + + /** + * Returns the currently installed version of a Piwik component. + * + * @param string $name The component name. Eg, a plugin name, `'core'` or dimension column name. + * @return string|false A semantic version, or false if the component version is not recorded yet. + */ + public function getCurrentComponentVersion($name) + { + try { + $currentVersion = Option::get(self::getNameInOptionTable($name)); + } catch (\Exception $e) { + // mysql error 1146: table doesn't exist + if (Db::get()->isErrNo($e, '1146')) { + // case when the option table is not yet created (before 0.2.10) + $currentVersion = false; + } else { + // failed for some other reason + throw $e; + } + } + + return $currentVersion; + } + + /** + * Returns a list of components (core | plugin) that need to run through the upgrade process. + * + * @param string[] $componentsToCheck An array mapping component names to the latest locally available version. + * If the version is later than the currently installed version, the component + * must be upgraded. + * + * Example: `array('core' => '2.11.0')` + * @return array( componentName => array( file1 => version1, [...]), [...]) + */ + public function getComponentsWithUpdateFile($componentsToCheck) + { + $this->componentsWithNewVersion = $this->getComponentsWithNewVersion($componentsToCheck); + $this->componentsWithUpdateFile = $this->loadComponentsWithUpdateFile(); + return $this->componentsWithUpdateFile; + } + + /** + * Component has a new version? + * + * @param string $componentName + * @return bool TRUE if component is to be updated; FALSE if not + */ + public function hasNewVersion($componentName) + { + return isset($this->componentsWithNewVersion[$componentName]); + } + + /** + * Does one of the new versions involve a major database update? + * Note: getSqlQueriesToExecute() must be called before this method! + * + * @return bool + */ + public function hasMajorDbUpdate() + { + return $this->hasMajorDbUpdate; + } + + /** + * Returns the list of SQL queries that would be executed during the update + * + * @return Migration[] of SQL queries + * @throws \Exception + */ + public function getSqlQueriesToExecute() + { + $queries = []; + $classNames = []; + + foreach ($this->componentsWithUpdateFile as $componentName => $componentUpdateInfo) { + foreach ($componentUpdateInfo as $file => $fileVersion) { + require_once $file; // prefixed by PIWIK_INCLUDE_PATH + + $className = $this->getUpdateClassName($componentName, $fileVersion); + if (!class_exists($className, false)) { + // throwing an error here causes Matomo to show the safe mode instead of showing an exception fatal only + // that makes it possible to deactivate / uninstall a broken plugin to recover Matomo directly + throw new \Error("The class $className was not found in $file"); + } + + if (in_array($className, $classNames)) { + continue; // prevent from getting updates from Piwik\Columns\Updater multiple times + } + + $classNames[] = $className; + + /* + * Fetch available migrations as super user, to ensure having access to everything. + * Otherwise migrations iterating e.g. over available sites or similar, might only update those the + * current user has permission for. + */ + $migrationsForComponent = Access::doAsSuperUser(function () use ($className) { + /** @var Updates $update */ + $update = StaticContainer::getContainer()->make($className); + return $update->getMigrations($this); + }); + foreach ($migrationsForComponent as $index => $migration) { + $migration = $this->keepBcForOldMigrationQueryFormat($index, $migration); + $queries[] = $migration; + } + $this->hasMajorDbUpdate = $this->hasMajorDbUpdate || call_user_func([$className, 'isMajorUpdate']); + } + } + return $queries; + } + + public function getUpdateClassName($componentName, $fileVersion) + { + $suffix = strtolower(str_replace(array('-', '.'), '_', $fileVersion)); + $className = 'Updates_' . $suffix; + + if ($componentName == 'core') { + return '\\Piwik\\Updates\\' . $className; + } + + if (ColumnUpdater::isDimensionComponent($componentName)) { + return '\\Piwik\\Columns\\Updater'; + } + + return '\\Piwik\\Plugins\\' . $componentName . '\\' . $className; + } + + /** + * Update the named component + * + * @param string $componentName 'core', or plugin name + * @throws \Exception|UpdaterErrorException + * @return array of warning strings if applicable + */ + public function update($componentName) + { + $warningMessages = array(); + + $this->executeListenerHook('onComponentUpdateStarting', array($componentName)); + + foreach ($this->componentsWithUpdateFile[$componentName] as $file => $fileVersion) { + try { + require_once $file; // prefixed by PIWIK_INCLUDE_PATH + + $className = $this->getUpdateClassName($componentName, $fileVersion); + if ( + !in_array($className, $this->updatedClasses) + && class_exists($className, false) + ) { + $this->executeListenerHook('onComponentUpdateFileStarting', array($componentName, $file, $className, $fileVersion)); + + $this->executeSingleUpdateClass($className); + + $this->executeListenerHook('onComponentUpdateFileFinished', array($componentName, $file, $className, $fileVersion)); + + // makes sure to call Piwik\Columns\Updater only once as one call updates all dimensions at the same + // time for better performance + $this->updatedClasses[] = $className; + } + + $this->markComponentSuccessfullyUpdated($componentName, $fileVersion); + } catch (UpdaterErrorException $e) { + $this->executeListenerHook('onError', array($componentName, $fileVersion, $e)); + throw $e; + } catch (\Exception $e) { + $warningMessages[] = $e->getMessage(); + + $this->executeListenerHook('onWarning', array($componentName, $fileVersion, $e)); + } + } + + // to debug, create core/Updates/X.php, update the core/Version.php, throw an Exception in the try, and comment the following lines + $updatedVersion = $this->componentsWithNewVersion[$componentName][self::INDEX_NEW_VERSION]; + $this->markComponentSuccessfullyUpdated($componentName, $updatedVersion); + + $this->executeListenerHook('onComponentUpdateFinished', array($componentName, $updatedVersion, $warningMessages)); + ServerFilesGenerator::createFilesForSecurity(); + return $warningMessages; + } + + /** + * Construct list of update files for the outdated components + * + * @return array( componentName => array( file1 => version1, [...]), [...]) + */ + private function loadComponentsWithUpdateFile() + { + $componentsWithUpdateFile = array(); + + foreach ($this->componentsWithNewVersion as $name => $versions) { + $currentVersion = $versions[self::INDEX_CURRENT_VERSION]; + $newVersion = $versions[self::INDEX_NEW_VERSION]; + + if ($name == 'core') { + $pathToUpdates = $this->pathUpdateFileCore . '*.php'; + } elseif (ColumnUpdater::isDimensionComponent($name)) { + $componentsWithUpdateFile[$name][PIWIK_INCLUDE_PATH . '/core/Columns/Updater.php'] = $newVersion; + } else { + if ($this->pathUpdateFilePlugins) { + $pathToUpdates = sprintf($this->pathUpdateFilePlugins, $name) . '*.php'; + } else { + $pathToUpdates = Manager::getPluginDirectory($name) . '/Updates/*.php'; + } + } + + if (!empty($pathToUpdates)) { + $files = _glob($pathToUpdates); + if ($files == false) { + $files = array(); + } + + foreach ($files as $file) { + $fileVersion = basename($file, '.php'); + if ( +// if the update is from a newer version + version_compare($currentVersion, $fileVersion) == -1 + // but we don't execute updates from non existing future releases + && version_compare($fileVersion, $newVersion) <= 0 + ) { + $componentsWithUpdateFile[$name][$file] = $fileVersion; + } + } + } + + if (isset($componentsWithUpdateFile[$name])) { + // order the update files by version asc + uasort($componentsWithUpdateFile[$name], "version_compare"); + } else { + // there are no update file => nothing to do, update to the new version is successful + $this->markComponentSuccessfullyUpdated($name, $newVersion); + } + } + + return $componentsWithUpdateFile; + } + + /** + * Construct list of outdated components + * + * @param string[] $componentsToCheck An array mapping component names to the latest locally available version. + * If the version is later than the currently installed version, the component + * must be upgraded. + * + * Example: `array('core' => '2.11.0')` + * @throws \Exception + * @return array array( componentName => array( oldVersion, newVersion), [...]) + */ + public function getComponentsWithNewVersion($componentsToCheck) + { + $componentsToUpdate = array(); + + // we make sure core updates are processed before any plugin updates + if (isset($componentsToCheck['core'])) { + $coreVersions = $componentsToCheck['core']; + unset($componentsToCheck['core']); + $componentsToCheck = array_merge(array('core' => $coreVersions), $componentsToCheck); + } + + $recordedCoreVersion = $this->getCurrentComponentVersion('core'); + if (empty($recordedCoreVersion)) { + // This should not happen + $recordedCoreVersion = Version::VERSION; + $this->markComponentSuccessfullyUpdated('core', $recordedCoreVersion); + } + + foreach ($componentsToCheck as $name => $version) { + $currentVersion = $this->getCurrentComponentVersion($name); + + if (ColumnUpdater::isDimensionComponent($name)) { + $isComponentOutdated = $currentVersion !== $version; + } else { + // note: when versionCompare == 1, the version in the DB is newer, we choose to ignore + $isComponentOutdated = version_compare($currentVersion, $version) == -1; + } + + if ($isComponentOutdated || $currentVersion === false) { + $componentsToUpdate[$name] = array( + self::INDEX_CURRENT_VERSION => $currentVersion, + self::INDEX_NEW_VERSION => $version, + ); + } + } + + return $componentsToUpdate; + } + + /** + * Updates multiple components, while capturing & returning errors and warnings. + * + * @param string[] $componentsWithUpdateFile Component names mapped with arrays of update files. Same structure + * as the result of `getComponentsWithUpdateFile()`. + * @return array Information about the update process, including: + * + * * **warnings**: The list of warnings that occurred during the update process. + * * **errors**: The list of updater exceptions thrown during individual component updates. + * * **coreError**: True if an exception was thrown while updating core. + * * **deactivatedPlugins**: The list of plugins that were deactivated due to an error in the + * update process. + */ + public function updateComponents($componentsWithUpdateFile) + { + $warnings = array(); + $errors = array(); + $deactivatedPlugins = array(); + $coreError = false; + + try { + $history = Option::get(self::OPTION_KEY_MATOMO_UPDATE_HISTORY); + $history = explode(',', (string) $history); + $previousVersion = Option::get(self::getNameInOptionTable('core')); + + if (!empty($previousVersion) && !in_array($previousVersion, $history, true)) { + // this allows us to see which versions of matomo the user was using before this update so we better understand + // which version maybe regressed something + array_unshift($history, $previousVersion); + $history = array_slice($history, 0, 6); // lets keep only the last 6 versions + Option::set(self::OPTION_KEY_MATOMO_UPDATE_HISTORY, implode(',', $history)); + } + } catch (\Exception $e) { + // case when the option table is not yet created (before 0.2.10) + } + + if (!empty($componentsWithUpdateFile)) { + /* + * Perform updates as super user, so we bypass any permission checks and are able to change anything. + */ + Access::doAsSuperUser(function () use ($componentsWithUpdateFile, &$coreError, &$deactivatedPlugins, &$errors, &$warnings) { + + $pluginManager = \Piwik\Plugin\Manager::getInstance(); + + // if error in any core update, show message + help message + EXIT + // if errors in any plugins updates, show them on screen, disable plugins that errored + CONTINUE + // if warning in any core update or in any plugins update, show message + CONTINUE + // if no error or warning, success message + CONTINUE + foreach ($componentsWithUpdateFile as $name => $filenames) { + try { + $warnings = array_merge($warnings, $this->update($name)); + } catch (UpdaterErrorException $e) { + $errors[] = $e->getMessage(); + if ($name == 'core') { + $coreError = true; + break; + } elseif ($pluginManager->isPluginActivated($name) && $pluginManager->isPluginBundledWithCore($name)) { + $coreError = true; + break; + } elseif ($pluginManager->isPluginActivated($name)) { + $pluginManager->deactivatePlugin($name); + $deactivatedPlugins[] = $name; + } + } + } + }); + } + + Filesystem::deleteAllCacheOnUpdate(); + ServerFilesGenerator::createFilesForSecurity(); + + $result = array( + 'warnings' => $warnings, + 'errors' => $errors, + 'coreError' => $coreError, + 'deactivatedPlugins' => $deactivatedPlugins, + ); + + /** + * Triggered after Piwik has been updated. + */ + Piwik::postEvent('CoreUpdater.update.end'); + + return $result; + } + + /** + * Returns any updates that should occur for core and all plugins that are both loaded and + * installed. Also includes updates required for dimensions. + * + * @return array|null Returns the result of `getComponentsWithUpdateFile()`. + */ + public function getComponentUpdates() + { + $componentsToCheck = array( + 'core' => Version::VERSION, + ); + + $manager = \Piwik\Plugin\Manager::getInstance(); + $plugins = $manager->getLoadedPlugins(); + foreach ($plugins as $pluginName => $plugin) { + if ($manager->isPluginInstalled($pluginName)) { + $componentsToCheck[$pluginName] = $plugin->getVersion(); + } + } + + $columnsVersions = $this->columnsUpdater->getAllVersions($this); + foreach ($columnsVersions as $component => $version) { + $componentsToCheck[$component] = $version; + } + + $componentsWithUpdateFile = $this->getComponentsWithUpdateFile($componentsToCheck); + + if (count($componentsWithUpdateFile) == 0) { + $this->columnsUpdater->onNoUpdateAvailable($columnsVersions); + + return null; + } + + return $componentsWithUpdateFile; + } + + /** + * Execute multiple migration queries from a single Update file. + * + * @param string $file The path to the Updates file. + * @param Migration[] $migrations An array of migrations + * @api + */ + public function executeMigrations($file, $migrations) + { + foreach ($migrations as $index => $migration) { + $migration = $this->keepBcForOldMigrationQueryFormat($index, $migration); + $this->executeMigration($file, $migration); + } + } + + /** + * @param $file + * @throws UpdaterErrorException + * @api + */ + public function executeMigration($file, Migration $migration) + { + try { + $this->executeListenerHook('onStartExecutingMigration', array($file, $migration)); + + $migration->exec(); + } catch (\Exception $e) { + if (!$migration->shouldIgnoreError($e)) { + $message = sprintf( + "%s:\nError trying to execute the migration '%s'.\nThe error was: %s", + $file, + $migration->__toString(), + $e->getMessage() + ); + throw new UpdaterErrorException($message); + } + } + + $this->executeListenerHook('onFinishedExecutingMigration', array($file, $migration)); + } + + private function executeListenerHook($hookName, $arguments) + { + foreach ($this->updateObservers as $listener) { + call_user_func_array(array($listener, $hookName), $arguments); + } + } + + private function executeSingleUpdateClass($className) + { + $update = StaticContainer::getContainer()->make($className); + try { + call_user_func(array($update, 'doUpdate'), $this); + } catch (\Exception $e) { + // if an Update file executes PHP statements directly, DB exceptions be handled by executeSingleMigrationQuery, so + // make sure to check for them here + if ($e instanceof Zend_Db_Exception) { + throw new UpdaterErrorException($e->getMessage(), $e->getCode(), $e); + } elseif ($e instanceof MissingFilePermissionException) { + throw new UpdaterErrorException($e->getMessage(), $e->getCode(), $e); + }{ + throw $e; + } + } + } + + private function keepBcForOldMigrationQueryFormat($index, $migration) + { + if (!is_object($migration)) { + // keep BC for old format (pre 3.0): array($sqlQuery => $errorCodeToIgnore) + $migrationFactory = StaticContainer::get('Piwik\Updater\Migration\Factory'); + $migration = $migrationFactory->db->sql($index, $migration); + } + + return $migration; + } + + /** + * Record version of successfully completed component update + * + * @param string $name + * @param string $version + */ + public static function recordComponentSuccessfullyUpdated($name, $version) + { + self::$activeInstance->markComponentSuccessfullyUpdated($name, $version); + } + + /** + * Returns the flag name to use in the option table to record current schema version + * @param string $name + * @return string + */ + private static function getNameInOptionTable($name) + { + return 'version_' . $name; + } +} diff --git a/core/Updater/Migration.php b/core/Updater/Migration.php new file mode 100644 index 0000000000000000000000000000000000000000..db91b1272209d4537d21500fdbad22a6882c0b2b --- /dev/null +++ b/core/Updater/Migration.php @@ -0,0 +1,44 @@ +container = StaticContainer::getContainer(); + } + + /** + * Sets a configuration to the Matomo config file + * + * @param string $section + * @param string $key + * @param scalar|scalar[] $value + * @return Set + */ + public function set($section, $key, $value) + { + return $this->container->make('Piwik\Updater\Migration\Config\Set', array( + 'section' => $section, + 'key' => $key, + 'value' => $value, + )); + } +} diff --git a/core/Updater/Migration/Config/Set.php b/core/Updater/Migration/Config/Set.php new file mode 100644 index 0000000000000000000000000000000000000000..cfb7d86f0736065c294c28a107cbf26841dcabe1 --- /dev/null +++ b/core/Updater/Migration/Config/Set.php @@ -0,0 +1,63 @@ +section = $section; + $this->key = $key; + $this->value = $value; + } + + public function __toString() + { + $domain = Config::getLocalConfigPath() == Config::getDefaultLocalConfigPath() ? '' : Config::getHostname(); + $domainArg = !empty($domain) ? "--matomo-domain=\"$domain\" " : ''; + + if (is_array($this->value)) { + $assignment = sprintf('%s.%s=%s', $this->section, $this->key, json_encode($this->value)); + $assignment = str_replace("'", "'\"'\"'", $assignment); + return sprintf("./console %sconfig:set '%s'", $domainArg, $assignment); + } + + return sprintf('./console %sconfig:set --section="%s" --key="%s" --value="%s"', $domainArg, $this->section, $this->key, $this->value); + } + + public function exec() + { + $config = Config::getInstance(); + $config->{$this->section}[$this->key] = $this->value; + $config->forceSave(); + } +} diff --git a/core/Updater/Migration/Custom.php b/core/Updater/Migration/Custom.php new file mode 100644 index 0000000000000000000000000000000000000000..4c381084363a3f129bd1e7ab751b185c815b6bee --- /dev/null +++ b/core/Updater/Migration/Custom.php @@ -0,0 +1,46 @@ +callback = $callback; + $this->toString = $toString; + $this->args = $args; + } + + public function exec() + { + call_user_func_array($this->callback, $this->args); + } + + public function __toString() + { + return $this->toString; + } + + public function shouldIgnoreError($exception) + { + return false; + } +} diff --git a/core/Updater/Migration/Db.php b/core/Updater/Migration/Db.php new file mode 100644 index 0000000000000000000000000000000000000000..07d2ff8986602f9de78a8e66c93f2ad95821b08e --- /dev/null +++ b/core/Updater/Migration/Db.php @@ -0,0 +1,105 @@ +getColumns($table); + } catch (\Exception $ex) { + $existingColumns = []; + } + + $changes = array(); + foreach ($columns as $columnName => $columnType) { + if (in_array($columnName, $existingColumns)) { + continue; + } + + $part = sprintf("ADD COLUMN `%s` %s", $columnName, $columnType); + + if (!empty($placeColumnAfter)) { + $part .= sprintf(' AFTER `%s`', $placeColumnAfter); + $placeColumnAfter = $columnName; + } + + $changes[] = $part; + } + + if (Schema::getInstance()->supportsComplexColumnUpdates()) { + $sql = sprintf("ALTER TABLE `%s` %s", $table, implode(', ', $changes)); + + parent::__construct($sql, static::ERROR_CODE_DUPLICATE_COLUMN); + } else { + $queriesToPerform = []; + + foreach ($changes as $change) { + $queriesToPerform[] = sprintf("ALTER TABLE `%s` %s", $table, $change); + } + + parent::__construct(implode(';', $queriesToPerform), static::ERROR_CODE_DUPLICATE_COLUMN); + } + } +} diff --git a/core/Updater/Migration/Db/AddIndex.php b/core/Updater/Migration/Db/AddIndex.php new file mode 100644 index 0000000000000000000000000000000000000000..07ca8a697b22b15395cbaa6edd0e5d053b8e3d34 --- /dev/null +++ b/core/Updater/Migration/Db/AddIndex.php @@ -0,0 +1,53 @@ + "column_name(10)" + preg_match('/^([\w]+)(\(?\d*\)?)$/', $columnName, $matches); // match "column_name" and "column_name(10)" + + $nameOnly = $matches[1]; // eg "column_name" + $columnNamesOnly[] = $nameOnly; + $column = "`$nameOnly`"; + if (!empty($matches[2])) { + $column .= ' ' . $matches[2]; // eg "(10)" + } + + $columns[] = $column; + } + + if (empty($indexName)) { + $indexName = $this->indexNamePrefix . '_' . implode('_', $columnNamesOnly); + } + + $sql = sprintf("ALTER TABLE `%s` ADD %s %s (%s)", $table, $this->indexType, $indexName, implode(', ', $columns)); + + parent::__construct($sql, array(static::ERROR_CODE_DUPLICATE_KEY, static::ERROR_CODE_KEY_COLUMN_NOT_EXISTS)); + } +} diff --git a/core/Updater/Migration/Db/AddPrimaryKey.php b/core/Updater/Migration/Db/AddPrimaryKey.php new file mode 100644 index 0000000000000000000000000000000000000000..e42b65c240bc5cb6370f2442fef24937a4fd6816 --- /dev/null +++ b/core/Updater/Migration/Db/AddPrimaryKey.php @@ -0,0 +1,29 @@ +table = $table; + $this->columnNames = $columnNames; + $this->values = $values; + $this->throwException = (bool) $throwException; + $this->charset = $charset; + } + + public function shouldIgnoreError($exception) + { + return false; + } + + public function __toString() + { + return ''; + } + + public function exec() + { + Db\BatchInsert::tableInsertBatch($this->table, $this->columnNames, $this->values, $this->throwException, $this->charset); + } + + public function getColumnNames() + { + return $this->columnNames; + } + + /** + * @return string + */ + public function getTable() + { + return $this->table; + } + + /** + * @return array + */ + public function getValues() + { + return $this->values; + } + + /** + * @return boolean + */ + public function doesThrowException() + { + return $this->throwException; + } + + /** + * @return string + */ + public function getCharset() + { + return $this->charset; + } +} diff --git a/core/Updater/Migration/Db/BoundSql.php b/core/Updater/Migration/Db/BoundSql.php new file mode 100644 index 0000000000000000000000000000000000000000..376a50a066f534ee399017faf5fc2ed4d694448e --- /dev/null +++ b/core/Updater/Migration/Db/BoundSql.php @@ -0,0 +1,55 @@ +bind = (array) $bind; + } + + public function __toString() + { + $sql = parent::__toString(); + + foreach ($this->bind as $value) { + if (!is_int($value) && !is_float($value)) { + $value = "'" . addcslashes($value, "\000\n\r\\'\"\032") . "'"; + } + $sql = substr_replace($sql, $value, $pos = strpos($sql, '?'), $len = 1); + } + + return $sql; + } + + public function exec() + { + Db::query($this->sql, $this->bind); + } +} diff --git a/core/Updater/Migration/Db/ChangeColumn.php b/core/Updater/Migration/Db/ChangeColumn.php new file mode 100644 index 0000000000000000000000000000000000000000..06f4c62e4083abe5729d2a39ec4cf900c40bfbdc --- /dev/null +++ b/core/Updater/Migration/Db/ChangeColumn.php @@ -0,0 +1,24 @@ + $columnType) { + $changes[] = sprintf("CHANGE `%s` `%s` %s", $columnName, $columnName, $columnType); + } + + $sql = sprintf("ALTER TABLE `%s` %s", $table, implode(', ', $changes)); + + parent::__construct($sql, static::ERROR_CODE_UNKNOWN_COLUMN); + } +} diff --git a/core/Updater/Migration/Db/CreateTable.php b/core/Updater/Migration/Db/CreateTable.php new file mode 100644 index 0000000000000000000000000000000000000000..e0f2d090ff50cc846a53de33542a234e41716297 --- /dev/null +++ b/core/Updater/Migration/Db/CreateTable.php @@ -0,0 +1,45 @@ + columnType) + * @param string|string[] $primaryKey one or multiple columns that define the primary key + */ + public function __construct($table, $columnNames, $primaryKey) + { + $columns = array(); + foreach ($columnNames as $column => $type) { + $columns[] = sprintf('`%s` %s', $column, $type); + } + + if (!empty($primaryKey)) { + $columns[] = sprintf('PRIMARY KEY ( `%s` )', implode('`, `', $primaryKey)); + } + + $sql = sprintf( + 'CREATE TABLE `%s` (%s) %s', + $table, + implode(', ', $columns), + Schema::getInstance()->getTableCreateOptions() + ); + + parent::__construct($sql, static::ERROR_CODE_TABLE_EXISTS); + } +} diff --git a/core/Updater/Migration/Db/DropColumn.php b/core/Updater/Migration/Db/DropColumn.php new file mode 100644 index 0000000000000000000000000000000000000000..996f6b21c310074a6ce9b846ff10d4be3fe58a9b --- /dev/null +++ b/core/Updater/Migration/Db/DropColumn.php @@ -0,0 +1,24 @@ +container = StaticContainer::getContainer(); + } + + /** + * Performs a custom SQL query during the update. + * + * Example: + * $factory->sql("DELETE * FROM table_name WHERE plugin_name = 'MyPluginName'"); + * + * @param string $sql The SQL query that should be executed. Make sure to prefix a table name via + * {@link Piwik\Commin::prefixTable()}. + * @param int|int[] $errorCodesToIgnore Any given MySQL server error code will be ignored. For a list of all + * possible error codes have a look at {@link \Piwik\Updater\Migration\Db}. + * If no error should be ignored use an empty array or `false`. + * @return Sql + */ + public function sql($sql, $errorCodesToIgnore = array()) + { + if ($errorCodesToIgnore === false) { + $errorCodesToIgnore = array(); + } + + return $this->container->make('Piwik\Updater\Migration\Db\Sql', array( + 'sql' => $sql, 'errorCodesToIgnore' => $errorCodesToIgnore, + )); + } + + /** + * Performs a custom SQL query that uses bound parameters during the update. + * + * You can replace values with a question mark and then pass the actual value via `$bind` for better security. + * + * Example: + * $factory->boundSql('DELETE * FROM table_name WHERE idsite = ?, array($idSite = 1)); + * + * @param string $sql The SQL query that should be executed. Make sure to prefix a table name via + * {@link Piwik\Commin::prefixTable()}. + * @param array $bind An array of values that need to be replaced with the question marks in the SQL query. + * @param int|int[] $errorCodesToIgnore Any given MySQL server error code will be ignored. For a list of all + * possible error codes have a look at {@link \Piwik\Updater\Migration\Db}. + * If no error should be ignored use `false`. + * @return BoundSql + */ + public function boundSql($sql, $bind, $errorCodesToIgnore = array()) + { + if ($errorCodesToIgnore === false) { + $errorCodesToIgnore = array(); + } + + return $this->container->make('Piwik\Updater\Migration\Db\BoundSql', array( + 'sql' => $sql, 'errorCodesToIgnore' => $errorCodesToIgnore, 'bind' => $bind, + )); + } + + /** + * Creates a new database table. + * @param string $table Unprefixed database table name, eg 'log_visit'. + * @param array $columnNames An array of column names and their type they should use. For example: + * array('column_name_1' => 'VARCHAR(200) NOT NULL', 'column_name_2' => 'INT(10) DEFAULT 0') + * @param string|string[] $primaryKey Optional. One or multiple columns that shall define the primary key. + * @return CreateTable + */ + public function createTable($table, $columnNames, $primaryKey = array()) + { + $table = $this->prefixTable($table); + + if (!empty($primaryKey) && !is_array($primaryKey)) { + $primaryKey = array($primaryKey); + } + + return $this->container->make('Piwik\Updater\Migration\Db\CreateTable', array( + 'table' => $table, 'columnNames' => $columnNames, 'primaryKey' => $primaryKey, + )); + } + + /** + * Drops an existing database table. + * @param string $table Unprefixed database table name, eg 'log_visit'. + * @return DropTable + */ + public function dropTable($table) + { + $table = $this->prefixTable($table); + + return $this->container->make('Piwik\Updater\Migration\Db\DropTable', array( + 'table' => $table, + )); + } + + /** + * Adds a new database table column to an existing table. + * + * @param string $table Unprefixed database table name, eg 'log_visit'. + * @param string $columnName The name of the column that shall be added, eg 'my_column_name'. + * @param string $columnType The column type it should have, eg 'VARCHAR(200) NOT NULL'. + * @param string|null $placeColumnAfter If specified, the added column will be added after this specified column + * name. If you specify a column be sure it actually exists and can be added + * after this column. + * @return AddColumn + */ + public function addColumn($table, $columnName, $columnType, $placeColumnAfter = null) + { + $table = $this->prefixTable($table); + + return $this->container->make('Piwik\Updater\Migration\Db\AddColumn', array( + 'table' => $table, 'columnName' => $columnName, 'columnType' => $columnType, 'placeColumnAfter' => $placeColumnAfter, + )); + } + + /** + * Adds multiple new database table columns to an existing table at once. + * + * Adding multiple columns at the same time can lead to performance improvements compared to adding each new column + * separately. + * + * @param string $table Unprefixed database table name, eg 'log_visit'. + * @param array $columns An array of column name to column type pairs, + * eg array('my_column_name' => 'VARCHAR(200) NOT NULL', 'column2' => '...') + * @param string|null $placeColumnAfter If specified, the first added column will be added after this specified column + * name. All following columns will be added after the previous specified in + * $columns. If you specify a column be sure it actually exists and can be added + * after this column. + * @return AddColumns + */ + public function addColumns($table, $columns, $placeColumnAfter = null) + { + $table = $this->prefixTable($table); + + return $this->container->make('Piwik\Updater\Migration\Db\AddColumns', array( + 'table' => $table, 'columns' => $columns, 'placeColumnAfter' => $placeColumnAfter, + )); + } + + /** + * Drops an existing database table column. + * + * @param string $table Unprefixed database table name, eg 'log_visit'. + * @param string $columnName The name of the column that shall be dropped, eg 'my_column_name'. + * @return DropColumn + */ + public function dropColumn($table, $columnName) + { + $table = $this->prefixTable($table); + + return $this->container->make('Piwik\Updater\Migration\Db\DropColumn', array( + 'table' => $table, 'columnName' => $columnName, + )); + } + + /** + * Drops an existing database table column. + * + * @param string $table Unprefixed database table name, eg 'log_visit'. + * @param array $columnNames An array of column names that should be dropped eg ['column1', 'column2']. + * @return DropColumns + */ + public function dropColumns($table, $columnNames) + { + $table = $this->prefixTable($table); + + return $this->container->make('Piwik\Updater\Migration\Db\DropColumns', array( + 'tableName' => $table, 'columnNames' => $columnNames, + )); + } + + /** + * Changes the column name and column type of an existing database table column. + * + * @param string $table Unprefixed database table name, eg 'log_visit'. + * @param string $oldColumnName The current name of the column that shall be renamed/changed, eg 'column_name'. + * @param string $newColumnName The new name of the column, eg 'new_column_name'. + * @param string $columnType The updated type the new column should have, eg 'VARCHAR(200) NOT NULL'. + * + * @return ChangeColumn + */ + public function changeColumn($table, $oldColumnName, $newColumnName, $columnType) + { + $table = $this->prefixTable($table); + + return $this->container->make('Piwik\Updater\Migration\Db\ChangeColumn', array( + 'table' => $table, 'oldColumnName' => $oldColumnName, + 'newColumnName' => $newColumnName, 'columnType' => $columnType, + )); + } + + /** + * Changes the type of an existing database table column. + * + * @param string $table Unprefixed database table name, eg 'log_visit'. + * @param string $columnName The name of the column that shall be changed, eg 'my_column_name'. + * @param string $columnType The updated type the column should have, eg 'VARCHAR(200) NOT NULL'. + * + * @return ChangeColumnType + */ + public function changeColumnType($table, $columnName, $columnType) + { + $table = $this->prefixTable($table); + + return $this->container->make('Piwik\Updater\Migration\Db\ChangeColumnType', array( + 'table' => $table, 'columnName' => $columnName, 'columnType' => $columnType, + )); + } + + /** + * Changes the type of multiple existing database table columns at the same time. + * + * Changing multiple columns at the same time can lead to performance improvements compared to changing the type + * of each column separately. + * + * @param string $table Unprefixed database table name, eg 'log_visit'. + * @param array $columns An array of column name to column type pairs, + * eg array('my_column_name' => 'VARCHAR(200) NOT NULL', 'column2' => '...') + * + * @return ChangeColumnTypes + */ + public function changeColumnTypes($table, $columns) + { + $table = $this->prefixTable($table); + + return $this->container->make('Piwik\Updater\Migration\Db\ChangeColumnTypes', array( + 'table' => $table, 'columns' => $columns, + )); + } + + /** + * Adds an index to an existing database table. + * + * This is equivalent to an `ADD INDEX indexname (column_name_1, column_name_2)` in SQL. + * It adds a normal index, no unique index. + * + * Note: If no indexName is specified, it will automatically generate a name for this index if which is basically: + * `'index_' . implode('_', $columnNames)`. If a column name is eg `column1(10)` then only the first part (`column1`) + * will be used. For example when using columns `array('column1', 'column2(10)')` then the index name will be + * `index_column1_column2`. + * + * @param string $table Unprefixed database table name, eg 'log_visit'. + * @param string[]|string $columnNames Either one or multiple column names, eg array('column_name_1', 'column_name_2'). + * A column name can be appended by a number bracket eg "column_name_1(10)". + * @param string $indexName If specified, the given index name will be used instead of the automatically generated one. + * @return AddIndex + */ + public function addIndex($table, $columnNames, $indexName = '') + { + $table = $this->prefixTable($table); + + if (!is_array($columnNames)) { + $columnNames = array($columnNames); + } + + return $this->container->make('Piwik\Updater\Migration\Db\AddIndex', array( + 'table' => $table, 'columnNames' => $columnNames, 'indexName' => $indexName, + )); + } + + /** + * Adds a unique key to an existing database table. + * + * This is equivalent to an `ADD UNIQUE KEY indexname (column_name_1, column_name_2)` in SQL. + * + * Note: If no indexName is specified, it will automatically generate a name for this index if which is basically: + * `'index_' . implode('_', $columnNames)`. If a column name is eg `column1(10)` then only the first part (`column1`) + * will be used. For example when using columns `array('column1', 'column2(10)')` then the index name will be + * `index_column1_column2`. + * + * @param string $table Unprefixed database table name, eg 'log_visit'. + * @param string[]|string $columnNames Either one or multiple column names, eg array('column_name_1', 'column_name_2'). + * A column name can be appended by a number bracket eg "column_name_1(10)". + * @param string $indexName If specified, the given unique key name will be used instead of the automatically generated one. + * @return AddIndex + */ + public function addUniqueKey($table, $columnNames, $indexName = '') + { + $table = $this->prefixTable($table); + + if (!is_array($columnNames)) { + $columnNames = array($columnNames); + } + + return $this->container->make('Piwik\Updater\Migration\Db\AddUniqueKey', array( + 'table' => $table, 'columnNames' => $columnNames, 'indexName' => $indexName, + )); + } + + /** + * Drops an existing index from a database table. + * + * @param string $table Unprefixed database table name, eg 'log_visit'. + * @param string $indexName The name of the index that shall be dropped. + * @return DropIndex + */ + public function dropIndex($table, $indexName) + { + $table = $this->prefixTable($table); + + return $this->container->make('Piwik\Updater\Migration\Db\DropIndex', array( + 'table' => $table, 'indexName' => $indexName, + )); + } + + /** + * Drops an existing index from a database table. + * + * @param string $table Unprefixed database table name, eg 'log_visit'. + * @return DropPrimaryKey + */ + public function dropPrimaryKey($table) + { + $table = $this->prefixTable($table); + + return $this->container->make('Piwik\Updater\Migration\Db\DropPrimaryKey', array( + 'table' => $table, + )); + } + + /** + * Adds a primary key to an existing database table. + * + * This is equivalent to an `ADD PRIMARY KEY(column_name_1, column_name_2)` in SQL. + * + * @param string $table Unprefixed database table name, eg 'log_visit'. + * @param string[]|string $columnNames Either one or multiple column names, eg array('column_name_1', 'column_name_2') + * @return AddPrimaryKey + */ + public function addPrimaryKey($table, $columnNames) + { + $table = $this->prefixTable($table); + if (!is_array($columnNames)) { + $columnNames = array($columnNames); + } + + return $this->container->make('Piwik\Updater\Migration\Db\AddPrimaryKey', array( + 'table' => $table, 'columnNames' => $columnNames, + )); + } + + /** + * Inserts a new record / row into an existing database table. + * + * Make sure to specify all columns that need to be defined in order to insert a value successfully. There could + * be for example columns that are not nullable and therefore need a value. + * + * @param string $table Unprefixed database table name, eg 'log_visit'. + * @param array $columnValuePairs An array containing column => value pairs. For example: + * array('column_name_1' => 'value1', 'column_name_2' => 'value2') + * @return Insert + */ + public function insert($table, $columnValuePairs) + { + $table = $this->prefixTable($table); + + return $this->container->make('Piwik\Updater\Migration\Db\Insert', array( + 'table' => $table, 'columnValuePairs' => $columnValuePairs, + )); + } + + /** + * Performs a batch insert into a specific table using either LOAD DATA INFILE or plain INSERTs, + * as a fallback. On MySQL, LOAD DATA INFILE is 20x faster than a series of plain INSERTs. + * + * Please note that queries for batch inserts are currently not shown to an end user and should therefore not be + * returned in an `Updates::getMigrations` method. Instead it needs to be execute directly in `Updates::doUpdate` + * via `$updater->executeMigration($factory->dbBatchInsert(...));` + * + * @param string $table Unprefixed database table name, eg 'log_visit'. + * @param string[] $columnNames An array of unquoted column names, eg array('column_name1', 'column_name_2') + * @param array $values An array of data to be inserted, eg array(array('row1column1', 'row1column2'),array('row2column1', 'row2column2')) + * @param bool $throwException Whether to throw an exception that was caught while trying LOAD DATA INFILE, or not. + * @param string $charset The charset to use, defaults to utf8 + * @return BatchInsert + */ + public function batchInsert($table, $columnNames, $values, $throwException = false, $charset = 'utf8') + { + $table = $this->prefixTable($table); + + return $this->container->make('Piwik\Updater\Migration\Db\BatchInsert', array( + 'table' => $table, 'columnNames' => $columnNames, 'values' => $values, + 'throwException' => $throwException, 'charset' => $charset, + )); + } + + private function prefixTable($table) + { + return Common::prefixTable($table); + } +} diff --git a/core/Updater/Migration/Db/Insert.php b/core/Updater/Migration/Db/Insert.php new file mode 100644 index 0000000000000000000000000000000000000000..2be41a37e0810231e9bde8ffed52810f4e47c53b --- /dev/null +++ b/core/Updater/Migration/Db/Insert.php @@ -0,0 +1,34 @@ + columnValue) + */ + public function __construct($table, $columnValuePairs) + { + $columns = implode('`, `', array_keys($columnValuePairs)); + $bind = array_values($columnValuePairs); + + $sql = sprintf('INSERT INTO `%s` (`%s`) VALUES (%s)', $table, $columns, Common::getSqlStringFieldsArray($columnValuePairs)); + + parent::__construct($sql, $bind, static::ERROR_CODE_DUPLICATE_ENTRY); + } +} diff --git a/core/Updater/Migration/Db/Sql.php b/core/Updater/Migration/Db/Sql.php new file mode 100644 index 0000000000000000000000000000000000000000..cafb9182b99b44e7f18dd09f9697bae37d6b13e7 --- /dev/null +++ b/core/Updater/Migration/Db/Sql.php @@ -0,0 +1,104 @@ +sql = $sql; + $globalErrorCodesToIgnore = Config::getInstance()->database['ignore_error_codes'] ?? []; + $this->errorCodesToIgnore = array_merge($errorCodesToIgnore, (is_array($globalErrorCodesToIgnore) ? $globalErrorCodesToIgnore : [])); + } + + public function shouldIgnoreError($exception) + { + if (empty($this->errorCodesToIgnore)) { + return false; + } + + foreach ($this->errorCodesToIgnore as $code) { + if (Db::get()->isErrNo($exception, $code)) { + return true; + } + } + + return false; + } + + /** + * @internal + * @param int $errorCode + * @return $this + */ + public function addErrorCodeToIgnore($errorCode) + { + $this->errorCodesToIgnore[] = $errorCode; + + return $this; + } + + /** + * @internal + */ + public function getErrorCodesToIgnore() + { + return $this->errorCodesToIgnore; + } + + public function __toString() + { + $sql = $this->sql; + + if (!empty($sql) && !Common::stringEndsWith($sql, ';')) { + $sql .= ';'; + } + + return $sql; + } + + public function exec() + { + if (!empty($this->sql)) { + Db::exec($this->sql); + } + } +} diff --git a/core/Updater/Migration/Factory.php b/core/Updater/Migration/Factory.php new file mode 100644 index 0000000000000000000000000000000000000000..04514e5fd8a9b92172c583a26a3b4533bf42b665 --- /dev/null +++ b/core/Updater/Migration/Factory.php @@ -0,0 +1,47 @@ +db = $dbFactory; + $this->plugin = $pluginFactory; + $this->config = $configFactory; + } +} diff --git a/core/Updater/Migration/Plugin/Activate.php b/core/Updater/Migration/Plugin/Activate.php new file mode 100644 index 0000000000000000000000000000000000000000..d8452a8c3f5b803498a237b7f41e31af635b56c0 --- /dev/null +++ b/core/Updater/Migration/Plugin/Activate.php @@ -0,0 +1,56 @@ +pluginManager = $pluginManager; + $this->pluginName = $pluginName; + } + + public function __toString() + { + $domain = Config::getLocalConfigPath() === Config::getDefaultLocalConfigPath() ? '' : Config::getHostname(); + $domainArg = !empty($domain) ? "--matomo-domain=\"$domain\" " : ''; + + return sprintf('./console %splugin:activate "%s"', $domainArg, $this->pluginName); + } + + public function shouldIgnoreError($exception) + { + return true; + } + + public function exec() + { + if (!$this->pluginManager->isPluginActivated($this->pluginName)) { + $this->pluginManager->activatePlugin($this->pluginName); + } + } +} diff --git a/core/Updater/Migration/Plugin/Deactivate.php b/core/Updater/Migration/Plugin/Deactivate.php new file mode 100644 index 0000000000000000000000000000000000000000..a7e8b26afc6c2828800c8aec8f147df37799f00c --- /dev/null +++ b/core/Updater/Migration/Plugin/Deactivate.php @@ -0,0 +1,56 @@ +pluginManager = $pluginManager; + $this->pluginName = $pluginName; + } + + public function __toString() + { + $domain = Config::getLocalConfigPath() == Config::getDefaultLocalConfigPath() ? '' : Config::getHostname(); + $domainArg = !empty($domain) ? "--matomo-domain=\"$domain\" " : ''; + + return sprintf('./console %splugin:deactivate "%s"', $domainArg, $this->pluginName); + } + + public function shouldIgnoreError($exception) + { + return true; + } + + public function exec() + { + if ($this->pluginManager->isPluginActivated($this->pluginName)) { + $this->pluginManager->deactivatePlugin($this->pluginName); + } + } +} diff --git a/core/Updater/Migration/Plugin/Factory.php b/core/Updater/Migration/Plugin/Factory.php new file mode 100644 index 0000000000000000000000000000000000000000..1a31a47bcfabe66b7f3386fbe78e221918886dc4 --- /dev/null +++ b/core/Updater/Migration/Plugin/Factory.php @@ -0,0 +1,78 @@ +container = StaticContainer::getContainer(); + } + + /** + * Activates the given plugin during an update. + * + * If the plugin is already activated or if any other error occurs it will be ignored. + * + * @param string $pluginName + * @return Activate + */ + public function activate($pluginName) + { + return $this->container->make('Piwik\Updater\Migration\Plugin\Activate', array( + 'pluginName' => $pluginName, + )); + } + + /** + * Deactivates the given plugin during an update. + * + * If the plugin is already deactivated or if any other error occurs it will be ignored. + * + * @param string $pluginName + * @return Deactivate + */ + public function deactivate($pluginName) + { + return $this->container->make('Piwik\Updater\Migration\Plugin\Deactivate', array( + 'pluginName' => $pluginName, + )); + } + + /** + * Uninstalls the given plugin during an update. + * + * If the plugin is still active or if any other error occurs it will be ignored. + * + * @param string $pluginName + * @return Uninstall + */ + public function uninstall($pluginName) + { + return $this->container->make('Piwik\Updater\Migration\Plugin\Uninstall', array( + 'pluginName' => $pluginName, + )); + } +} diff --git a/core/Updater/Migration/Plugin/Uninstall.php b/core/Updater/Migration/Plugin/Uninstall.php new file mode 100644 index 0000000000000000000000000000000000000000..73b0a42be81102ea53a51d7c2a9e81142f87737e --- /dev/null +++ b/core/Updater/Migration/Plugin/Uninstall.php @@ -0,0 +1,58 @@ +pluginManager = $pluginManager; + $this->pluginName = $pluginName; + } + + public function __toString() + { + $domain = Config::getLocalConfigPath() == Config::getDefaultLocalConfigPath() ? '' : Config::getHostname(); + $domainArg = !empty($domain) ? "--matomo-domain=\"$domain\" " : ''; + + return sprintf('./console %splugin:uninstall "%s"', $domainArg, $this->pluginName); + } + + public function shouldIgnoreError($exception) + { + return true; + } + + public function exec() + { + $this->pluginManager->uninstallPlugin($this->pluginName); + + // uninstallPlugin() loads all plugins in the filesystem, which we don't want for the rest of the updates + $this->pluginManager->unloadPlugins(); + $this->pluginManager->loadActivatedPlugins(); + } +} diff --git a/core/Updater/UpdateObserver.php b/core/Updater/UpdateObserver.php new file mode 100644 index 0000000000000000000000000000000000000000..291d80ca7d8e7b904324ed1becb81c330bb4bd2a --- /dev/null +++ b/core/Updater/UpdateObserver.php @@ -0,0 +1,116 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $tableNotExistsError = Updater\Migration\Db::ERROR_CODE_TABLE_NOT_EXISTS; + return array( + $this->migration->db->createTable('option', array( + 'idoption' => 'BIGINT NOT NULL AUTO_INCREMENT' , + 'option_name' => 'VARCHAR( 64 ) NOT NULL' , + 'option_value' => 'LONGTEXT NOT NULL' , + ), array('idoption', 'option_name')), + + // 0.1.7 [463] + $this->migration->db->changeColumnType('log_visit', 'location_provider', 'VARCHAR( 100 ) DEFAULT NULL'), + + // 0.1.7 [470] + $this->migration->db->changeColumnTypes('logger_api_call', array( + 'parameter_names_default_values' => 'TEXT', + 'parameter_values' => 'TEXT', + 'returned_value' => 'TEXT', + ))->addErrorCodeToIgnore($tableNotExistsError), + $this->migration->db->changeColumnType('logger_error', 'message', 'TEXT')->addErrorCodeToIgnore($tableNotExistsError), + $this->migration->db->changeColumnType('logger_exception', 'message', 'TEXT')->addErrorCodeToIgnore($tableNotExistsError), + $this->migration->db->changeColumnType('logger_message', 'message', 'TEXT')->addErrorCodeToIgnore($tableNotExistsError), + + // 0.2.2 [489] + $this->migration->db->changeColumnType('site', 'feedburnerName', 'VARCHAR( 100 ) DEFAULT NULL'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + + $obsoleteDirectories = array( + '/plugins/AdminHome', + '/plugins/Home', + '/plugins/PluginsAdmin', + ); + foreach ($obsoleteDirectories as $dir) { + if (file_exists(PIWIK_INCLUDE_PATH . $dir)) { + Filesystem::unlinkRecursive(PIWIK_INCLUDE_PATH . $dir, true); + } + } + } +} diff --git a/core/Updates/0.2.12.php b/core/Updates/0.2.12.php new file mode 100644 index 0000000000000000000000000000000000000000..28d53b89d63618aa3450b690f433fea4d09565b9 --- /dev/null +++ b/core/Updates/0.2.12.php @@ -0,0 +1,44 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->changeColumnType('site', 'ts_created', 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL'), + $this->migration->db->dropColumn('log_visit', 'config_color_depth'), + + // 0.2.12 [673] + // Note: requires INDEX privilege + $this->migration->db->dropIndex('log_action', 'index_idaction'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/0.2.13.php b/core/Updates/0.2.13.php new file mode 100644 index 0000000000000000000000000000000000000000..247dd4db37124286360451ef09415f5d3f2d9bd6 --- /dev/null +++ b/core/Updates/0.2.13.php @@ -0,0 +1,45 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->dropTable('option'), + $this->migration->db->createTable('option', array( + 'option_name' => 'VARCHAR( 64 ) NOT NULL' , + 'option_value' => 'LONGTEXT NOT NULL' , + 'autoload' => "TINYINT NOT NULL DEFAULT '1'", + )), + $this->migration->db->addPrimaryKey('option', 'option_name'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/0.2.24.php b/core/Updates/0.2.24.php new file mode 100644 index 0000000000000000000000000000000000000000..23b0bd49f3320c7143015f35defbbe7141a7dee2 --- /dev/null +++ b/core/Updates/0.2.24.php @@ -0,0 +1,42 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addIndex('log_action', array('type', 'name(15)'), 'index_type_name'), + $this->migration->db->addIndex('log_visit', array('idsite', 'visit_server_date'), 'index_idsite_date'), + $this->migration->db->dropIndex('log_visit', 'index_idsite'), + $this->migration->db->dropIndex('log_visit', 'index_visit_server_date'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/0.2.27.php b/core/Updates/0.2.27.php new file mode 100644 index 0000000000000000000000000000000000000000..6c1377a7d0e39712c56825486e83d4291d85a12f --- /dev/null +++ b/core/Updates/0.2.27.php @@ -0,0 +1,86 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migrations = array( + $this->migration->db->addColumn('log_visit', 'visit_goal_converted', 'TINYINT( 1 ) NOT NULL', 'visit_total_time'), + $this->migration->db->sql('CREATE TABLE `' . Common::prefixTable('goal') . "` ( + `idsite` int(11) NOT NULL, + `idgoal` int(11) NOT NULL, + `name` varchar(50) NOT NULL, + `match_attribute` varchar(20) NOT NULL, + `pattern` varchar(255) NOT NULL, + `pattern_type` varchar(10) NOT NULL, + `case_sensitive` tinyint(4) NOT NULL, + `revenue` float NOT NULL, + `deleted` tinyint(4) NOT NULL default '0', + PRIMARY KEY (`idsite`,`idgoal`) + )", Updater\Migration\Db::ERROR_CODE_TABLE_EXISTS), + + $this->migration->db->sql('CREATE TABLE `' . Common::prefixTable('log_conversion') . '` ( + `idvisit` int(10) unsigned NOT NULL, + `idsite` int(10) unsigned NOT NULL, + `visitor_idcookie` char(32) NOT NULL, + `server_time` datetime NOT NULL, + `visit_server_date` date NOT NULL, + `idaction` int(11) NOT NULL, + `idlink_va` int(11) NOT NULL, + `referer_idvisit` int(10) unsigned default NULL, + `referer_type` int(10) unsigned default NULL, + `referer_name` varchar(70) default NULL, + `referer_keyword` varchar(255) default NULL, + `visitor_returning` tinyint(1) NOT NULL, + `location_country` char(3) NOT NULL, + `location_continent` char(3) NOT NULL, + `url` text NOT NULL, + `idgoal` int(10) unsigned NOT NULL, + `revenue` float default NULL, + PRIMARY KEY (`idvisit`,`idgoal`), + KEY `index_idsite_date` (`idsite`,`visit_server_date`) + )', Updater\Migration\Db::ERROR_CODE_TABLE_EXISTS), + ); + + $tables = DbHelper::getTablesInstalled(); + foreach ($tables as $tableName) { + if (preg_match('/archive_/', $tableName) == 1) { + $columns = array('idsite','date1','date2','name','ts_archived'); + $tableNameUnprefixed = Common::unprefixTable($tableName); + $migrations[] = $this->migration->db->addIndex($tableNameUnprefixed, $columns, 'index_all'); + } + } + + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/0.2.32.php b/core/Updates/0.2.32.php new file mode 100644 index 0000000000000000000000000000000000000000..71e01d1642ed46303cb8becaf02624185c0ebf72 --- /dev/null +++ b/core/Updates/0.2.32.php @@ -0,0 +1,43 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + // 0.2.32 [941] + $this->migration->db->changeColumnType('access', 'login', 'VARCHAR( 100 ) NOT NULL'), + $this->migration->db->changeColumnType('user', 'login', 'VARCHAR( 100 ) NOT NULL'), + $this->migration->db->changeColumnType('user_dashboard', 'login', 'VARCHAR( 100 ) NOT NULL'), + $this->migration->db->changeColumnType('user_language', 'login', 'VARCHAR( 100 ) NOT NULL'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/0.2.33.php b/core/Updates/0.2.33.php new file mode 100644 index 0000000000000000000000000000000000000000..01c6ba41d0d0ddafc0f858a8aa517a631c5c16fe --- /dev/null +++ b/core/Updates/0.2.33.php @@ -0,0 +1,53 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migrations = array( + // 0.2.33 [1020] + $this->migration->db->sql('ALTER TABLE `' . Common::prefixTable('user_dashboard') . '` + CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci ', Updater\Migration\Db::ERROR_CODE_TABLE_NOT_EXISTS), + $this->migration->db->sql('ALTER TABLE `' . Common::prefixTable('user_language') . '` + CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci ', Updater\Migration\Db::ERROR_CODE_TABLE_NOT_EXISTS), + ); + + // alter table to set the utf8 collation + $tablesToAlter = DbHelper::getTablesInstalled(true); + foreach ($tablesToAlter as $table) { + $migrations[] = $this->migration->db->sql('ALTER TABLE `' . $table . '` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci'); + } + + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/0.2.35.php b/core/Updates/0.2.35.php new file mode 100644 index 0000000000000000000000000000000000000000..d9a486ffa8ddc501ac952bf5a5427ed16c2d8d7f --- /dev/null +++ b/core/Updates/0.2.35.php @@ -0,0 +1,39 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->changeColumnType('user_dashboard', 'layout', 'TEXT NOT NULL'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/0.2.37.php b/core/Updates/0.2.37.php new file mode 100644 index 0000000000000000000000000000000000000000..b195997cd0da5af1f412869930e583746d04b2e8 --- /dev/null +++ b/core/Updates/0.2.37.php @@ -0,0 +1,42 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->sql('DELETE FROM `' . Common::prefixTable('user_dashboard') . "` + WHERE layout LIKE '%.getLastVisitsGraph%' + OR layout LIKE '%.getLastVisitsReturningGraph%'"), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/0.4.1.php b/core/Updates/0.4.1.php new file mode 100644 index 0000000000000000000000000000000000000000..0340e12ce12ceda1db7d2a7602e660f807f9a789 --- /dev/null +++ b/core/Updates/0.4.1.php @@ -0,0 +1,40 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->changeColumnType('log_conversion', 'idlink_va', 'INT(11) DEFAULT NULL'), + $this->migration->db->changeColumnType('log_conversion', 'idaction', 'INT(11) DEFAULT NULL'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/0.4.2.php b/core/Updates/0.4.2.php new file mode 100644 index 0000000000000000000000000000000000000000..9f845516d42ac82d4c4f1bdc4d36b6d9ae997cb4 --- /dev/null +++ b/core/Updates/0.4.2.php @@ -0,0 +1,43 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('log_visit', 'config_java', 'TINYINT(1) NOT NULL', 'config_flash'), + $this->migration->db->addColumn('log_visit', 'config_quicktime', 'TINYINT(1) NOT NULL', 'config_flash'), + $this->migration->db->addColumn('log_visit', 'config_gears', 'TINYINT(1) NOT NULL', 'config_windowsmedia'), + $this->migration->db->addColumn('log_visit', 'config_silverlight', 'TINYINT(1) NOT NULL', 'config_gears'), + ); + } + + // when restoring (possibly) previousy dropped columns, ignore mysql code error 1060: duplicate column + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/0.4.4.php b/core/Updates/0.4.4.php new file mode 100644 index 0000000000000000000000000000000000000000..a9fca87746843dd057db5c900e2a334226678b04 --- /dev/null +++ b/core/Updates/0.4.4.php @@ -0,0 +1,28 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + // 0.4 [1140] + $this->migration->db->sql('UPDATE `' . Common::prefixTable('log_visit') . '` + SET location_ip=location_ip+CAST(POW(2,32) AS UNSIGNED) WHERE location_ip < 0'), + $this->migration->db->changeColumnType('log_visit', 'location_ip', 'BIGINT UNSIGNED NOT NULL'), + $this->migration->db->sql('UPDATE `' . Common::prefixTable('logger_api_call') . '` + SET caller_ip=caller_ip+CAST(POW(2,32) AS UNSIGNED) WHERE caller_ip < 0', Updater\Migration\Db::ERROR_CODE_TABLE_NOT_EXISTS), + $this->migration->db->changeColumnType('logger_api_call', 'caller_ip', 'BIGINT UNSIGNED')->addErrorCodeToIgnore(Updater\Migration\Db::ERROR_CODE_TABLE_NOT_EXISTS), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/0.5.4.php b/core/Updates/0.5.4.php new file mode 100644 index 0000000000000000000000000000000000000000..2bb3a92c55d33bcfb300f78b62c79d3b329c03cb --- /dev/null +++ b/core/Updates/0.5.4.php @@ -0,0 +1,73 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->changeColumnType('log_action', 'name', 'TEXT'), + ); + } + + public function doUpdate(Updater $updater) + { + $salt = Common::generateUniqId(); + $config = Config::getInstance(); + $superuser = $config->superuser; + if (!isset($superuser['salt'])) { + try { + if (is_writable(Config::getLocalConfigPath())) { + $superuser['salt'] = $salt; + $config->superuser = $superuser; + $config->forceSave(); + } else { + throw new \Exception('mandatory update failed'); + } + } catch (\Exception $e) { + throw new \Piwik\UpdaterErrorException("Please edit your config/config.ini.php file and add below [superuser] the following line:
salt = $salt"); + } + } + + $plugins = $config->Plugins; + if (!in_array('MultiSites', $plugins)) { + try { + if (is_writable(Config::getLocalConfigPath())) { + $plugins[] = 'MultiSites'; + $config->Plugins = $plugins; + $config->forceSave(); + } else { + throw new \Exception('optional update failed'); + } + } catch (\Exception $e) { + throw new \Exception("You can now enable the new MultiSites plugin in the Plugins screen in the Matomo admin!"); + } + } + + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/0.5.5.php b/core/Updates/0.5.5.php new file mode 100644 index 0000000000000000000000000000000000000000..2e8b674f8220996f3ba9a1d4400d01ad52f2ee0f --- /dev/null +++ b/core/Updates/0.5.5.php @@ -0,0 +1,56 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migrations = array( + $this->migration->db->dropIndex('log_visit', 'index_idsite_date'), + $this->migration->db->addIndex('log_visit', array('idsite', 'visit_server_date', 'config_md5config(8)'), 'index_idsite_date_config'), + ); + + $tables = DbHelper::getTablesInstalled(); + foreach ($tables as $tableName) { + $unprefixedTable = Common::unprefixTable($tableName); + if (preg_match('/archive_/', $tableName) == 1) { + $migrations[] = $this->migration->db->dropIndex($unprefixedTable, 'index_all'); + } + if (preg_match('/archive_numeric_/', $tableName) == 1) { + $columns = array('idsite', 'date1', 'date2', 'period'); + $migrations[] = $this->migration->db->addIndex($unprefixedTable, $columns, 'index_idsite_dates_period'); + } + } + + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/0.5.php b/core/Updates/0.5.php new file mode 100644 index 0000000000000000000000000000000000000000..ec226a9a4378505573ce4737533cd2d43d22a514 --- /dev/null +++ b/core/Updates/0.5.php @@ -0,0 +1,51 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $logActionTable = Common::prefixTable('log_action'); + + return array( + $this->migration->db->addColumn('log_action', 'hash', 'INTEGER(10) UNSIGNED NOT NULL', 'name'), + $this->migration->db->changeColumn('log_visit', 'visit_exit_idaction', 'visit_exit_idaction_url', 'INTEGER(11) NOT NULL'), + $this->migration->db->changeColumn('log_visit', 'visit_entry_idaction', 'visit_entry_idaction_url', 'INTEGER(11) NOT NULL'), + $this->migration->db->changeColumn('log_link_visit_action', 'idaction_ref', 'idaction_url_ref', 'INTEGER(10) UNSIGNED NOT NULL'), + $this->migration->db->changeColumn('log_link_visit_action', 'idaction', 'idaction_url', 'INTEGER(10) UNSIGNED NOT NULL'), + $this->migration->db->addColumn('log_link_visit_action', 'idaction_name', 'INTEGER(10) UNSIGNED', 'idaction_url_ref'), + $this->migration->db->changeColumn('log_conversion', 'idaction', 'idaction_url', 'INTEGER(11) UNSIGNED NOT NULL'), + $this->migration->db->sql('UPDATE ' . $logActionTable . ' SET `hash` = CRC32(name);'), + $this->migration->db->addIndex('log_action', array('type', 'hash'), 'index_type_hash'), + $this->migration->db->dropIndex('log_action', 'index_type_name'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/0.6-rc1.php b/core/Updates/0.6-rc1.php new file mode 100644 index 0000000000000000000000000000000000000000..195862b53b7f124dc6528f92acbe57693fc12ce9 --- /dev/null +++ b/core/Updates/0.6-rc1.php @@ -0,0 +1,78 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $defaultTimezone = 'UTC'; + $defaultCurrency = 'USD'; + + return array( + $this->migration->db->changeColumnType('user', 'date_registered', 'TIMESTAMP NULL'), + $this->migration->db->changeColumnType('site', 'ts_created', 'TIMESTAMP NULL'), + $this->migration->db->addColumn('site', 'timezone', 'VARCHAR( 50 ) NOT NULL', 'ts_created'), + $this->migration->db->sql('UPDATE ' . Common::prefixTable('site') . ' SET `timezone` = "' . $defaultTimezone . '";', Migration\Db::ERROR_CODE_DUPLICATE_COLUMN), + $this->migration->db->addColumn('site', 'currency', 'CHAR( 3 ) NOT NULL', 'timezone'), + $this->migration->db->sql('UPDATE ' . Common::prefixTable('site') . ' SET `currency` = "' . $defaultCurrency . '";', Migration\Db::ERROR_CODE_DUPLICATE_COLUMN), + $this->migration->db->addColumn('site', 'excluded_ips', 'TEXT NOT NULL', 'currency'), + $this->migration->db->addColumn('site', 'excluded_parameters', 'VARCHAR( 255 ) NOT NULL', 'excluded_ips'), + $this->migration->db->addIndex('log_visit', array('idsite', 'visit_last_action_time', 'config_md5config(8)'), 'index_idsite_datetime_config'), + $this->migration->db->addIndex('log_visit', array('idsite', 'idvisit')), + $this->migration->db->dropIndex('log_conversion', 'index_idsite_date'), + $this->migration->db->dropColumn('log_conversion', 'visit_server_date'), + $this->migration->db->addIndex('log_conversion', array('idsite', 'server_time'), 'index_idsite_datetime'), + ); + } + + public function doUpdate(Updater $updater) + { + // first we disable the plugins and keep an array of warnings messages + $pluginsToDisableMessage = array( + 'SearchEnginePosition' => "SearchEnginePosition plugin was disabled, because it is not compatible with the new Piwik 0.6. \n You can download the latest version of the plugin, compatible with Piwik 0.6.\nClick here.", + 'GeoIP' => "GeoIP plugin was disabled, because it is not compatible with the new Piwik 0.6. \nYou can download the latest version of the plugin, compatible with Piwik 0.6.\nClick here.", + ); + $disabledPlugins = array(); + foreach ($pluginsToDisableMessage as $pluginToDisable => $warningMessage) { + if (\Piwik\Plugin\Manager::getInstance()->isPluginActivated($pluginToDisable)) { + \Piwik\Plugin\Manager::getInstance()->deactivatePlugin($pluginToDisable); + $disabledPlugins[] = $warningMessage; + } + } + + // Run the SQL + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + + // Outputs warning message, pointing users to the plugin download page + if (!empty($disabledPlugins)) { + throw new \Exception("The following plugins were disabled during the upgrade:" + . "
  • " . + implode('
  • ', $disabledPlugins) . + "
"); + } + } +} diff --git a/core/Updates/0.6.3.php b/core/Updates/0.6.3.php new file mode 100644 index 0000000000000000000000000000000000000000..1e5eb6ba01eb50e69f71b5a8d2a98e8fa35f9371 --- /dev/null +++ b/core/Updates/0.6.3.php @@ -0,0 +1,55 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->changeColumnType('log_visit', 'location_ip', 'INT UNSIGNED NOT NULL'), + $this->migration->db->changeColumnType('logger_api_call', 'caller_ip', 'INT UNSIGNED')->addErrorCodeToIgnore(Updater\Migration\Db::ERROR_CODE_TABLE_NOT_EXISTS), + ); + } + + public function doUpdate(Updater $updater) + { + $config = Config::getInstance(); + $dbInfos = $config->database; + if (!isset($dbInfos['schema'])) { + try { + if (is_writable(Config::getLocalConfigPath())) { + $config->database = $dbInfos; + $config->forceSave(); + } else { + throw new \Exception('mandatory update failed'); + } + } catch (\Exception $e) { + } + } + + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/0.7.php b/core/Updates/0.7.php new file mode 100644 index 0000000000000000000000000000000000000000..b7c6e2e1904cf3527e3c29257ddfee386027644c --- /dev/null +++ b/core/Updates/0.7.php @@ -0,0 +1,39 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->changeColumnType('option', 'option_name', 'VARCHAR(255) NOT NULL'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/0.9.1.php b/core/Updates/0.9.1.php new file mode 100644 index 0000000000000000000000000000000000000000..fa99f319f527c3374229f5d1359e580a8132a46a --- /dev/null +++ b/core/Updates/0.9.1.php @@ -0,0 +1,67 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + if (!SettingsServer::isTimezoneSupportEnabled()) { + return array(); + } + // @see https://bugs.php.net/46111 + $timezones = timezone_identifiers_list(); + $brokenTZ = array(); + + foreach ($timezones as $timezone) { + $testDate = "2008-08-19 13:00:00 " . $timezone; + + if (!strtotime($testDate)) { + $brokenTZ[] = $timezone; + } + } + $timezoneList = '"' . implode('","', $brokenTZ) . '"'; + + return array( + $this->migration->db->sql( + 'UPDATE ' . Common::prefixTable('site') . ' + SET timezone = "UTC" WHERE timezone IN (' . $timezoneList . ')' + ), + + $this->migration->db->sql( + 'UPDATE `' . Common::prefixTable('option') . '` + SET option_value = "UTC" WHERE option_name = "SitesManager_DefaultTimezone" AND option_value IN (' . $timezoneList . ')' + ), + ); + } + + public function doUpdate(Updater $updater) + { + if (SettingsServer::isTimezoneSupportEnabled()) { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } + } +} diff --git a/core/Updates/1.1.php b/core/Updates/1.1.php new file mode 100644 index 0000000000000000000000000000000000000000..deab8070b093b0f0b15d84169ea9f1f41f1a6ae6 --- /dev/null +++ b/core/Updates/1.1.php @@ -0,0 +1,43 @@ +superuser; + } catch (\Exception $e) { + return; + } + + if (empty($superuser['login'])) { + return; + } + + $rootLogin = $superuser['login']; + try { + // throws an exception if invalid + Piwik::checkValidLoginString($rootLogin); + } catch (\Exception $e) { + throw new \Exception('Superuser login name "' . $rootLogin . '" is no longer a valid format. ' + . $e->getMessage() + . ' Edit your config/config.ini.php to change it.'); + } + } +} diff --git a/core/Updates/1.10-b4.php b/core/Updates/1.10-b4.php new file mode 100644 index 0000000000000000000000000000000000000000..10800ff369b00d726a4451882edcbc4b1d0f0253 --- /dev/null +++ b/core/Updates/1.10-b4.php @@ -0,0 +1,30 @@ +activatePlugin('MobileMessaging'); + } catch (\Exception $e) { + // pass + } + } +} diff --git a/core/Updates/1.10.1.php b/core/Updates/1.10.1.php new file mode 100644 index 0000000000000000000000000000000000000000..0b5a08c47fe93a55cbc1787800ecdfbcbd77d308 --- /dev/null +++ b/core/Updates/1.10.1.php @@ -0,0 +1,30 @@ +activatePlugin('Overlay'); + } catch (\Exception $e) { + // pass + } + } +} diff --git a/core/Updates/1.10.2-b1.php b/core/Updates/1.10.2-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..87395aef446f0f359317da07a53dc14ad127e7ef --- /dev/null +++ b/core/Updates/1.10.2-b1.php @@ -0,0 +1,39 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('report', 'hour', 'TINYINT NOT NULL DEFAULT 0', 'period'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/1.10.2-b2.php b/core/Updates/1.10.2-b2.php new file mode 100644 index 0000000000000000000000000000000000000000..6a2fd278a3798f2343f390bda35ace755742bcfa --- /dev/null +++ b/core/Updates/1.10.2-b2.php @@ -0,0 +1,39 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('site', 'keep_url_fragment', 'TINYINT NOT NULL DEFAULT 0', 'group'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/1.11-b1.php b/core/Updates/1.11-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..7140a676afa1bb36809610061c7bb019ff8bf310 --- /dev/null +++ b/core/Updates/1.11-b1.php @@ -0,0 +1,30 @@ +activatePlugin('UserCountryMap'); + } catch (\Exception $e) { + // pass + } + } +} diff --git a/core/Updates/1.12-b1.php b/core/Updates/1.12-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..c88d2f8f72eb6a88b55f7b9e28aff8635183b4a6 --- /dev/null +++ b/core/Updates/1.12-b1.php @@ -0,0 +1,44 @@ +migration = $factory; + } + + public static function isMajorUpdate() + { + return true; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('log_link_visit_action', 'custom_float', 'FLOAT NULL DEFAULT NULL'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/1.12-b15.php b/core/Updates/1.12-b15.php new file mode 100644 index 0000000000000000000000000000000000000000..004d7c15508c37c6200463c4a930f308915febfd --- /dev/null +++ b/core/Updates/1.12-b15.php @@ -0,0 +1,25 @@ +activatePlugin('SegmentEditor'); + } catch (\Exception $e) { + // pass + } + } +} diff --git a/core/Updates/1.12-b16.php b/core/Updates/1.12-b16.php new file mode 100644 index 0000000000000000000000000000000000000000..e2146436868a4f41984bcb3a6a0e97cf400fda14 --- /dev/null +++ b/core/Updates/1.12-b16.php @@ -0,0 +1,39 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('report', 'idsegment', 'INT(11)', 'description'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/1.2-rc1.php b/core/Updates/1.2-rc1.php new file mode 100644 index 0000000000000000000000000000000000000000..57f13e664ea1f355f07dde3dc40895fae0909c9f --- /dev/null +++ b/core/Updates/1.2-rc1.php @@ -0,0 +1,152 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $customVarType = 'VARCHAR(100) DEFAULT NULL'; + $customVarColumns = array( + 'custom_var_k1' => $customVarType, + 'custom_var_v1' => $customVarType, + 'custom_var_k2' => $customVarType, + 'custom_var_v2' => $customVarType, + 'custom_var_k3' => $customVarType, + 'custom_var_v3' => $customVarType, + 'custom_var_k4' => $customVarType, + 'custom_var_v4' => $customVarType, + 'custom_var_k5' => $customVarType, + 'custom_var_v5' => $customVarType, + ); + + return array( + // Various performance improvements schema updates + $this->migration->db->sql('ALTER TABLE `' . Common::prefixTable('log_visit') . '` + DROP `visit_server_date`, + DROP INDEX `index_idsite_date_config`, + DROP INDEX `index_idsite_datetime_config`, + ADD `idvisitor` BINARY(8) NOT NULL AFTER `idsite`, + ADD `config_id` BINARY(8) NOT NULL AFTER `config_md5config` + ', array(Updater\Migration\Db::ERROR_CODE_UNKNOWN_COLUMN, Updater\Migration\Db::ERROR_CODE_COLUMN_NOT_EXISTS)), + $this->migration->db->sql('ALTER TABLE `' . Common::prefixTable('log_visit') . '` + ADD `visit_entry_idaction_name` INT UNSIGNED NOT NULL AFTER `visit_entry_idaction_url`, + ADD `visit_exit_idaction_name` INT UNSIGNED NOT NULL AFTER `visit_exit_idaction_url`, + CHANGE `visit_exit_idaction_url` `visit_exit_idaction_url` INT UNSIGNED NOT NULL, + CHANGE `visit_entry_idaction_url` `visit_entry_idaction_url` INT UNSIGNED NOT NULL, + CHANGE `referer_type` `referer_type` TINYINT UNSIGNED NULL DEFAULT NULL, + ADD visitor_count_visits SMALLINT(5) UNSIGNED NOT NULL AFTER `visitor_returning`, + ADD visitor_days_since_last SMALLINT(5) UNSIGNED NOT NULL, + ADD visitor_days_since_first SMALLINT(5) UNSIGNED NOT NULL + ', Updater\Migration\Db::ERROR_CODE_DUPLICATE_COLUMN), + + $this->migration->db->addColumns('log_visit', $customVarColumns), + + $this->migration->db->addColumns('log_link_visit_action', array( + 'idsite' => 'INT( 10 ) UNSIGNED NOT NULL', + 'idvisitor' => 'BINARY(8) NOT NULL', + 'idaction_name_ref' => 'INT UNSIGNED NOT NULL', + ), 'idlink_va'), + + $this->migration->db->addColumn('log_link_visit_action', 'server_time', 'DATETIME', 'idsite'), + $this->migration->db->addIndex('log_link_visit_action', array('idsite', 'server_time'), 'index_idsite_servertime'), + + $this->migration->db->sql('ALTER TABLE `' . Common::prefixTable('log_conversion') . '` + DROP `referer_idvisit`, + ADD `idvisitor` BINARY(8) NOT NULL AFTER `idsite` + ', array(Updater\Migration\Db::ERROR_CODE_DUPLICATE_COLUMN, Updater\Migration\Db::ERROR_CODE_COLUMN_NOT_EXISTS)), + $this->migration->db->addColumns('log_conversion', array( + 'visitor_count_visits' => 'SMALLINT(5) UNSIGNED NOT NULL', + 'visitor_days_since_first' => 'SMALLINT(5) UNSIGNED NOT NULL', + )), + $this->migration->db->addColumns('log_conversion', $customVarColumns), + + // Migrate 128bits IDs inefficiently stored as 8bytes (256 bits) into 64bits + $this->migration->db->sql('UPDATE ' . Common::prefixTable('log_visit') . ' + SET idvisitor = binary(unhex(substring(visitor_idcookie,1,16))), + config_id = binary(unhex(substring(config_md5config,1,16))) + ', Updater\Migration\Db::ERROR_CODE_UNKNOWN_COLUMN), + $this->migration->db->sql('UPDATE ' . Common::prefixTable('log_conversion') . ' + SET idvisitor = binary(unhex(substring(visitor_idcookie,1,16))) + ', Updater\Migration\Db::ERROR_CODE_UNKNOWN_COLUMN), + + // Drop migrated fields + $this->migration->db->sql('ALTER TABLE `' . Common::prefixTable('log_visit') . '` + DROP visitor_idcookie, + DROP config_md5config + ', Updater\Migration\Db::ERROR_CODE_COLUMN_NOT_EXISTS), + $this->migration->db->sql('ALTER TABLE `' . Common::prefixTable('log_conversion') . '` + DROP visitor_idcookie + ', Updater\Migration\Db::ERROR_CODE_COLUMN_NOT_EXISTS), + + // Recreate INDEX on new field + $this->migration->db->addIndex('log_visit', array('idsite', 'visit_last_action_time', 'config_id'), 'index_idsite_datetime_config'), + + // Backfill action logs as best as we can + $this->migration->db->sql('UPDATE ' . Common::prefixTable('log_link_visit_action') . ' as action, + ' . Common::prefixTable('log_visit') . ' as visit + SET action.idsite = visit.idsite, + action.server_time = visit.visit_last_action_time, + action.idvisitor = visit.idvisitor + WHERE action.idvisit=visit.idvisit + '), + + $this->migration->db->changeColumnType('log_link_visit_action', 'server_time', 'DATETIME NOT NULL'), + + // New index used max once per request, in case this table grows significantly in the future + $this->migration->db->addIndex('option', 'autoload', 'autoload'), + + // new field for websites + $this->migration->db->addColumn('site', 'group', 'VARCHAR( 250 ) NOT NULL'), + ); + } + + public function doUpdate(Updater $updater) + { + // first we disable the plugins and keep an array of warnings messages + $pluginsToDisableMessage = array( + 'GeoIP' => "GeoIP plugin was disabled, because it is not compatible with the new Piwik 1.2. \nYou can download the latest version of the plugin, compatible with Piwik 1.2.\nClick here.", + 'EntryPage' => "EntryPage plugin is not compatible with this version of Matomo, it was disabled.", + ); + $disabledPlugins = array(); + foreach ($pluginsToDisableMessage as $pluginToDisable => $warningMessage) { + if (\Piwik\Plugin\Manager::getInstance()->isPluginActivated($pluginToDisable)) { + \Piwik\Plugin\Manager::getInstance()->deactivatePlugin($pluginToDisable); + $disabledPlugins[] = $warningMessage; + } + } + + // Run the SQL + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + + // Outputs warning message, pointing users to the plugin download page + if (!empty($disabledPlugins)) { + throw new \Exception("The following plugins were disabled during the upgrade:" + . "
  • " . + implode('
  • ', $disabledPlugins) . + "
"); + } + } +} diff --git a/core/Updates/1.2-rc2.php b/core/Updates/1.2-rc2.php new file mode 100644 index 0000000000000000000000000000000000000000..fef6d58c887657b8677e4238fc504dd4b2708c4f --- /dev/null +++ b/core/Updates/1.2-rc2.php @@ -0,0 +1,24 @@ +activatePlugin('CustomVariables'); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/1.2.3.php b/core/Updates/1.2.3.php new file mode 100644 index 0000000000000000000000000000000000000000..6f3f2be615ffea429cc58743c4fe828fdb27bc4f --- /dev/null +++ b/core/Updates/1.2.3.php @@ -0,0 +1,55 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $dbName = Config::getInstance()->database['dbname']; + + return array( + + // LOAD DATA INFILE uses the database's charset + $this->migration->db->sql('ALTER DATABASE `' . $dbName . '` DEFAULT CHARACTER SET utf8'), + + // Various performance improvements schema updates + $this->migration->db->sql( + 'ALTER TABLE `' . Common::prefixTable('log_visit') . '` + DROP INDEX index_idsite_datetime_config, + DROP INDEX index_idsite_idvisit, + ADD INDEX index_idsite_config_datetime (idsite, config_id, visit_last_action_time), + ADD INDEX index_idsite_datetime (idsite, visit_last_action_time)', + array(Updater\Migration\Db::ERROR_CODE_DUPLICATE_KEY, Updater\Migration\Db::ERROR_CODE_COLUMN_NOT_EXISTS) + ), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/1.2.5-rc1.php b/core/Updates/1.2.5-rc1.php new file mode 100644 index 0000000000000000000000000000000000000000..fb1dd8d19ef8b63e9ccda3fd096a9cbf352f8423 --- /dev/null +++ b/core/Updates/1.2.5-rc1.php @@ -0,0 +1,47 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('goal', 'allow_multiple', 'TINYINT(4) NOT NULL', 'case_sensitive'), + $this->migration->db->sql( + 'ALTER TABLE `' . Common::prefixTable('log_conversion') . '` + ADD buster int unsigned NOT NULL AFTER revenue, + DROP PRIMARY KEY, + ADD PRIMARY KEY (idvisit, idgoal, buster)', + Updater\Migration\Db::ERROR_CODE_DUPLICATE_COLUMN + ), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/1.2.5-rc7.php b/core/Updates/1.2.5-rc7.php new file mode 100644 index 0000000000000000000000000000000000000000..762fcbe7b81709d70c2e0e0b777f4aa0a753a6a8 --- /dev/null +++ b/core/Updates/1.2.5-rc7.php @@ -0,0 +1,39 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addIndex('log_visit', array('idsite', 'idvisitor')), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/1.4-rc1.php b/core/Updates/1.4-rc1.php new file mode 100644 index 0000000000000000000000000000000000000000..de8d41f9c071da6b2c80b73aeaa1f0dc12595d43 --- /dev/null +++ b/core/Updates/1.4-rc1.php @@ -0,0 +1,44 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->sql('UPDATE `' . Common::prefixTable('pdf') . '` SET format = "pdf"', '42S22'), + $this->migration->db->addColumn('pdf', 'format', 'VARCHAR(10)'), + ); + } + + public function doUpdate(Updater $updater) + { + try { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/1.4-rc2.php b/core/Updates/1.4-rc2.php new file mode 100644 index 0000000000000000000000000000000000000000..239644b7da088398ff902f1cdbe02186454bea6e --- /dev/null +++ b/core/Updates/1.4-rc2.php @@ -0,0 +1,53 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $errorCodeDbNotExists = Updater\Migration\Db::ERROR_CODE_TABLE_NOT_EXISTS; + + return array( + $this->migration->db->sql("SET sql_mode=''"), + // this converts the 32-bit UNSIGNED INT column to a 16 byte VARBINARY; + // _but_ MySQL does string conversion! (e.g., integer 1 is converted to 49 -- the ASCII code for "1") + $this->migration->db->sql('ALTER TABLE ' . Common::prefixTable('log_visit') . ' MODIFY location_ip VARBINARY(16) NOT NULL'), + $this->migration->db->sql('ALTER TABLE ' . Common::prefixTable('logger_api_call') . ' MODIFY caller_ip VARBINARY(16) NOT NULL', $errorCodeDbNotExists), + + // fortunately, 2^32 is 10 digits long and fits in the VARBINARY(16) without truncation; + // to fix this, we cast to an integer, convert to hex, pad out leading zeros, and unhex it + $this->migration->db->sql('UPDATE ' . Common::prefixTable('log_visit') . " + SET location_ip = UNHEX(LPAD(HEX(CONVERT(location_ip, UNSIGNED)), 8, '0'))"), + $this->migration->db->sql('UPDATE ' . Common::prefixTable('logger_api_call') . " + SET caller_ip = UNHEX(LPAD(HEX(CONVERT(caller_ip, UNSIGNED)), 8, '0'))", $errorCodeDbNotExists), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/1.5-b1.php b/core/Updates/1.5-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..099fedd748d4d7a150e71eb9b60f0d7284e4365f --- /dev/null +++ b/core/Updates/1.5-b1.php @@ -0,0 +1,68 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->createTable('log_conversion_item', array( + 'idsite' => 'int(10) UNSIGNED NOT NULL', + 'idvisitor' => 'BINARY(8) NOT NULL', + 'server_time' => 'DATETIME NOT NULL', + 'idvisit' => 'INTEGER(10) UNSIGNED NOT NULL', + 'idorder' => 'varchar(100) NOT NULL', + 'idaction_sku' => 'INTEGER(10) UNSIGNED NOT NULL', + 'idaction_name' => 'INTEGER(10) UNSIGNED NOT NULL', + 'idaction_category' => 'INTEGER(10) UNSIGNED NOT NULL', + 'price' => 'FLOAT NOT NULL', + 'quantity' => 'INTEGER(10) UNSIGNED NOT NULL', + 'deleted' => 'TINYINT(1) UNSIGNED NOT NULL', + ), array('idvisit', 'idorder', 'idaction_sku')), + $this->migration->db->addIndex('log_conversion_item', array('idsite', 'server_time')), + + $this->migration->db->addColumns('log_visit', array( + 'visitor_days_since_order' => 'SMALLINT(5) UNSIGNED NOT NULL', + 'visit_goal_buyer' => 'TINYINT(1) NOT NULL', + )), + + $this->migration->db->addColumn('log_conversion', 'visitor_days_since_order', 'SMALLINT(5) UNSIGNED NOT NULL'), + $this->migration->db->addColumns('log_conversion', array( + 'idorder' => 'varchar(100) default NULL', + 'items' => 'SMALLINT UNSIGNED DEFAULT NULL', + 'revenue_subtotal' => 'float default NULL', + 'revenue_tax' => 'float default NULL', + 'revenue_shipping' => 'float default NULL', + 'revenue_discount' => 'float default NULL', + )), + $this->migration->db->addUniqueKey('log_conversion', array('idsite', 'idorder')), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/1.5-b2.php b/core/Updates/1.5-b2.php new file mode 100644 index 0000000000000000000000000000000000000000..4ccee8fc908a5cd82903000eeccb27c5d1ba1ff2 --- /dev/null +++ b/core/Updates/1.5-b2.php @@ -0,0 +1,54 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $customVarType = 'VARCHAR(100) DEFAULT NULL'; + + $customVarColumns = array( + 'custom_var_k1' => $customVarType, + 'custom_var_v1' => $customVarType, + 'custom_var_k2' => $customVarType, + 'custom_var_v2' => $customVarType, + 'custom_var_k3' => $customVarType, + 'custom_var_v3' => $customVarType, + 'custom_var_k4' => $customVarType, + 'custom_var_v4' => $customVarType, + 'custom_var_k5' => $customVarType, + 'custom_var_v5' => $customVarType, + ); + + return array( + $this->migration->db->addColumns('log_link_visit_action', $customVarColumns, 'time_spent_ref_action'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/1.5-b3.php b/core/Updates/1.5-b3.php new file mode 100644 index 0000000000000000000000000000000000000000..899720d5cba0b6a26bb865610f7f4459f7980203 --- /dev/null +++ b/core/Updates/1.5-b3.php @@ -0,0 +1,56 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $customVarType = 'VARCHAR(100) DEFAULT NULL'; + + $customVarColumns = array( + 'custom_var_k1' => $customVarType, + 'custom_var_v1' => $customVarType, + 'custom_var_k2' => $customVarType, + 'custom_var_v2' => $customVarType, + 'custom_var_k3' => $customVarType, + 'custom_var_v3' => $customVarType, + 'custom_var_k4' => $customVarType, + 'custom_var_v4' => $customVarType, + 'custom_var_k5' => $customVarType, + 'custom_var_v5' => $customVarType, + ); + + return array( + $this->migration->db->changeColumnTypes('log_visit', $customVarColumns), + $this->migration->db->changeColumnTypes('log_conversion', $customVarColumns), + $this->migration->db->changeColumnTypes('log_link_visit_action', $customVarColumns), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/1.5-b4.php b/core/Updates/1.5-b4.php new file mode 100644 index 0000000000000000000000000000000000000000..630d71fe4e9dd134a556cf3226ee52fb3fcbd810 --- /dev/null +++ b/core/Updates/1.5-b4.php @@ -0,0 +1,39 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('site', 'ecommerce', 'TINYINT DEFAULT 0'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/1.5-b5.php b/core/Updates/1.5-b5.php new file mode 100644 index 0000000000000000000000000000000000000000..ab06efb0b4c51d571d03d1093d59907604583e02 --- /dev/null +++ b/core/Updates/1.5-b5.php @@ -0,0 +1,44 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->createTable('session', array( + 'id' => 'CHAR(32) NOT NULL', + 'modified' => 'INTEGER', + 'lifetime' => 'INTEGER', + 'data' => 'TEXT', + ), $primary = 'id'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/1.5-rc6.php b/core/Updates/1.5-rc6.php new file mode 100644 index 0000000000000000000000000000000000000000..f37172d421845a33660971c401d69461d91e6c5f --- /dev/null +++ b/core/Updates/1.5-rc6.php @@ -0,0 +1,24 @@ +activatePlugin('PrivacyManager'); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/1.6-b1.php b/core/Updates/1.6-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..12603f21f0d472cc5544d8d53c431a00c9f0f8c3 --- /dev/null +++ b/core/Updates/1.6-b1.php @@ -0,0 +1,63 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $idActionType = 'INTEGER(10) UNSIGNED NOT NULL'; + $customVarType = 'VARCHAR(200) DEFAULT NULL'; + + $customVarColumns = array( + 'custom_var_k1' => $customVarType, + 'custom_var_v1' => $customVarType, + 'custom_var_k2' => $customVarType, + 'custom_var_v2' => $customVarType, + 'custom_var_k3' => $customVarType, + 'custom_var_v3' => $customVarType, + 'custom_var_k4' => $customVarType, + 'custom_var_v4' => $customVarType, + 'custom_var_k5' => $customVarType, + 'custom_var_v5' => $customVarType, + ); + + return array( + $this->migration->db->addColumns('log_conversion_item', array( + 'idaction_category2' => $idActionType, + 'idaction_category3' => $idActionType, + 'idaction_category4' => $idActionType, + 'idaction_category5' => $idActionType, + ), 'idaction_category'), + $this->migration->db->changeColumnTypes('log_visit', $customVarColumns), + $this->migration->db->changeColumnTypes('log_conversion', $customVarColumns), + $this->migration->db->changeColumnTypes('log_link_visit_action', $customVarColumns), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/1.6-rc1.php b/core/Updates/1.6-rc1.php new file mode 100644 index 0000000000000000000000000000000000000000..480e3ac669a0d36089dd51b7986c852c28393cdf --- /dev/null +++ b/core/Updates/1.6-rc1.php @@ -0,0 +1,24 @@ +activatePlugin('ImageGraph'); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/1.7-b1.php b/core/Updates/1.7-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..5b97cace4797f014f9b9897ddaeb0dca8a3860f6 --- /dev/null +++ b/core/Updates/1.7-b1.php @@ -0,0 +1,44 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('pdf', 'aggregate_reports_format', 'TINYINT(1) NOT NULL', 'reports'), + $this->migration->db->sql('UPDATE `' . Common::prefixTable('pdf') . '` SET `aggregate_reports_format` = 1'), + ); + } + + public function doUpdate(Updater $updater) + { + try { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/1.7.2-rc5.php b/core/Updates/1.7.2-rc5.php new file mode 100644 index 0000000000000000000000000000000000000000..5c2eb03f54e22baa2b9049a202b21c06a129d0bb --- /dev/null +++ b/core/Updates/1.7.2-rc5.php @@ -0,0 +1,42 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->changeColumn('pdf', 'aggregate_reports_format', 'display_format', 'TINYINT(1) NOT NULL'), + ); + } + + public function doUpdate(Updater $updater) + { + try { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/1.7.2-rc7.php b/core/Updates/1.7.2-rc7.php new file mode 100644 index 0000000000000000000000000000000000000000..3e4d2320ec0870215dabb84cab23d47975af8306 --- /dev/null +++ b/core/Updates/1.7.2-rc7.php @@ -0,0 +1,62 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('user_dashboard', 'name', 'VARCHAR( 100 ) NULL DEFAULT NULL', 'iddashboard'), + ); + } + + public function doUpdate(Updater $updater) + { + try { + $migrations = array(); + + $table = Common::prefixTable('user_dashboard'); + $dashboards = Db::fetchAll('SELECT iddashboard, login, layout FROM `' . $table . '`'); + + $updateQuery = 'UPDATE `' . $table . '` SET layout = ? WHERE iddashboard = ? AND login = ?'; + + foreach ($dashboards as $dashboard) { + $idDashboard = $dashboard['iddashboard']; + $login = $dashboard['login']; + $layout = $dashboard['layout']; + $layout = html_entity_decode($layout, ENT_COMPAT | ENT_HTML401, 'UTF-8'); + $layout = str_replace("\\\"", "\"", $layout); + + $migrations[] = $this->migration->db->boundSql($updateQuery, array($layout, $idDashboard, $login)); + } + + $updater->executeMigrations(__FILE__, $migrations); + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/1.8.3-b1.php b/core/Updates/1.8.3-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..28ba38243b81c1f861dd75d96bdd7db628c80d38 --- /dev/null +++ b/core/Updates/1.8.3-b1.php @@ -0,0 +1,119 @@ +migration = $factory; + } + + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->changeColumnType('site', 'excluded_parameters', 'TEXT NOT NULL'), + + $this->migration->db->createTable('report', array( + 'idreport' => 'INT(11) NOT NULL AUTO_INCREMENT', + 'idsite' => 'INTEGER(11) NOT NULL', + 'login' => 'VARCHAR(100) NOT NULL', + 'description' => 'VARCHAR(255) NOT NULL', + 'period' => 'VARCHAR(10) NOT NULL', + 'type' => 'VARCHAR(10) NOT NULL', + 'format' => 'VARCHAR(10) NOT NULL', + 'reports' => 'TEXT NOT NULL', + 'parameters' => 'TEXT NULL', + 'ts_created' => 'TIMESTAMP NULL', + 'ts_last_sent' => 'TIMESTAMP NULL', + 'deleted' => 'tinyint(4) NOT NULL default 0', + ), $primaryKey = 'idreport'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + if (!\Piwik\Plugin\Manager::getInstance()->isPluginLoaded('ScheduledReports')) { + return; + } + + try { + // Common::prefixTable('pdf') has been heavily refactored to be more generic + // The following actions are taken in this update script : + // - create the new generic report table Common::prefixTable('report') + // - migrate previous reports, if any, from Common::prefixTable('pdf') to Common::prefixTable('report') + // - delete Common::prefixTable('pdf') + + $reports = Db::fetchAll('SELECT * FROM `' . Common::prefixTable('pdf') . '`'); + foreach ($reports as $report) { + $idreport = $report['idreport']; + $idsite = $report['idsite']; + $login = $report['login']; + $description = $report['description']; + $period = $report['period']; + $format = $report['format']; + $display_format = $report['display_format']; + $email_me = $report['email_me']; + $additional_emails = $report['additional_emails']; + $reports = $report['reports']; + $ts_created = $report['ts_created']; + $ts_last_sent = $report['ts_last_sent']; + $deleted = $report['deleted']; + + $parameters = array(); + + if (!is_null($additional_emails)) { + $parameters[ScheduledReports::ADDITIONAL_EMAILS_PARAMETER] = preg_split('/,/', $additional_emails); + } + + $parameters[ScheduledReports::EMAIL_ME_PARAMETER] = is_null($email_me) ? ScheduledReports::EMAIL_ME_PARAMETER_DEFAULT_VALUE : (bool)$email_me; + $parameters[ScheduledReports::DISPLAY_FORMAT_PARAMETER] = $display_format; + + Db::query( + 'INSERT INTO `' . Common::prefixTable('report') . '` SET + idreport = ?, idsite = ?, login = ?, description = ?, period = ?, + type = ?, format = ?, reports = ?, parameters = ?, ts_created = ?, + ts_last_sent = ?, deleted = ?', + array( + $idreport, + $idsite, + $login, + $description, + is_null($period) ? ScheduledReports::DEFAULT_PERIOD : $period, + ScheduledReports::EMAIL_TYPE, + is_null($format) ? ScheduledReports::DEFAULT_REPORT_FORMAT : $format, + json_encode(preg_split('/,/', $reports)), + json_encode($parameters), + $ts_created, + $ts_last_sent, + $deleted, + ) + ); + } + + $updater->executeMigration(__FILE__, $this->migration->db->dropTable('pdf')); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/1.8.4-b1.php b/core/Updates/1.8.4-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..3c99bca8ff60b7bfa02a274978b72355b8cba52e --- /dev/null +++ b/core/Updates/1.8.4-b1.php @@ -0,0 +1,206 @@ +migration = $factory; + } + + public static function isMajorUpdate() + { + return true; + } + + public function getMigrations(Updater $updater) + { + $action = Common::prefixTable('log_action'); + $duplicates = Common::prefixTable('log_action_duplicates'); + $visitAction = Common::prefixTable('log_link_visit_action'); + $conversion = Common::prefixTable('log_conversion'); + $visit = Common::prefixTable('log_visit'); + + return array( + + $this->migration->db->addColumn('log_action', 'url_prefix', 'TINYINT(2) NULL', 'type'), + + // remove protocol and www and store information in url_prefix + $this->migration->db->sql( + " UPDATE `$action` + SET + url_prefix = IF ( + LEFT(name, 11) = 'http://www.', 1, IF ( + LEFT(name, 7) = 'http://', 0, IF ( + LEFT(name, 12) = 'https://www.', 3, IF ( + LEFT(name, 8) = 'https://', 2, NULL + ) + ) + ) + ), + name = IF ( + url_prefix = 0, SUBSTRING(name, 8), IF ( + url_prefix = 1, SUBSTRING(name, 12), IF ( + url_prefix = 2, SUBSTRING(name, 9), IF ( + url_prefix = 3, SUBSTRING(name, 13), name + ) + ) + ) + ), + hash = CRC32(name) + WHERE + type = 1 AND + url_prefix IS NULL; + " + ), + $this->migration->db->dropTable('log_action_duplicates'), + $this->migration->db->createTable('log_action_duplicates', array( + 'before' => 'int(10) unsigned NOT NULL', + 'after' => 'int(10) unsigned NOT NULL', + )), + $this->migration->db->sql("ALTER TABLE $duplicates ADD KEY `mainkey` (`before`)"), + + // grouping by name only would be case-insensitive, so we GROUP BY name,hash + // ON (action.type = 1 AND canonical.hash = action.hash) will use index (type, hash) + $this->migration->db->sql( + " INSERT INTO `$duplicates` ( + SELECT + action.idaction AS `before`, + canonical.idaction AS `after` + FROM + ( + SELECT + name, + hash, + MIN(idaction) AS idaction + FROM + `$action` AS action_canonical_base + WHERE + type = 1 AND + url_prefix IS NOT NULL + GROUP BY name, hash + HAVING COUNT(idaction) > 1 + ) + AS canonical + LEFT JOIN + `$action` AS action + ON (action.type = 1 AND canonical.hash = action.hash) + AND canonical.name = action.name + AND canonical.idaction != action.idaction + ); + " + ), + + // replace idaction in log_link_visit_action + $this->migration->db->sql( + " UPDATE + `$visitAction` AS link + LEFT JOIN + `$duplicates` AS duplicates_idaction_url + ON link.idaction_url = duplicates_idaction_url.before + SET + link.idaction_url = duplicates_idaction_url.after + WHERE + duplicates_idaction_url.after IS NOT NULL; + " + ), + $this->migration->db->sql( + " UPDATE + `$visitAction` AS link + LEFT JOIN + `$duplicates` AS duplicates_idaction_url_ref + ON link.idaction_url_ref = duplicates_idaction_url_ref.before + SET + link.idaction_url_ref = duplicates_idaction_url_ref.after + WHERE + duplicates_idaction_url_ref.after IS NOT NULL; + " + ), + + // replace idaction in log_conversion + $this->migration->db->sql( + " UPDATE + `$conversion` AS conversion + LEFT JOIN + `$duplicates` AS duplicates + ON conversion.idaction_url = duplicates.before + SET + conversion.idaction_url = duplicates.after + WHERE + duplicates.after IS NOT NULL; + " + ), + + // replace idaction in log_visit + $this->migration->db->sql( + " UPDATE + `$visit` AS visit + LEFT JOIN + `$duplicates` AS duplicates_entry + ON visit.visit_entry_idaction_url = duplicates_entry.before + SET + visit.visit_entry_idaction_url = duplicates_entry.after + WHERE + duplicates_entry.after IS NOT NULL; + " + ), + $this->migration->db->sql( + " UPDATE + `$visit` AS visit + LEFT JOIN + `$duplicates` AS duplicates_exit + ON visit.visit_exit_idaction_url = duplicates_exit.before + SET + visit.visit_exit_idaction_url = duplicates_exit.after + WHERE + duplicates_exit.after IS NOT NULL; + " + ), + + // remove duplicates from log_action + $this->migration->db->sql( + " DELETE action FROM + `$action` AS action + LEFT JOIN + `$duplicates` AS duplicates + ON action.idaction = duplicates.before + WHERE + duplicates.after IS NOT NULL; + " + ), + + // remove the duplicates table + $this->migration->db->dropTable('log_action_duplicates'), + ); + } + + public function doUpdate(Updater $updater) + { + try { + self::enableMaintenanceMode(); + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + self::disableMaintenanceMode(); + } catch (\Exception $e) { + self::disableMaintenanceMode(); + throw $e; + } + } +} diff --git a/core/Updates/1.9-b16.php b/core/Updates/1.9-b16.php new file mode 100644 index 0000000000000000000000000000000000000000..9c2700ad13453a0f2347d1d5a87b4d24e384f527 --- /dev/null +++ b/core/Updates/1.9-b16.php @@ -0,0 +1,54 @@ +migration = $factory; + } + + public static function isMajorUpdate() + { + return true; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->changeColumnType('log_link_visit_action', 'idaction_url', 'INT( 10 ) UNSIGNED NULL DEFAULT NULL'), + $this->migration->db->addColumn('log_visit', 'visit_total_searches', 'SMALLINT(5) UNSIGNED NOT NULL', 'visit_total_actions'), + $this->migration->db->addColumns('site', array( + 'sitesearch' => 'TINYINT DEFAULT 1', + 'sitesearch_keyword_parameters' => 'TEXT NOT NULL', + 'sitesearch_category_parameters' => 'TEXT NOT NULL', + ), 'excluded_parameters'), + + // enable Site Search for all websites, users can manually disable the setting + $this->migration->db->sql('UPDATE `' . Common::prefixTable('site') . '` SET `sitesearch` = 1'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/1.9-b19.php b/core/Updates/1.9-b19.php new file mode 100644 index 0000000000000000000000000000000000000000..8f63c40c1666f5f86a5cb4177ded9f7b5f1b133c --- /dev/null +++ b/core/Updates/1.9-b19.php @@ -0,0 +1,41 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->changeColumnType('log_link_visit_action', 'idaction_url_ref', 'INT( 10 ) UNSIGNED NULL DEFAULT 0'), + $this->migration->db->changeColumnType('log_visit', 'visit_exit_idaction_url', 'INT( 10 ) UNSIGNED NULL DEFAULT 0'), + $this->migration->plugin->activate('Transitions'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/1.9-b9.php b/core/Updates/1.9-b9.php new file mode 100644 index 0000000000000000000000000000000000000000..df7377167031769fb3216d9e1a70d05bc6bd2d2e --- /dev/null +++ b/core/Updates/1.9-b9.php @@ -0,0 +1,66 @@ +migration = $factory; + } + + public static function isMajorUpdate() + { + return true; + } + + public function getMigrations(Updater $updater) + { + $logVisit = 'log_visit'; + $logConversion = 'log_conversion'; + + $addColumns = array('location_region' => 'CHAR(2) NULL', + 'location_city' => 'VARCHAR(255) NULL', + 'location_latitude' => 'FLOAT(10, 6) NULL', + 'location_longitude' => 'FLOAT(10, 6) NULL'); + $dropColumn = 'location_continent'; + + return array( + $this->migration->db->dropColumn($logVisit, $dropColumn), + $this->migration->db->dropColumn($logConversion, $dropColumn), + + // add geoip columns to log_visit + $this->migration->db->addColumns($logVisit, $addColumns, 'location_country'), + // add geoip columns to log_conversion + $this->migration->db->addColumns($logConversion, $addColumns, 'location_country'), + ); + } + + public function doUpdate(Updater $updater) + { + try { + self::enableMaintenanceMode(); + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + self::disableMaintenanceMode(); + } catch (\Exception $e) { + self::disableMaintenanceMode(); + throw $e; + } + } +} diff --git a/core/Updates/1.9.1-b2.php b/core/Updates/1.9.1-b2.php new file mode 100644 index 0000000000000000000000000000000000000000..1e0c7898196b5a804b251b0af5dc0380fcd55189 --- /dev/null +++ b/core/Updates/1.9.1-b2.php @@ -0,0 +1,44 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->dropColumn('site', 'feedburnerName'), + ); + } + + public function doUpdate(Updater $updater) + { + // manually remove ExampleFeedburner column + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + + // remove ExampleFeedburner plugin + $pluginToDelete = 'ExampleFeedburner'; + self::deletePluginFromConfigFile($pluginToDelete); + } +} diff --git a/core/Updates/1.9.3-b10.php b/core/Updates/1.9.3-b10.php new file mode 100644 index 0000000000000000000000000000000000000000..e95b4a37c78b990ec463a67961cee5fade3e1043 --- /dev/null +++ b/core/Updates/1.9.3-b10.php @@ -0,0 +1,30 @@ +activatePlugin('Annotations'); + } catch (\Exception $e) { + // pass + } + } +} diff --git a/core/Updates/1.9.3-b3.php b/core/Updates/1.9.3-b3.php new file mode 100644 index 0000000000000000000000000000000000000000..727882479b2b10bcd11bd4ff92809ec34cdf8e94 --- /dev/null +++ b/core/Updates/1.9.3-b3.php @@ -0,0 +1,27 @@ +deletePluginFromFilesystem($pluginToDelete); + + // We also clean up 1.9.1 and delete Feedburner plugin + \Piwik\Plugin\Manager::getInstance()->deletePluginFromFilesystem('Feedburner'); + } +} diff --git a/core/Updates/1.9.3-b8.php b/core/Updates/1.9.3-b8.php new file mode 100644 index 0000000000000000000000000000000000000000..a6992d3e5da4891c729503fcce0b8c8b8547dfc4 --- /dev/null +++ b/core/Updates/1.9.3-b8.php @@ -0,0 +1,40 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('site', 'excluded_user_agents', 'TEXT NOT NULL', 'excluded_parameters'), + ); + } + + public function doUpdate(Updater $updater) + { + // add excluded_user_agents column to site table + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.0-a12.php b/core/Updates/2.0-a12.php new file mode 100644 index 0000000000000000000000000000000000000000..e2a07f2f9e7f66e3c6983c1e780a05ae536d2eb3 --- /dev/null +++ b/core/Updates/2.0-a12.php @@ -0,0 +1,58 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $result = array( + $this->migration->db->sql('ALTER TABLE ' . Common::prefixTable('logger_message') . ' MODIFY level VARCHAR(16) NULL'), + ); + + $unneededLogTables = array('logger_exception', 'logger_error', 'logger_api_call'); + foreach ($unneededLogTables as $table) { + $tableName = Common::prefixTable($table); + + try { + $rows = Db::fetchOne("SELECT COUNT(*) FROM `$tableName`"); + if ($rows == 0) { + $result[] = $this->migration->db->dropTable($table); + } + } catch (\Exception $ex) { + // ignore + } + } + + return $result; + } + + public function doUpdate(Updater $updater) + { + // change level column in logger_message table to string & remove other logging tables if empty + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.0-a13.php b/core/Updates/2.0-a13.php new file mode 100644 index 0000000000000000000000000000000000000000..dd2b0ddd3e774c8327da0fdf4f72bd7c51fcdd36 --- /dev/null +++ b/core/Updates/2.0-a13.php @@ -0,0 +1,71 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + // Renaming old archived records now that the plugin is called Referrers + $migrations = array(); + $tables = \Piwik\DbHelper::getTablesInstalled(); + foreach ($tables as $tableName) { + if (strpos($tableName, 'archive_') !== false) { + $migrations[] = $this->migration->db->sql('UPDATE `' . $tableName . '` SET `name`=REPLACE(`name`, \'Referers_\', \'Referrers_\') WHERE `name` LIKE \'Referers_%\''); + } + } + $errorCodeTableNotFound = '1146'; + + // Rename custom segments containing Referers segments + $migrations[] = $this->migration->db->sql('UPDATE `' . Common::prefixTable('segment') . '` SET `definition`=REPLACE(`definition`, \'referer\', \'referrer\') WHERE `definition` LIKE \'%referer%\'', $errorCodeTableNotFound); + + // Rename Referrers reports within scheduled reports + $query = 'UPDATE `' . Common::prefixTable('report') . '` SET `reports`=REPLACE(`reports`, \'Referer\', \'Referrer\') WHERE `reports` LIKE \'%Referer%\''; + $migrations[] = $this->migration->db->sql($query, $errorCodeTableNotFound); + + // Rename Referrers widgets in custom dashboards + $query = 'UPDATE `' . Common::prefixTable('user_dashboard') . '` SET `layout`=REPLACE(`layout`, \'Referer\', \'Referrer\') WHERE `layout` LIKE \'%Referer%\''; + $migrations[] = $this->migration->db->sql($query, $errorCodeTableNotFound); + + $query = 'UPDATE `' . Common::prefixTable('option') . '` SET `option_name` = \'version_ScheduledReports\' WHERE `option_name` = \'version_PDFReports\' '; + $migrations[] = $this->migration->db->sql($query, Updater\Migration\Db::ERROR_CODE_DUPLICATE_ENTRY); // https://forum.piwik.org/read.php?2,106895 + + $migrations[] = $this->migration->plugin->activate('Referrers'); + $migrations[] = $this->migration->plugin->activate('ScheduledReports'); + + return $migrations; + } + + public function doUpdate(Updater $updater) + { + // delete schema version_ + Option::delete('version_Referers'); + + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + + // old plugins deleted in 2.0-a17 update file + } +} diff --git a/core/Updates/2.0-a17.php b/core/Updates/2.0-a17.php new file mode 100644 index 0000000000000000000000000000000000000000..f83ef64b69bdcdf610711fa275b418163f6e921b --- /dev/null +++ b/core/Updates/2.0-a17.php @@ -0,0 +1,40 @@ +" . implode("
", $errors)); + } + } +} diff --git a/core/Updates/2.0-a7.php b/core/Updates/2.0-a7.php new file mode 100644 index 0000000000000000000000000000000000000000..812db57803a8c2a94b6d0e446ea1da23b4a64999 --- /dev/null +++ b/core/Updates/2.0-a7.php @@ -0,0 +1,41 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('logger_message', 'tag', 'VARCHAR(50) NULL', 'idlogger_message'), + $this->migration->db->addColumn('logger_message', 'level', 'TINYINT', 'timestamp'), + ); + } + + public function doUpdate(Updater $updater) + { + // add tag & level columns to logger_message table + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.0-b10.php b/core/Updates/2.0-b10.php new file mode 100644 index 0000000000000000000000000000000000000000..66b34436953d86d1c6be5573382e0d7ee9d2e414 --- /dev/null +++ b/core/Updates/2.0-b10.php @@ -0,0 +1,22 @@ +" . implode("
", $errors)); + } + } +} diff --git a/core/Updates/2.0-b3.php b/core/Updates/2.0-b3.php new file mode 100644 index 0000000000000000000000000000000000000000..12c6de3ad1179d2174bd0d82de8620a9b1e87bce --- /dev/null +++ b/core/Updates/2.0-b3.php @@ -0,0 +1,53 @@ +migration = $factory; + } + + public static function isMajorUpdate() + { + return true; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('log_visit', 'visit_total_events', 'SMALLINT(5) UNSIGNED NOT NULL', 'visit_total_searches'), + $this->migration->db->addColumns('log_link_visit_action', array( + 'idaction_event_category' => 'INTEGER(10) UNSIGNED', + 'idaction_event_action' => 'INTEGER(10) UNSIGNED', + ), $placeAfter = 'idaction_name_ref'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + + try { + \Piwik\Plugin\Manager::getInstance()->activatePlugin('Events'); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/2.0-b9.php b/core/Updates/2.0-b9.php new file mode 100644 index 0000000000000000000000000000000000000000..29754acb235d5ba494fbcb907bb0d8359e69f07d --- /dev/null +++ b/core/Updates/2.0-b9.php @@ -0,0 +1,42 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $type = "VARCHAR(255) NOT NULL DEFAULT '" . Site::DEFAULT_SITE_TYPE . "'"; + + return array( + $this->migration->db->addColumn('site', 'type', $type, 'group'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.0-rc1.php b/core/Updates/2.0-rc1.php new file mode 100644 index 0000000000000000000000000000000000000000..efdaddb1c21f9d62b6d3803dc9d5517fe97be681 --- /dev/null +++ b/core/Updates/2.0-rc1.php @@ -0,0 +1,24 @@ +activatePlugin('Morpheus'); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/2.0.3-b7.php b/core/Updates/2.0.3-b7.php new file mode 100644 index 0000000000000000000000000000000000000000..c32300b4f0ac53a496e0a5789202305543174ab1 --- /dev/null +++ b/core/Updates/2.0.3-b7.php @@ -0,0 +1,62 @@ +isPluginActivated('DoNotTrack')) { + $checker->activate(); + } + + // enable IP anonymization if AnonymizeIP plugin was enabled + if (\Piwik\Plugin\Manager::getInstance()->isPluginActivated('AnonymizeIP')) { + IPAnonymizer::activate(); + } + } catch (\Exception $ex) { + // pass + } + + // disable & delete old plugins + $oldPlugins = array('DoNotTrack', 'AnonymizeIP'); + foreach ($oldPlugins as $plugin) { + try { + \Piwik\Plugin\Manager::getInstance()->deactivatePlugin($plugin); + } catch (\Exception $e) { + } + + $dir = PIWIK_INCLUDE_PATH . "/plugins/$plugin"; + + if (file_exists($dir)) { + Filesystem::unlinkRecursive($dir, true); + } + + if (file_exists($dir)) { + $errors[] = "Please delete this directory manually (eg. using your FTP software): $dir \n"; + } + } + if (!empty($errors)) { + throw new \Exception("Warnings during the update:
" . implode("
", $errors)); + } + } +} diff --git a/core/Updates/2.0.4-b5.php b/core/Updates/2.0.4-b5.php new file mode 100644 index 0000000000000000000000000000000000000000..9c780386c0863b0d81e9de89e1d66ec8aab53314 --- /dev/null +++ b/core/Updates/2.0.4-b5.php @@ -0,0 +1,102 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('user', 'superuser_access', "TINYINT(2) UNSIGNED NOT NULL DEFAULT '0'"), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + + try { + self::migrateConfigSuperUserToDb(); + } catch (\Exception $e) { + throw new UpdaterErrorException($e->getMessage()); + } + } + + private static function migrateConfigSuperUserToDb() + { + $config = Config::getInstance(); + + if (!$config->existsLocalConfig()) { + return; + } + + try { + $superUser = $config->superuser; + } catch (\Exception $e) { + $superUser = null; + } + + if ( + !empty($superUser['bridge']) + || empty($superUser) + || empty($superUser['login']) + ) { + // there is a super user which is not from the config but from the bridge, that means we already have + // a super user in the database + return; + } + + $userApi = UsersManagerApi::getInstance(); + + try { + Db::get()->insert(Common::prefixTable('user'), array( + 'login' => $superUser['login'], + 'password' => $superUser['password'], + 'alias' => $superUser['login'], + 'email' => $superUser['email'], + 'token_auth' => md5(Common::getRandomString(32)), + 'date_registered' => Date::now()->getDatetime(), + 'superuser_access' => 1, + )); + } catch (\Exception $e) { + echo "There was an issue, but we proceed: " . $e->getMessage(); + } + + if (array_key_exists('salt', $superUser)) { + $salt = $superUser['salt']; + } else { + $salt = Common::generateUniqId(); + } + + $config->General['salt'] = $salt; + $config->superuser = array(); + $config->forceSave(); + } +} diff --git a/core/Updates/2.0.4-b7.php b/core/Updates/2.0.4-b7.php new file mode 100644 index 0000000000000000000000000000000000000000..321997d8a471e162a08add0be6c9e41d1095f3ce --- /dev/null +++ b/core/Updates/2.0.4-b7.php @@ -0,0 +1,62 @@ +getMessage()); + } + } + + private static function migrateExistingMobileMessagingOptions() + { + if (Option::get(MobileMessaging::DELEGATED_MANAGEMENT_OPTION) == 'true') { + return; + } + + // copy $superUserLogin_MobileMessagingSettings -> _MobileMessagingSettings as settings are managed globally + + $optionName = MobileMessaging::USER_SETTINGS_POSTFIX_OPTION; + $superUsers = UsersManagerApi::getInstance()->getUsersHavingSuperUserAccess(); + + if (empty($superUsers)) { + return; + } + + $firstSuperUser = array_shift($superUsers); + + if (empty($firstSuperUser)) { + return; + } + + $superUserLogin = $firstSuperUser['login']; + $optionPrefixed = $superUserLogin . $optionName; + + // $superUserLogin_MobileMessagingSettings + $value = Option::get($optionPrefixed); + + if (false !== $value) { + // _MobileMessagingSettings + Option::set($optionName, $value); + } + } +} diff --git a/core/Updates/2.0.4-b8.php b/core/Updates/2.0.4-b8.php new file mode 100644 index 0000000000000000000000000000000000000000..b63e72455e5bd1a4fffea242026371109ac60440 --- /dev/null +++ b/core/Updates/2.0.4-b8.php @@ -0,0 +1,70 @@ +forceSave(); + } catch (\Exception $e) { + throw new UpdaterErrorException($e->getMessage()); + } + } + + private static function migrateBrandingConfig(Config $config) + { + $useCustomLogo = self::getValueAndDelete($config, 'branding', 'use_custom_logo'); + + $customLogo = new CustomLogo(); + $useCustomLogo ? $customLogo->enable() : $customLogo->disable(); + } + + private static function migratePrivacyManagerConfig(Config $oldConfig, PrivacyManagerConfig $newConfig) + { + $ipVisitEnrichment = self::getValueAndDelete($oldConfig, 'Tracker', 'use_anonymized_ip_for_visit_enrichment'); + $ipAddressMarkLength = self::getValueAndDelete($oldConfig, 'Tracker', 'ip_address_mask_length'); + + if (null !== $ipVisitEnrichment) { + $newConfig->useAnonymizedIpForVisitEnrichment = $ipVisitEnrichment; + } + if (null !== $ipAddressMarkLength) { + $newConfig->ipAddressMaskLength = $ipAddressMarkLength; + } + } + + private static function getValueAndDelete(Config $config, $section, $key) + { + if (!$config->$section || !array_key_exists($key, $config->$section)) { + return null; + } + + $values = $config->$section; + $value = $values[$key]; + unset($values[$key]); + + $config->$section = $values; + + return $value; + } +} diff --git a/core/Updates/2.1.1-b11.php b/core/Updates/2.1.1-b11.php new file mode 100644 index 0000000000000000000000000000000000000000..47c6c1766719da5502739363860c65fed206fe8d --- /dev/null +++ b/core/Updates/2.1.1-b11.php @@ -0,0 +1,143 @@ +migration = $factory; + } + + public function doUpdate(Updater $updater) + { + $returningMetrics = array( + 'nb_visits_returning', + 'nb_actions_returning', + 'max_actions_returning', + 'sum_visit_length_returning', + 'bounce_count_returning', + 'nb_visits_converted_returning', + 'nb_uniq_visitors_returning', + ); + + $now = Date::factory('now')->getDatetime(); + + $archiveNumericTables = Db::get()->fetchCol("SHOW TABLES LIKE '%archive_numeric%'"); + + // for each numeric archive table, copy *_returning metrics to VisitsSummary metrics w/ the appropriate + // returning visit segment + foreach ($archiveNumericTables as $table) { + // get archives w/ *._returning + $sql = "SELECT idarchive, idsite, period, date1, date2 FROM `$table` + WHERE name IN ('" . implode("','", $returningMetrics) . "') + GROUP BY idarchive"; + $idArchivesWithReturning = Db::fetchAll($sql); + + // get archives for visitssummary returning visitor segment + $sql = "SELECT idarchive, idsite, period, date1, date2 FROM `$table` + WHERE name = ? GROUP BY idarchive"; + $visitSummaryReturningSegmentDone = Rules::getDoneFlagArchiveContainsOnePlugin( + new Segment(VisitFrequencyApi::RETURNING_VISITOR_SEGMENT, $idSites = array()), + 'VisitsSummary' + ); + $idArchivesWithVisitReturningSegment = Db::fetchAll($sql, array($visitSummaryReturningSegmentDone)); + + // collect info for new visitssummary archives have to be created to match archives w/ *._returning + // metrics + $missingIdArchives = array(); + $idArchiveMappings = array(); + foreach ($idArchivesWithReturning as $row) { + $withMetricsIdArchive = $row['idarchive']; + foreach ($idArchivesWithVisitReturningSegment as $segmentRow) { + if ( + $row['idsite'] == $segmentRow['idsite'] + && $row['period'] == $segmentRow['period'] + && $row['date1'] == $segmentRow['date1'] + && $row['date2'] == $segmentRow['date2'] + ) { + $idArchiveMappings[$withMetricsIdArchive] = $segmentRow['idarchive']; + } + } + + if (!isset($idArchiveMappings[$withMetricsIdArchive])) { + $missingIdArchives[$withMetricsIdArchive] = $row; + } + } + + // if there are missing idarchives, fill out new archive row values + if (!empty($missingIdArchives)) { + $newIdArchiveStart = Db::fetchOne("SELECT MAX(idarchive) FROM `$table`") + 1; + foreach ($missingIdArchives as $withMetricsIdArchive => &$rowToInsert) { + $idArchiveMappings[$withMetricsIdArchive] = $newIdArchiveStart; + + $rowToInsert['idarchive'] = $newIdArchiveStart; + $rowToInsert['ts_archived'] = $now; + $rowToInsert['name'] = $visitSummaryReturningSegmentDone; + $rowToInsert['value'] = ArchiveWriter::DONE_OK; + + ++$newIdArchiveStart; + } + + // add missing archives + $params = array(); + foreach ($missingIdArchives as $missingIdArchive) { + $params[] = array_values($missingIdArchive); + } + $fields = array_keys(reset($missingIdArchives)); + $tableUnprefixed = Common::unprefixTable($table); + $migration = $this->migration->db->batchInsert($tableUnprefixed, $fields, $params, $throwException = false, $charset = 'latin1'); + $updater->executeMigration(__FILE__, $migration); + } + + // update idarchive & name columns in rows with *._returning metrics + $updateSqlPrefix = "UPDATE $table + SET idarchive = CASE idarchive "; + $updateSqlSuffix = " END, name = CASE name "; + foreach ($returningMetrics as $metric) { + $newMetricName = substr($metric, 0, strlen($metric) - strlen(VisitFrequencyApi::RETURNING_COLUMN_SUFFIX)); + $updateSqlSuffix .= "WHEN '$metric' THEN '" . $newMetricName . "' "; + } + $updateSqlSuffix .= " END WHERE idarchive IN (%s) + AND name IN ('" . implode("','", $returningMetrics) . "')"; + + // update only 1000 rows at a time so we don't send too large an SQL query to MySQL + foreach (array_chunk($missingIdArchives, 1000, $preserveKeys = true) as $chunk) { + $idArchives = array(); + + $updateSql = $updateSqlPrefix; + foreach ($chunk as $withMetricsIdArchive => $row) { + $updateSql .= "WHEN $withMetricsIdArchive THEN {$row['idarchive']} "; + + $idArchives[] = $withMetricsIdArchive; + } + $updateSql .= sprintf($updateSqlSuffix, implode(',', $idArchives)); + + $updater->executeMigration(__FILE__, $this->migration->db->sql($updateSql)); + } + } + } +} diff --git a/core/Updates/2.10.0-b10.php b/core/Updates/2.10.0-b10.php new file mode 100644 index 0000000000000000000000000000000000000000..0457bcdbbbdf85f6df36194fc5eb0b072319e74e --- /dev/null +++ b/core/Updates/2.10.0-b10.php @@ -0,0 +1,57 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migrations = array(); + + $archiveTables = ArchiveTableCreator::getTablesArchivesInstalled(); + + $archiveBlobTables = array_filter($archiveTables, function ($name) { + return ArchiveTableCreator::getTypeFromTableName($name) == ArchiveTableCreator::BLOB_TABLE; + }); + + foreach ($archiveBlobTables as $table) { + $migrations[] = $this->migration->db->sql("UPDATE $table SET name = 'DevicePlugins_plugin' WHERE name = 'UserSettings_plugin'"); + } + + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $pluginManager = \Piwik\Plugin\Manager::getInstance(); + + try { + $pluginManager->activatePlugin('DevicePlugins'); + } catch (\Exception $e) { + } + + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.10.0-b4.php b/core/Updates/2.10.0-b4.php new file mode 100644 index 0000000000000000000000000000000000000000..3bbed52b6fbb08f3503e0c9e5b73bac65e0a36b4 --- /dev/null +++ b/core/Updates/2.10.0-b4.php @@ -0,0 +1,29 @@ +activatePlugin('BulkTracking'); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/2.10.0-b5.php b/core/Updates/2.10.0-b5.php new file mode 100644 index 0000000000000000000000000000000000000000..f1b3418a5edddffb98916fa7e41c78727e730cd9 --- /dev/null +++ b/core/Updates/2.10.0-b5.php @@ -0,0 +1,219 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migrations = array('# ATTENTION: This update script will execute some more SQL queries than that below as it is necessary to rebuilt some archives #' => false); + + // update scheduled reports to use new plugin + $reportsToReplace = array( + 'UserSettings_getBrowserVersion' => 'DevicesDetection_getBrowserVersions', + 'UserSettings_getBrowser' => 'DevicesDetection_getBrowsers', + 'UserSettings_getOSFamily' => 'DevicesDetection_getOsFamilies', + 'UserSettings_getOS' => 'DevicesDetection_getOsVersions', + 'UserSettings_getMobileVsDesktop' => 'DevicesDetection_getType', + 'UserSettings_getBrowserType' => 'DevicesDetection_getBrowserEngines', + 'UserSettings_getWideScreen' => 'UserSettings_getScreenType', + ); + + $reportTable = Common::prefixTable('report'); + foreach ($reportsToReplace as $old => $new) { + $migrations[] = $this->migration->db->sql("UPDATE $reportTable SET reports = REPLACE(reports, '" . $old . "', '" . $new . "')"); + } + + // update dashboard to use new widgets + $oldWidgets = array( + array('module' => 'UserSettings', 'action' => 'getBrowserVersion', 'params' => array()), + array('module' => 'UserSettings', 'action' => 'getBrowser', 'params' => array()), + array('module' => 'UserSettings', 'action' => 'getOSFamily', 'params' => array()), + array('module' => 'UserSettings', 'action' => 'getOS', 'params' => array()), + array('module' => 'UserSettings', 'action' => 'getMobileVsDesktop', 'params' => array()), + array('module' => 'UserSettings', 'action' => 'getBrowserType', 'params' => array()), + array('module' => 'UserSettings', 'action' => 'getWideScreen', 'params' => array()), + ); + + $newWidgets = array( + array('module' => 'DevicesDetection', 'action' => 'getBrowserVersions', 'params' => array()), + array('module' => 'DevicesDetection', 'action' => 'getBrowsers', 'params' => array()), + array('module' => 'DevicesDetection', 'action' => 'getOsFamilies', 'params' => array()), + array('module' => 'DevicesDetection', 'action' => 'getOsVersions', 'params' => array()), + array('module' => 'DevicesDetection', 'action' => 'getType', 'params' => array()), + array('module' => 'DevicesDetection', 'action' => 'getBrowserEngines', 'params' => array()), + array('module' => 'UserSettings', 'action' => 'getScreenType', 'params' => array()), + ); + + $allDashboards = Db::get()->fetchAll(sprintf("SELECT * FROM `%s`", Common::prefixTable('user_dashboard'))); + + $dashboardTable = Common::prefixTable('user_dashboard'); + $dashboardQuery = "UPDATE $dashboardTable SET layout = ? WHERE iddashboard = ?"; + + foreach ($allDashboards as $dashboard) { + $dashboardLayout = json_decode($dashboard['layout']); + + $dashboardLayout = DashboardModel::replaceDashboardWidgets($dashboardLayout, $oldWidgets, $newWidgets); + + $newLayout = json_encode($dashboardLayout); + if ($newLayout != $dashboard['layout']) { + $migrations[] = $this->migration->db->boundSql($dashboardQuery, array($newLayout, $dashboard['iddashboard'])); + } + } + + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + + // DeviceDetection upgrade in beta1 timed out on demo #6750 + $archiveBlobTables = self::getAllArchiveBlobTables(); + + foreach ($archiveBlobTables as $table) { + self::updateBrowserArchives($table); + self::updateOsArchives($table); + } + } + + /** + * Returns all available archive blob tables + * + * @return array + */ + public static function getAllArchiveBlobTables() + { + if (empty(self::$archiveBlobTables)) { + $archiveTables = ArchiveTableCreator::getTablesArchivesInstalled(); + + self::$archiveBlobTables = array_filter($archiveTables, function ($name) { + return ArchiveTableCreator::getTypeFromTableName($name) == ArchiveTableCreator::BLOB_TABLE; + }); + + // sort tables so we have them in order of their date + rsort(self::$archiveBlobTables); + } + + return (array) self::$archiveBlobTables; + } + + /** + * Find the first day on which DevicesDetection archives were generated + * + * @return int Timestamp + */ + public static function getFirstDayOfArchivedDeviceDetectorData() + { + static $deviceDetectionBlobAvailableDate; + + if (empty($deviceDetectionBlobAvailableDate)) { + $archiveBlobTables = self::getAllArchiveBlobTables(); + + $deviceDetectionBlobAvailableDate = null; + foreach ($archiveBlobTables as $table) { + // Look for all day archives and try to find that with the lowest date + $deviceDetectionBlobAvailableDate = Db::get()->fetchOne(sprintf("SELECT date1 FROM `%s` WHERE name = 'DevicesDetection_browserVersions' AND period = 1 ORDER BY date1 ASC LIMIT 1", $table)); + + if (!empty($deviceDetectionBlobAvailableDate)) { + break; + } + } + + $deviceDetectionBlobAvailableDate = strtotime($deviceDetectionBlobAvailableDate); + } + + return $deviceDetectionBlobAvailableDate; + } + + /** + * Updates all browser archives to new structure + * @param string $table + * @throws \Exception + */ + public static function updateBrowserArchives($table) + { + // rename old UserSettings archives where no DeviceDetection archives exists + Db::exec(sprintf("UPDATE IGNORE `%s` SET name='DevicesDetection_browserVersions' WHERE name = 'UserSettings_browser'", $table)); + + /* + * check dates of remaining (non-day) archives with calculated safe date + * archives before or within that week/month/year of that date will be replaced + */ + $oldBrowserBlobs = Db::get()->fetchAll(sprintf("SELECT * FROM `%s` WHERE name = 'UserSettings_browser' AND `period` > 1", $table)); + foreach ($oldBrowserBlobs as $blob) { + // if start date of blob is before calculated date us old usersettings archive instead of already existing DevicesDetection archive + if (strtotime($blob['date1']) < self::getFirstDayOfArchivedDeviceDetectorData()) { + Db::get()->query(sprintf("DELETE FROM `%s` WHERE idarchive = ? AND name = ?", $table), [$blob['idarchive'], 'DevicesDetection_browserVersions']); + Db::get()->query(sprintf("UPDATE `%s` SET name = ? WHERE idarchive = ? AND name = ?", $table), ['DevicesDetection_browserVersions', $blob['idarchive'], 'UserSettings_browser']); + } + } + } + + public static function updateOsArchives($table) + { + Db::exec(sprintf("UPDATE IGNORE `%s` SET name='DevicesDetection_osVersions' WHERE name = 'UserSettings_os'", $table)); + + /* + * check dates of remaining (non-day) archives with calculated safe date + * archives before or within that week/month/year of that date will be replaced + */ + $oldOsBlobs = Db::get()->fetchAll(sprintf("SELECT * FROM `%s` WHERE name = 'UserSettings_os' AND `period` > 1", $table)); + foreach ($oldOsBlobs as $blob) { + // if start date of blob is before calculated date us old usersettings archive instead of already existing DevicesDetection archive + if (strtotime($blob['date1']) < self::getFirstDayOfArchivedDeviceDetectorData()) { + Db::get()->query(sprintf("DELETE FROM `%s` WHERE idarchive = ? AND name = ?", $table), [$blob['idarchive'], 'DevicesDetection_osVersions']); + Db::get()->query(sprintf("UPDATE `%s` SET name = ? WHERE idarchive = ? AND name = ?", $table), ['DevicesDetection_osVersions', $blob['idarchive'], 'UserSettings_os']); + } + } + } +} diff --git a/core/Updates/2.10.0-b7.php b/core/Updates/2.10.0-b7.php new file mode 100644 index 0000000000000000000000000000000000000000..1c5c27cf394c3bb24208a5511330cd26fffd5f33 --- /dev/null +++ b/core/Updates/2.10.0-b7.php @@ -0,0 +1,51 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migrations = array(); + + $archiveTables = ArchiveTableCreator::getTablesArchivesInstalled(); + + $archiveBlobTables = array_filter($archiveTables, function ($name) { + return ArchiveTableCreator::getTypeFromTableName($name) == ArchiveTableCreator::BLOB_TABLE; + }); + + foreach ($archiveBlobTables as $table) { + $migrations[] = $this->migration->db->sql("UPDATE $table SET name = 'Resolution_resolution' WHERE name = 'UserSettings_resolution'"); + $migrations[] = $this->migration->db->sql("UPDATE $table SET name = 'Resolution_configuration' WHERE name = 'UserSettings_configuration'"); + } + + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.10.0-b8.php b/core/Updates/2.10.0-b8.php new file mode 100644 index 0000000000000000000000000000000000000000..1b93cda4e5e5b078178ffe55e05f25b9e4f64854 --- /dev/null +++ b/core/Updates/2.10.0-b8.php @@ -0,0 +1,26 @@ +activatePlugin('Resolution'); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/2.11.0-b2.php b/core/Updates/2.11.0-b2.php new file mode 100644 index 0000000000000000000000000000000000000000..c8d28fc7eede25222a8bae135ebc36525f37ca2e --- /dev/null +++ b/core/Updates/2.11.0-b2.php @@ -0,0 +1,73 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migrations = array(); + + // update dashboard to use new ecommerce widgets, they were moved from goals plugin to ecommerce + $oldWidgets = array( + array('module' => 'Goals', 'action' => 'getEcommerceLog', 'params' => array()), + array('module' => 'Goals', 'action' => 'widgetGoalReport', 'params' => array('idGoal' => Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER)), + ); + + $newWidgets = array( + array('module' => 'Ecommerce', 'action' => 'getEcommerceLog', 'params' => array()), + array('module' => 'Ecommerce', 'action' => 'widgetGoalReport', 'params' => array('idGoal' => Piwik::LABEL_ID_GOAL_IS_ECOMMERCE_ORDER)), + ); + + $allDashboards = Db::get()->fetchAll(sprintf("SELECT * FROM `%s`", Common::prefixTable('user_dashboard'))); + + $sql = "UPDATE " . Common::prefixTable('user_dashboard') . " SET layout = ? WHERE iddashboard = ?"; + + foreach ($allDashboards as $dashboard) { + $dashboardLayout = json_decode($dashboard['layout']); + $dashboardLayout = DashboardModel::replaceDashboardWidgets($dashboardLayout, $oldWidgets, $newWidgets); + + $newLayout = json_encode($dashboardLayout); + if ($newLayout != $dashboard['layout']) { + $migrations[] = $this->migration->db->boundSql($sql, array($newLayout, $dashboard['iddashboard'])); + } + } + + $migrations[] = $this->migration->plugin->activate('Ecommerce'); + + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.11.0-b4.php b/core/Updates/2.11.0-b4.php new file mode 100644 index 0000000000000000000000000000000000000000..066f7273172b26d031bdcc091740543340e431ed --- /dev/null +++ b/core/Updates/2.11.0-b4.php @@ -0,0 +1,57 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migrations = array(); + + $archiveTables = ArchiveTableCreator::getTablesArchivesInstalled(); + + $archiveBlobTables = array_filter($archiveTables, function ($name) { + return ArchiveTableCreator::getTypeFromTableName($name) == ArchiveTableCreator::BLOB_TABLE; + }); + + foreach ($archiveBlobTables as $table) { + $migrations[] = $this->migration->db->sql("UPDATE $table SET name = 'UserLanguage_language' WHERE name = 'UserSettings_language'"); + } + + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $pluginManager = \Piwik\Plugin\Manager::getInstance(); + + try { + $pluginManager->activatePlugin('UserLanguage'); + } catch (\Exception $e) { + } + + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.11.0-b5.php b/core/Updates/2.11.0-b5.php new file mode 100644 index 0000000000000000000000000000000000000000..acb3f844aacdd35f20a4bf4230a7c60dc6efa228 --- /dev/null +++ b/core/Updates/2.11.0-b5.php @@ -0,0 +1,39 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->plugin->activate('Monolog'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.11.1-b4.php b/core/Updates/2.11.1-b4.php new file mode 100644 index 0000000000000000000000000000000000000000..6cfde8a6d2eb103a25267b907e777d3648eb2738 --- /dev/null +++ b/core/Updates/2.11.1-b4.php @@ -0,0 +1,40 @@ +database_tests; + + if ($dbTests['username'] === '@USERNAME@') { + $dbTests['username'] = 'root'; + } + + $config->database_tests = $dbTests; + + $config->forceSave(); + } +} diff --git a/core/Updates/2.13.0-b3.php b/core/Updates/2.13.0-b3.php new file mode 100644 index 0000000000000000000000000000000000000000..467116956c3ff18432b9b9b9811c63287c947da4 --- /dev/null +++ b/core/Updates/2.13.0-b3.php @@ -0,0 +1,39 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->plugin->activate('Diagnostics'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.13.1.php b/core/Updates/2.13.1.php new file mode 100644 index 0000000000000000000000000000000000000000..f5cb758199bfcf514708b4ecac93693651ad3e3c --- /dev/null +++ b/core/Updates/2.13.1.php @@ -0,0 +1,54 @@ +migration = $factory; + } + + /** + * Here you can define one or multiple SQL statements that should be executed during the update. + * @return Updater\Migration[] + */ + public function getMigrations(Updater $updater) + { + $optionTable = Common::prefixTable('option'); + $removeEmptyDefaultReportsSql = "delete from `$optionTable` where option_name like '%defaultReport%' and option_value=''"; + + return array( + $this->migration->db->sql($removeEmptyDefaultReportsSql), + ); + } + + /** + * Here you can define any action that should be performed during the update. For instance executing SQL statements, + * renaming config entries, updating files, etc. + */ + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.14.0-b1.php b/core/Updates/2.14.0-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..f610b1958a2decc7c7d0dd15db183b60f59bfb94 --- /dev/null +++ b/core/Updates/2.14.0-b1.php @@ -0,0 +1,43 @@ +uninstallPlugin('UserSettings'); + } + + private function uninstallPlugin($plugin) + { + $pluginManager = Manager::getInstance(); + + if ($pluginManager->isPluginInstalled($plugin)) { + if ($pluginManager->isPluginActivated($plugin)) { + $pluginManager->deactivatePlugin($plugin); + } + + $pluginManager->unloadPlugin($plugin); + $pluginManager->uninstallPlugin($plugin); + } else { + $this->makeSurePluginIsRemovedFromFilesystem($plugin); + } + } + + private function makeSurePluginIsRemovedFromFilesystem($plugin) + { + Manager::deletePluginFromFilesystem($plugin); + } +} diff --git a/core/Updates/2.14.0-b2.php b/core/Updates/2.14.0-b2.php new file mode 100644 index 0000000000000000000000000000000000000000..e3d87bae2a0c1b670fe8d2b301b262e9c1eb2ee6 --- /dev/null +++ b/core/Updates/2.14.0-b2.php @@ -0,0 +1,46 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $table = 'site_setting'; + + return array( + $this->migration->db->dropTable($table), + $this->migration->db->createTable($table, array( + 'idsite' => 'INTEGER(10) UNSIGNED NOT NULL AUTO_INCREMENT', + 'setting_name' => 'VARCHAR(255) NOT NULL', + 'setting_value' => 'LONGTEXT NOT NULL', + ), $primaryKey = array('idsite', 'setting_name')), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.14.2.php b/core/Updates/2.14.2.php new file mode 100644 index 0000000000000000000000000000000000000000..786e844908d7753cf7d5571c612f89ee873e0501 --- /dev/null +++ b/core/Updates/2.14.2.php @@ -0,0 +1,132 @@ +migration = $factory; + } + + /** + * Removes option entries for columns that are marked as installed but are actually no longer installed due to + * a bug in previous versions where the option entries were not correctly removed. + * + * @return array + */ + public function getMigrations(Updater $updater) + { + $visitMigrations = $this->getMigrationsThatRemoveOptionEntriesOfNotActuallyInstalledColumns(VisitDimension::INSTALLER_PREFIX, 'log_visit'); + $actionMigrations = $this->getMigrationsThatRemoveOptionEntriesOfNotActuallyInstalledColumns(ActionDimension::INSTALLER_PREFIX, 'log_link_visit_action'); + $conversionMigrations = $this->getMigrationsThatRemoveOptionEntriesOfNotActuallyInstalledColumns(ConversionDimension::INSTALLER_PREFIX, 'log_conversion'); + + $migrations = array(); + + foreach ($visitMigrations as $migration) { + $migrations[] = $migration; + } + + foreach ($actionMigrations as $migration) { + $migrations[] = $migration; + } + + foreach ($conversionMigrations as $migration) { + $migrations[] = $migration; + } + + return $migrations; + } + + private function getMigrationsThatRemoveOptionEntriesOfNotActuallyInstalledColumns($dimensionPrefix, $tableName) + { + $componentPrefix = 'version_' . $dimensionPrefix; + + $notActuallyInstalledColumns = self::getNotActuallyInstalledColumnNames($componentPrefix, $tableName); + + $sqls = array(); + foreach ($notActuallyInstalledColumns as $column) { + $sqls[] = $this->buildRemoveOptionEntrySql($componentPrefix . $column); + } + + return $sqls; + } + + private function buildRemoveOptionEntrySql($optionName) + { + $tableName = Common::prefixTable('option'); + + $sql = sprintf("DELETE FROM `%s` WHERE `option_name` = ?", $tableName); + + return $this->migration->db->boundSql($sql, array($optionName)); + } + + /** + * @param string $componentPrefix + * @param string $tableName + * @return array An array of columns that are marked as installed but are actually removed. There was a bug + * where option entries were not correctly removed. eg array('idvist', 'server_time', ...) + */ + private static function getNotActuallyInstalledColumnNames($componentPrefix, $tableName) + { + $installedVisitColumns = self::getMarkedAsInstalledColumns($componentPrefix); + $existingVisitColumns = self::getActuallyExistingColumns($tableName); + + return array_diff($installedVisitColumns, $existingVisitColumns); + } + + /** + * @param string $componentPrefix eg 'version_log_visit.' + * @return array An array of column names that are marked as installed. eg array('idvist', 'server_time', ...) + */ + private static function getMarkedAsInstalledColumns($componentPrefix) + { + $installedVisitColumns = Option::getLike($componentPrefix . '%'); + $installedVisitColumns = array_keys($installedVisitColumns); + $installedVisitColumns = array_map(function ($entry) use ($componentPrefix) { + return str_replace($componentPrefix, '', $entry); + }, $installedVisitColumns); + + return $installedVisitColumns; + } + + /** + * @param string $tableName + * @return array An array of actually existing column names in the given table. eg array('idvist', 'server_time', ...) + */ + private static function getActuallyExistingColumns($tableName) + { + $tableName = Common::prefixTable($tableName); + return array_keys(DbHelper::getTableColumns($tableName)); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.15.0-b12.php b/core/Updates/2.15.0-b12.php new file mode 100644 index 0000000000000000000000000000000000000000..138e710c26b989dedc33dff0f2b416d85af1c681 --- /dev/null +++ b/core/Updates/2.15.0-b12.php @@ -0,0 +1,44 @@ +migrateBetaUpgradesToReleaseChannel(); + } + + private function migrateBetaUpgradesToReleaseChannel() + { + $config = Config::getInstance(); + $debug = $config->Debug; + + if (array_key_exists('allow_upgrades_to_beta', $debug)) { + $allowUpgradesToBeta = 1 == $debug['allow_upgrades_to_beta']; + unset($debug['allow_upgrades_to_beta']); + + $general = $config->General; + if ($allowUpgradesToBeta) { + $general['release_channel'] = 'latest_beta'; + } else { + $general['release_channel'] = 'latest_stable'; + } + + $config->Debug = $debug; + $config->General = $general; + $config->forceSave(); + } + } +} diff --git a/core/Updates/2.15.0-b16.php b/core/Updates/2.15.0-b16.php new file mode 100644 index 0000000000000000000000000000000000000000..762594a232b13196d41c906a5bec3df69d585c90 --- /dev/null +++ b/core/Updates/2.15.0-b16.php @@ -0,0 +1,44 @@ +uninstallPlugin('LeftMenu'); + $this->uninstallPlugin('ZenMode'); + } + + private function uninstallPlugin($plugin) + { + $pluginManager = Manager::getInstance(); + + if ($pluginManager->isPluginInstalled($plugin)) { + if ($pluginManager->isPluginActivated($plugin)) { + $pluginManager->deactivatePlugin($plugin); + } + + $pluginManager->unloadPlugin($plugin); + $pluginManager->uninstallPlugin($plugin); + } else { + $this->makeSurePluginIsRemovedFromFilesystem($plugin); + } + } + + private function makeSurePluginIsRemovedFromFilesystem($plugin) + { + Manager::deletePluginFromFilesystem($plugin); + } +} diff --git a/core/Updates/2.15.0-b17.php b/core/Updates/2.15.0-b17.php new file mode 100644 index 0000000000000000000000000000000000000000..afd281beda8454c4f0e8f976670673f49f5cff2e --- /dev/null +++ b/core/Updates/2.15.0-b17.php @@ -0,0 +1,42 @@ +removeDeprecatedDebugConfig('enable_measure_piwik_usage_in_idsite'); + } + + private function removeDeprecatedDebugConfig($name) + { + $config = Config::getInstance(); + $debug = $config->Debug; + unset($debug[$name]); + $config->Debug = $debug; + $config->forceSave(); + } +} diff --git a/core/Updates/2.15.0-b20.php b/core/Updates/2.15.0-b20.php new file mode 100644 index 0000000000000000000000000000000000000000..a2a248975b0fdac49277e6a529bf2e1fc089e731 --- /dev/null +++ b/core/Updates/2.15.0-b20.php @@ -0,0 +1,39 @@ +makeSurePluginIsRemovedFromFilesystem('ZenMode'); + $this->makeSurePluginIsRemovedFromFilesystem('LeftMenu'); + } + + private function makeSurePluginIsRemovedFromFilesystem($plugin) + { + Plugin\Manager::deletePluginFromFilesystem($plugin); + } +} diff --git a/core/Updates/2.15.0-b3.php b/core/Updates/2.15.0-b3.php new file mode 100644 index 0000000000000000000000000000000000000000..e2171ba7b57a6cc886af4def5c3e8ede78b7a12d --- /dev/null +++ b/core/Updates/2.15.0-b3.php @@ -0,0 +1,39 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('site', 'exclude_unknown_urls', 'TINYINT(1) DEFAULT 0', 'currency'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.15.0.php b/core/Updates/2.15.0.php new file mode 100644 index 0000000000000000000000000000000000000000..5dbe94c88561c06091a7a2f9461dd2e791101c87 --- /dev/null +++ b/core/Updates/2.15.0.php @@ -0,0 +1,39 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->plugin->activate('Heartbeat'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.16.2-b2.php b/core/Updates/2.16.2-b2.php new file mode 100644 index 0000000000000000000000000000000000000000..fe27c49a0de224648ee8783006622af44b2212a0 --- /dev/null +++ b/core/Updates/2.16.2-b2.php @@ -0,0 +1,32 @@ +isPluginActivated($pluginName)) { + $pluginManager->activatePlugin($pluginName); + } + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/2.16.2-rc2.php b/core/Updates/2.16.2-rc2.php new file mode 100644 index 0000000000000000000000000000000000000000..502f32cf33c4b5fbf4657f69fa651b0728872bc2 --- /dev/null +++ b/core/Updates/2.16.2-rc2.php @@ -0,0 +1,33 @@ +activatePlugin('ProfessionalServices'); + } catch (\Exception $e) { + } + + try { + \Piwik\Plugin\Manager::getInstance()->deactivatePlugin('PiwikPro'); + self::deletePluginFromConfigFile('PiwikPro'); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/2.16.3-b1.php b/core/Updates/2.16.3-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..b5d77d0b17735c8e52f870cd731ca11b0bc8bd6b --- /dev/null +++ b/core/Updates/2.16.3-b1.php @@ -0,0 +1,22 @@ +activatePlugin('CustomJsTracker'); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/2.16.3-rc2.php b/core/Updates/2.16.3-rc2.php new file mode 100644 index 0000000000000000000000000000000000000000..86118228f15d7f8200a50e3b4a09efa3d9e7d0f6 --- /dev/null +++ b/core/Updates/2.16.3-rc2.php @@ -0,0 +1,23 @@ +getReports(); + foreach ($allReports as $report) { + $update = array('hour' => $this->adjustTimezoneBySite($report['hour'], $report['idsite'])); + $model->updateReport($report['idreport'], $update); + } + } + + protected function adjustTimezoneBySite($hour, $idSite) + { + $timezone = Site::getTimezoneFor($idSite); + $timeZoneDifference = -ceil(Date::getUtcOffset($timezone) / 3600); + return (24 + $hour + $timeZoneDifference) % 24; + } +} diff --git a/core/Updates/2.2.3-b6.php b/core/Updates/2.2.3-b6.php new file mode 100644 index 0000000000000000000000000000000000000000..baf01ed826718d38fd233c1d0da8b2de4e24cb5e --- /dev/null +++ b/core/Updates/2.2.3-b6.php @@ -0,0 +1,24 @@ +activatePlugin('ZenMode'); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/2.4.0-b1.php b/core/Updates/2.4.0-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..c1d1d9f01e2674a569460736f883fa7f4c61798c --- /dev/null +++ b/core/Updates/2.4.0-b1.php @@ -0,0 +1,30 @@ +activatePlugin('Morpheus'); + } catch (\Exception $e) { + } + + try { + \Piwik\Plugin\Manager::getInstance()->deactivatePlugin('Zeitgeist'); + self::deletePluginFromConfigFile('Zeitgeist'); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/2.4.0-b3.php b/core/Updates/2.4.0-b3.php new file mode 100644 index 0000000000000000000000000000000000000000..5e9324ea879b90dde7d05a75c2d8eeed747db058 --- /dev/null +++ b/core/Updates/2.4.0-b3.php @@ -0,0 +1,36 @@ +activatePlugin('LeftMenu'); + } catch (\Exception $e) { + } + + try { + $pluginManager->deactivatePlugin('Zeitgeist'); + } catch (\Exception $e) { + } + + try { + $pluginManager->uninstallPlugin('Zeitgeist'); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/2.4.0-b4.php b/core/Updates/2.4.0-b4.php new file mode 100644 index 0000000000000000000000000000000000000000..b021e363d00726ac6aa95331dd7128d9a9697a92 --- /dev/null +++ b/core/Updates/2.4.0-b4.php @@ -0,0 +1,36 @@ +getAllPluginsNames(); + + if (!in_array('Zeitgeist', $pluginNames)) { + return; + } + + try { + $pluginManager->deactivatePlugin('Zeitgeist'); + } catch (\Exception $e) { + } + + try { + $pluginManager->uninstallPlugin('Zeitgeist'); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/2.4.0-b6.php b/core/Updates/2.4.0-b6.php new file mode 100644 index 0000000000000000000000000000000000000000..ef76c472131f2b860b460e22fc14832e8d288721 --- /dev/null +++ b/core/Updates/2.4.0-b6.php @@ -0,0 +1,26 @@ +activatePlugin('DevicesDetection'); + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/2.4.0-b8.php b/core/Updates/2.4.0-b8.php new file mode 100644 index 0000000000000000000000000000000000000000..bd7acd297a9223672e01c602f9bdbd535562c0c0 --- /dev/null +++ b/core/Updates/2.4.0-b8.php @@ -0,0 +1,39 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->changeColumnType('session', 'id', 'VARCHAR( 255 ) NOT NULL'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.5.0-b1.php b/core/Updates/2.5.0-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..cb71d607e216e9cd5c5b932dfea872e0648f6a03 --- /dev/null +++ b/core/Updates/2.5.0-b1.php @@ -0,0 +1,38 @@ +Debug; + + if (array_key_exists('disable_merged_assets', $debug)) { + $development = $config->Development; + $development['disable_merged_assets'] = $debug['disable_merged_assets']; + unset($debug['disable_merged_assets']); + + $config->Debug = $debug; + $config->Development = $development; + $config->forceSave(); + } + } +} diff --git a/core/Updates/2.5.0-rc2.php b/core/Updates/2.5.0-rc2.php new file mode 100644 index 0000000000000000000000000000000000000000..1cc3f5ccaa7f5c38555a40b61eadebbc31b414a3 --- /dev/null +++ b/core/Updates/2.5.0-rc2.php @@ -0,0 +1,68 @@ +Plugins_Tracker = array(); + $config->forceSave(); + } +} diff --git a/core/Updates/2.7.0-b2.php b/core/Updates/2.7.0-b2.php new file mode 100644 index 0000000000000000000000000000000000000000..52ce503b5e918d01827753aa8deb891e4a0c5c0b --- /dev/null +++ b/core/Updates/2.7.0-b2.php @@ -0,0 +1,39 @@ +migration = $factory; + } + + public function getMigrationss(Updater $updater) + { + return array( + $this->migration->plugin->activate('Contents'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/2.7.0-b4.php b/core/Updates/2.7.0-b4.php new file mode 100644 index 0000000000000000000000000000000000000000..19fea66e2c7f5e77289882dd3fcc6f0130439bbe --- /dev/null +++ b/core/Updates/2.7.0-b4.php @@ -0,0 +1,31 @@ +activatePlugin('Contents'); + } catch (\Exception $e) { + } + } + + public static function isMajorUpdate() + { + return true; + } +} diff --git a/core/Updates/2.9.0-b1.php b/core/Updates/2.9.0-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..61957df103489621b3fef1fa66d555cb703537d8 --- /dev/null +++ b/core/Updates/2.9.0-b1.php @@ -0,0 +1,96 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migrations = array(); + $migrations = $this->updateBrowserEngine($migrations); + $migrations[] = $this->migration->plugin->activate('TestRunner'); + + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + + self::updateIPAnonymizationSettings(); + } + + private function updateBrowserEngine($sql) + { + $sql[] = $this->migration->db->addColumn('log_visit', 'config_browser_engine', 'VARCHAR(10) NOT NULL'); + + $browserEngineMatch = array( + 'Trident' => array('IE'), + 'Gecko' => array('NS', 'PX', 'FF', 'FB', 'CA', 'GA', 'KM', 'MO', 'SM', 'CO', 'FE', 'KP', 'KZ', 'TB'), + 'KHTML' => array('KO'), + 'WebKit' => array('SF', 'CH', 'OW', 'AR', 'EP', 'FL', 'WO', 'AB', 'IR', 'CS', 'FD', 'HA', 'MI', 'GE', 'DF', 'BB', 'BP', 'TI', 'CF', 'RK', 'B2', 'NF'), + 'Presto' => array('OP'), + ); + + // Update visits, fill in now missing engine + $engineUpdate = "''"; + $ifFragment = "IF (`config_browser_name` IN ('%s'), '%s', %s)"; + + foreach ($browserEngineMatch as $engine => $browsers) { + $engineUpdate = sprintf($ifFragment, implode("','", $browsers), $engine, $engineUpdate); + } + + $engineUpdate = sprintf("UPDATE `%s` SET `config_browser_engine` = %s", Common::prefixTable('log_visit'), $engineUpdate); + $sql[] = $this->migration->db->sql($engineUpdate); + + $archiveBlobTables = Db::get()->fetchCol("SHOW TABLES LIKE '%archive_blob%'"); + + // for each blob archive table, rename UserSettings_browserType to DevicesDetection_browserEngines + foreach ($archiveBlobTables as $table) { + // try to rename old archives + $query = sprintf("UPDATE IGNORE `%s` SET name='DevicesDetection_browserEngines' WHERE name = 'UserSettings_browserType'", $table); + $sql[] = $this->migration->db->sql($query); + } + + return $sql; + } + + private static function updateIPAnonymizationSettings() + { + $optionName = 'PrivacyManager.ipAnonymizerEnabled'; + + $value = Option::get($optionName); + + if ($value !== false) { + // If the config is defined, nothing to do + return; + } + + // We disable IP anonymization if it wasn't configured (because by default it has gone from disabled to enabled) + Option::set($optionName, '0'); + } +} diff --git a/core/Updates/2.9.0-b7.php b/core/Updates/2.9.0-b7.php new file mode 100644 index 0000000000000000000000000000000000000000..4be710f255a0f29212d9a225e3bbda08c1509502 --- /dev/null +++ b/core/Updates/2.9.0-b7.php @@ -0,0 +1,81 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migrations = array(); + $migrations = $this->addCreateSequenceTableQuery($migrations); + $migrations = $this->addArchivingIdMigrationQueries($migrations); + + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } + + private function addArchivingIdMigrationQueries($sql) + { + $tables = ArchiveTableCreator::getTablesArchivesInstalled(); + + foreach ($tables as $table) { + $type = ArchiveTableCreator::getTypeFromTableName($table); + + if ($type === ArchiveTableCreator::NUMERIC_TABLE) { + $maxId = Db::fetchOne('SELECT MAX(idarchive) FROM `' . $table . '`'); + + if (!empty($maxId)) { + $maxId = (int) $maxId + 500; + } else { + $maxId = 1; + } + + $sql[] = $this->migration->db->insert($this->sequenceTable, array('name' => $table, 'value' => $maxId)); + } + } + + return $sql; + } + + /** + * @return string + */ + private function addCreateSequenceTableQuery($sql) + { + $sql[] = $this->migration->db->createTable($this->sequenceTable, array( + 'name' => 'VARCHAR(120) NOT NULL', + 'value' => 'BIGINT(20) UNSIGNED NOT NULL', + ), $primary = 'name'); + + return $sql; + } +} diff --git a/core/Updates/3.0.0-b1.php b/core/Updates/3.0.0-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..5226c231bcb4870b888dfc06b7768ec7634773d3 --- /dev/null +++ b/core/Updates/3.0.0-b1.php @@ -0,0 +1,506 @@ +migration = $factory; + } + + /** + * Here you can define one or multiple SQL statements that should be executed during the update. + * @return Migration[] + */ + public function getMigrations(Updater $updater) + { + $db = Db::get(); + $allGoals = $db->fetchAll(sprintf("SELECT DISTINCT idgoal FROM `%s`", Common::prefixTable('goal'))); + $allDashboards = $db->fetchAll(sprintf("SELECT * FROM `%s`", Common::prefixTable('user_dashboard'))); + + $migrations = $this->getDashboardMigrations($allDashboards, $allGoals); + $migrations = $this->getPluginSettingsMigrations($migrations); + $migrations = $this->getSiteSettingsMigrations($migrations); + $migrations = $this->getBigIntPreventOverflowMigrations($migrations); + + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + $this->migratePluginEmailUpdateSetting(); + + // added .woff and woff2 allowlisted file for apache webserver + ServerFilesGenerator::deleteHtAccessFiles(); + ServerFilesGenerator::createHtAccessFiles(); + + // Renamed plugin ExampleRssWidget -> RssWidget + \Piwik\Plugin\Manager::getInstance()->activatePlugin('RssWidget'); + \Piwik\Plugin\Manager::getInstance()->deactivatePlugin('ExampleRssWidget'); + } + + private function migratePluginEmailUpdateSetting() + { + $isEnabled = Option::get('enableUpdateCommunicationPlugins'); + + Access::doAsSuperUser(function () use ($isEnabled) { + $table = Common::prefixTable('plugin_setting'); + $sql = "INSERT INTO $table (`plugin_name`, `user_login`, `setting_name`, `setting_value`) VALUES (?, ?, ?, ?)"; + $bind = array('CoreUpdater', '', 'enable_plugin_update_communication', (int) !empty($isEnabled)); + Db::query($sql, $bind); + }); + } + + /** + * @param Migration[] $queries + * @return Migration[] + */ + private function getBigIntPreventOverflowMigrations($queries) + { + $queries[] = $this->migration->db->changeColumnTypes('log_visit', array( + 'idvisit' => 'BIGINT(10) UNSIGNED NOT NULL AUTO_INCREMENT', + )); + + $queries[] = $this->migration->db->changeColumnTypes('log_conversion_item', array( + 'idvisit' => 'BIGINT(10) UNSIGNED NOT NULL', + )); + + $queries[] = $this->migration->db->changeColumnTypes('log_conversion', array( + 'idvisit' => 'BIGINT(10) UNSIGNED NOT NULL', + 'idlink_va' => 'BIGINT(10) UNSIGNED default NULL', + )); + + $queries[] = $this->migration->db->changeColumnTypes('log_link_visit_action', array( + 'idlink_va' => 'BIGINT(10) UNSIGNED NOT NULL AUTO_INCREMENT', + 'idvisit' => 'BIGINT(10) UNSIGNED NOT NULL', + + // Note; this column is made NULLable for #9231 + 'idaction_name_ref' => 'INTEGER(10) UNSIGNED NULL', + )); + + return $queries; + } + + /** + * @param Migration[] $queries + * @return Migration[] + */ + private function getPluginSettingsMigrations($queries) + { + $queries[] = $this->migration->db->createTable($this->pluginSettingsTable, array( + 'plugin_name' => 'VARCHAR(60) NOT NULL', + 'setting_name' => 'VARCHAR(255) NOT NULL', + 'setting_value' => 'LONGTEXT NOT NULL', + 'user_login' => "VARCHAR(100) NOT NULL DEFAULT ''", + )); + $queries[] = $this->migration->db->addIndex($this->pluginSettingsTable, array('plugin_name', 'user_login')); + + $optionTable = Common::prefixTable('option'); + $query = 'SELECT `option_name`, `option_value` FROM `' . $optionTable . '` WHERE `option_name` LIKE "Plugin_%_Settings"'; + $options = Db::get()->fetchAll($query); + + foreach ($options as $option) { + $name = $option['option_name']; + $pluginName = str_replace(array('Plugin_', '_Settings'), '', $name); + $values = Common::safe_unserialize($option['option_value']); + + if (empty($values)) { + continue; + } + + foreach ($values as $settingName => $settingValue) { + if (!is_array($settingValue)) { + $settingValue = array($settingValue); + } + + foreach ($settingValue as $val) { + $queries[] = $this->createPluginSettingQuery($pluginName, $settingName, $val); + } + } + } + + $queries[] = $this->migration->db->sql(sprintf('DELETE FROM `%s` WHERE `option_name` like "Plugin_%%_Settings"', $optionTable)); + + return $queries; + } + + /** + * @param Migration[] $queries + * @return Migration[] + */ + private function getSiteSettingsMigrations($queries) + { + $table = $this->siteSettingsTable; + + // we cannot migrate existing settings as we do not know the related plugin name, but this feature + // (measurablesettings) was not used anyway. also see https://github.com/piwik/piwik/issues/10703 + // we make sure to recreate the table as it might not have existed for some users instead of just + // deleting the content of it + $queries[] = $this->migration->db->dropTable($table); + $queries[] = $this->migration->db->createTable($table, array( + 'idsite' => 'INTEGER(10) UNSIGNED NOT NULL', + 'plugin_name' => 'VARCHAR(60) NOT NULL', + 'setting_name' => 'VARCHAR(255) NOT NULL', + 'setting_value' => 'LONGTEXT NOT NULL', + )); + + $table = Common::prefixTable($table); + $queries[] = $this->migration->db->sql( + "ALTER TABLE `$table` ADD INDEX(idsite, plugin_name);", + Migration\Db::ERROR_CODE_COLUMN_NOT_EXISTS + ); + + return $queries; + } + + private function createPluginSettingQuery($pluginName, $settingName, $settingValue) + { + $login = ''; + if (preg_match('/^.+#(.+)#$/', $settingName, $matches)) { + $login = $matches[1]; + $settingName = str_replace('#' . $login . '#', '', $settingName); + } + + return $this->migration->db->insert($this->pluginSettingsTable, array( + 'plugin_name' => $pluginName, + 'setting_name' => $settingName, + 'setting_value' => $settingValue, + 'user_login' => $login, + )); + } + + private function getDashboardMigrations($allDashboards, $allGoals) + { + $sqls = array(); + + // update dashboard to use new widgets + $oldWidgets = array( + array ( + 'module' => 'VisitTime', + 'action' => 'getVisitInformationPerServerTime', + 'params' => + array ( + ), + ),array ( + 'module' => 'VisitTime', + 'action' => 'getVisitInformationPerLocalTime', + 'params' => + array ( + ), + ),array ( + 'module' => 'VisitTime', + 'action' => 'getByDayOfWeek', + 'params' => + array ( + ), + ),array ( + 'module' => 'VisitsSummary', + 'action' => 'getEvolutionGraph', + 'params' => + array ( + 'columns' => array ('nb_visits'), + ), + ),array ( + 'module' => 'VisitsSummary', + 'action' => 'getSparklines', + 'params' => + array ( + ), + ),array ( + 'module' => 'VisitsSummary', + 'action' => 'index', + 'params' => + array ( + ), + ),array ( + 'module' => 'Live', + 'action' => 'getVisitorLog', + 'params' => + array ('small' => 1), + ),array ( + 'module' => 'VisitorInterest', + 'action' => 'getNumberOfVisitsPerVisitDuration', + 'params' => + array ( + ), + ),array ( + 'module' => 'VisitorInterest', + 'action' => 'getNumberOfVisitsPerPage', + 'params' => + array ( + ), + ),array ( + 'module' => 'VisitFrequency', + 'action' => 'getSparklines', + 'params' => + array ( + ), + ),array ( + 'module' => 'VisitFrequency', + 'action' => 'getEvolutionGraph', + 'params' => + array ( + 'columns' => array ('nb_visits_returning'), + ), + ),array ( + 'module' => 'DevicesDetection', + 'action' => 'getBrowserEngines', + 'params' => + array ( + ), + ),array ( + 'module' => 'Referrers', + 'action' => 'getReferrerType', + 'params' => + array ( + ), + ),array ( + 'module' => 'Referrers', + 'action' => 'getAll', + 'params' => + array ( + ), + ),array ( + 'module' => 'Referrers', + 'action' => 'getSocials', + 'params' => + array ( + ), + ),array ( + 'module' => 'Goals', + 'action' => 'widgetGoalsOverview', + 'params' => + array ( + ), + ),array ( + 'module' => 'Goals', + 'action' => 'getItemsSku', + 'params' => + array ( + ), + ),array ( + 'module' => 'Goals', + 'action' => 'getItemsName', + 'params' => + array ( + ), + ),array ( + 'module' => 'Goals', + 'action' => 'getItemsCategory', + 'params' => + array ( + ), + ),array ( + 'module' => 'Ecommerce', + 'action' => 'widgetGoalReport', + 'params' => + array ( + 'idGoal' => 'ecommerceOrder', + ), + ), + ); + + foreach ($allGoals as $goal) { + $oldWidgets[] = array ( + 'module' => 'Goals', + 'action' => 'widgetGoalReport', + 'params' => + array ( + 'idGoal' => (int) $goal['idgoal'], + )); + } + + $newWidgets = array( + array ( + 'module' => 'VisitTime', + 'action' => 'getVisitInformationPerServerTime', + 'params' => + array ( + ), + ),array ( + 'module' => 'VisitTime', + 'action' => 'getVisitInformationPerLocalTime', + 'params' => + array ( + ), + ),array ( + 'module' => 'VisitTime', + 'action' => 'getByDayOfWeek', + 'params' => + array ( + ), + ),array ( + 'module' => 'VisitsSummary', + 'action' => 'getEvolutionGraph', + 'params' => + array ( + 'forceView' => '1', + 'viewDataTable' => 'graphEvolution', + ), + ),array ( + 'module' => 'VisitsSummary', + 'action' => 'get', + 'params' => + array ( + 'forceView' => '1', + 'viewDataTable' => 'sparklines', + ), + ),array ( + 'module' => 'CoreHome', + 'action' => 'renderWidgetContainer', + 'uniqueId' => 'widgetVisitOverviewWithGraph', + 'params' => + array ( + 'containerId' => 'VisitOverviewWithGraph', + ), + ),array ( + 'module' => 'Live', + 'action' => 'getLastVisitsDetails', + 'params' => + array ( + 'forceView' => '1', + 'viewDataTable' => 'VisitorLog', + 'small' => '1', + ), + ),array ( + 'module' => 'VisitorInterest', + 'action' => 'getNumberOfVisitsPerVisitDuration', + 'params' => + array ( + ), + ),array ( + 'module' => 'VisitorInterest', + 'action' => 'getNumberOfVisitsPerPage', + 'params' => + array ( + ), + ),array ( + 'module' => 'VisitFrequency', + 'action' => 'get', + 'params' => + array ( + 'forceView' => '1', + 'viewDataTable' => 'sparklines', + ), + ),array ( + 'module' => 'VisitFrequency', + 'action' => 'getEvolutionGraph', + 'params' => + array ( + 'forceView' => 1, + 'viewDataTable' => 'graphEvolution', + ), + ),array ( + 'module' => 'DevicesDetection', + 'action' => 'getBrowserEngines', + 'params' => + array ( + ), + ),array ( + 'module' => 'Referrers', + 'action' => 'getReferrerType', + 'params' => + array ( + ), + ),array ( + 'module' => 'Referrers', + 'action' => 'getAll', + 'params' => + array ( + ), + ),array ( + 'module' => 'Referrers', + 'action' => 'getSocials', + 'params' => + array ( + ), + ),array ( + 'module' => 'CoreHome', + 'action' => 'renderWidgetContainer', + 'uniqueId' => 'widgetGoalsOverview', + 'params' => + array ( + 'containerId' => 'GoalsOverview', + ), + ),array ( + 'module' => 'Goals', + 'action' => 'getItemsSku', + 'params' => array (), + ),array ( + 'module' => 'Goals', + 'action' => 'getItemsName', + 'params' => array (), + ),array ( + 'module' => 'Goals', + 'action' => 'getItemsCategory', + 'params' => array (), + ),array ( + 'module' => 'CoreHome', + 'action' => 'renderWidgetContainer', + 'uniqueId' => 'widgetEcommerceOverview', + 'params' => + array ( + 'containerId' => 'EcommerceOverview', + ), + ), + ); + + foreach ($allGoals as $goal) { + $newWidgets[] = array ( + 'module' => 'CoreHome', + 'action' => 'renderWidgetContainer', + 'uniqueId' => 'widgetGoal_' . (int) $goal['idgoal'], + 'params' => + array ( + 'containerId' => 'Goal_' . (int) $goal['idgoal'], + )); + } + + $table = Common::prefixTable('user_dashboard'); + $sql = sprintf('UPDATE `%s` SET layout = ? WHERE iddashboard = ?', $table); + + foreach ($allDashboards as $dashboard) { + $dashboardLayout = json_decode($dashboard['layout']); + + $dashboardLayout = Dashboard\Model::replaceDashboardWidgets($dashboardLayout, $oldWidgets, $newWidgets); + + $newLayout = json_encode($dashboardLayout); + if ($newLayout != $dashboard['layout']) { + $sqls[] = $this->migration->db->boundSql($sql, array($newLayout, $dashboard['iddashboard'])); + } + } + + return $sqls; + } +} diff --git a/core/Updates/3.0.0-b3.php b/core/Updates/3.0.0-b3.php new file mode 100644 index 0000000000000000000000000000000000000000..582e1d8c99310207630db13a27b7acb0235c57eb --- /dev/null +++ b/core/Updates/3.0.0-b3.php @@ -0,0 +1,71 @@ +getConfig()->General; + + // need to check against int(0) value, as if the config setting is not set at all its value is null + if (isset($general[$this->marketplaceEnabledConfigSetting])) { + $isMarketplaceEnabled = 0 !== $general[$this->marketplaceEnabledConfigSetting]; + + $this->removeOldMarketplaceEnabledConfig(); + + if ($isMarketplaceEnabled) { + $this->activateMarketplacePlugin(); + } + } else { + $this->activateMarketplacePlugin(); + } + } + + private function getConfig() + { + return Config::getInstance(); + } + + private function removeOldMarketplaceEnabledConfig() + { + $config = $this->getConfig(); + $general = $config->General; + + if (array_key_exists($this->marketplaceEnabledConfigSetting, $general)) { + unset($general[$this->marketplaceEnabledConfigSetting]); + + $config->General = $general; + $config->forceSave(); + } + } + + public function activateMarketplacePlugin() + { + $pluginManager = Plugin\Manager::getInstance(); + $pluginName = 'Marketplace'; + + if (!$pluginManager->isPluginActivated($pluginName)) { + $pluginManager->activatePlugin($pluginName); + } + } +} diff --git a/core/Updates/3.0.0-b4.php b/core/Updates/3.0.0-b4.php new file mode 100644 index 0000000000000000000000000000000000000000..511b88322025e0acb190cbea37eb73dd525b086e --- /dev/null +++ b/core/Updates/3.0.0-b4.php @@ -0,0 +1,98 @@ +migration = $factory; + } + + /** + * Here you can define one or multiple SQL statements that should be executed during the update. + * @return Migration[] + */ + public function getMigrations(Updater $updater) + { + $migrations = []; + $migrations = $this->getUserDatabaseMigrations($migrations); + + return $migrations; + } + + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + $updater->executeMigrations(__FILE__, $this->getUserPasswordMigrations([])); + + ServerFilesGenerator::createFilesForSecurity(); + } + + /** + * Returns database migrations for this update. + * @param Migration[] $queries + * @return Migration[] + */ + private function getUserDatabaseMigrations($queries) + { + $queries[] = $this->migration->db->changeColumn($this->userTable, 'password', 'password', 'VARCHAR(255) NOT NULL'); + + return $queries; + } + + /** + * Returns migrations to hash existing password with bcrypt. + * @param Migration[] $queries + * @return Migration[] + */ + private function getUserPasswordMigrations($queries) + { + $db = Db::get(); + $userTable = Common::prefixTable($this->userTable); + + $users = $db->fetchAll( + 'SELECT `login`, `password` FROM `' . $userTable . '` WHERE LENGTH(`password`) = 32' + ); + + foreach ($users as $user) { + $queries[] = $this->migration->db->boundSql( + 'UPDATE `' . $userTable . '`' + . ' SET `password` = ?' + . ' WHERE `login` = ?', + [ + password_hash($user['password'], PASSWORD_BCRYPT), + $user['login'], + ] + ); + } + + return $queries; + } +} diff --git a/core/Updates/3.0.1-b1.php b/core/Updates/3.0.1-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..62fea22b854b27c4451ebf2f337762932161eb68 --- /dev/null +++ b/core/Updates/3.0.1-b1.php @@ -0,0 +1,24 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('report', 'period_param', 'VARCHAR(10) NULL'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/3.10.0-rc5.php b/core/Updates/3.10.0-rc5.php new file mode 100644 index 0000000000000000000000000000000000000000..cbe7c8a94bcf482111531998d4b138c7b9d8260f --- /dev/null +++ b/core/Updates/3.10.0-rc5.php @@ -0,0 +1,44 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migration1 = $this->migration->plugin->activate('Tour'); + + return array( + $migration1, + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/3.11.0-b1.php b/core/Updates/3.11.0-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..088d908b6e005aeb95d60619ad78803f34c0532d --- /dev/null +++ b/core/Updates/3.11.0-b1.php @@ -0,0 +1,44 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migration1 = $this->migration->db->changeColumnType('goal', 'pattern_type', 'varchar(25) NOT NULL'); + + return array( + $migration1, + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/3.12.0-b1.php b/core/Updates/3.12.0-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..03df4dbdcb57dc20a59f5a1ce458f75fa3a9ddd1 --- /dev/null +++ b/core/Updates/3.12.0-b1.php @@ -0,0 +1,48 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migration1 = $this->migration->db->createTable('locks', [ + 'key' => 'VARCHAR(70) NOT NULL', + 'value' => 'VARCHAR(255) NULL DEFAULT NULL', + 'expiry_time' => 'BIGINT UNSIGNED DEFAULT 9999999999', + ], 'key'); + + return array( + $migration1, + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/3.12.0-b7.php b/core/Updates/3.12.0-b7.php new file mode 100644 index 0000000000000000000000000000000000000000..eb58971b5dd0a9f2a918e2dfa395406eb436dfd1 --- /dev/null +++ b/core/Updates/3.12.0-b7.php @@ -0,0 +1,46 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migration1 = $this->migration->plugin->deactivate('ExamplePlugin'); + $migration2 = $this->migration->plugin->deactivate('ExampleAPI'); + + return array( + $migration1, + $migration2, + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/3.13.1-b2.php b/core/Updates/3.13.1-b2.php new file mode 100644 index 0000000000000000000000000000000000000000..2a5035790b0fa489da39f6a2d782bd9017af0800 --- /dev/null +++ b/core/Updates/3.13.1-b2.php @@ -0,0 +1,55 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $geoIpLiteUrl = 'https://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz'; + $optionTable = Common::prefixTable('option'); + $migration1 = $this->migration->db->boundSql( + "UPDATE `$optionTable` SET option_value = ? WHERE option_name = ? AND option_value = ?", + [GeoIp2::getDbIpLiteUrl(), GeoIP2AutoUpdater::LOC_URL_OPTION_NAME, $geoIpLiteUrl] + ); + $migration2 = $this->migration->db->boundSql( + "UPDATE `$optionTable` SET option_value = ? WHERE option_name = ? AND option_value = ?", + [GeoIp2::getDbIpLiteUrl('country'), GeoIP2AutoUpdater::LOC_URL_OPTION_NAME, self::GEO_LITE_COUNTRY_URL] + ); + return [$migration1, $migration2]; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/3.13.4-b1.php b/core/Updates/3.13.4-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..18ffabf670f96fe1a4b1ef128a5653e691e0a716 --- /dev/null +++ b/core/Updates/3.13.4-b1.php @@ -0,0 +1,23 @@ +addArchivesToPurge(); + } + + private function addArchivesToPurge() + { + $archivesToPurge = new ArchivesToPurgeDistributedList(); + + $startOfProblem = Date::factory('2020-01-01 00:00:00'); + + $archiveTables = ArchiveTableCreator::getTablesArchivesInstalled(ArchiveTableCreator::NUMERIC_TABLE); + foreach ($archiveTables as $table) { + $date = ArchiveTableCreator::getDateFromTableName($table); + list($year, $month) = explode('_', $date); + + // only add if the table is for jan 2020 or above since tables w/ that date will be most affected + try { + $dateObj = Date::factory("$year-$month-01 00:00:00"); + } catch (\Exception $ex) { + continue; // date is too old for some reason + } + + if ($dateObj->isEarlier($startOfProblem)) { + continue; + } + + $archivesToPurge->add("{$year}_{$month}"); + } + } +} diff --git a/core/Updates/3.5.0-b2.php b/core/Updates/3.5.0-b2.php new file mode 100644 index 0000000000000000000000000000000000000000..c319b3dffbcf94cae9d8d0f286e777294bf6a7f6 --- /dev/null +++ b/core/Updates/3.5.0-b2.php @@ -0,0 +1,57 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $columns = array( + 'idlogdata_anonymization' => 'BIGINT UNSIGNED NOT NULL AUTO_INCREMENT', + 'idsites' => 'TEXT NULL DEFAULT NULL', + 'date_start' => 'DATETIME NOT NULL', + 'date_end' => 'DATETIME NOT NULL', + 'anonymize_ip' => 'TINYINT(1) UNSIGNED NOT NULL DEFAULT 0', + 'anonymize_location' => 'TINYINT(1) UNSIGNED NOT NULL DEFAULT 0', + 'anonymize_userid' => 'TINYINT(1) UNSIGNED NOT NULL DEFAULT 0', + 'unset_visit_columns' => "TEXT NOT NULL DEFAULT ''", + 'unset_link_visit_action_columns' => "TEXT NOT NULL DEFAULT ''", + 'output' => 'MEDIUMTEXT NULL DEFAULT NULL', + 'scheduled_date' => 'DATETIME NULL', + 'job_start_date' => 'DATETIME NULL', + 'job_finish_date' => 'DATETIME NULL', + 'requester' => "VARCHAR(100) NOT NULL DEFAULT ''", + ); + return array( + $this->migration->db->createTable(LogDataAnonymizations::getDbTableName(), $columns, $primary = 'idlogdata_anonymization'), + $this->migration->db->addIndex(LogDataAnonymizations::getDbTableName(), array('job_start_date')), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/3.5.0-b4.php b/core/Updates/3.5.0-b4.php new file mode 100644 index 0000000000000000000000000000000000000000..463eda0c9d7e8de0e44c97eac8ea701453add615 --- /dev/null +++ b/core/Updates/3.5.0-b4.php @@ -0,0 +1,40 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('plugin_setting', 'json_encoded', 'TINYINT UNSIGNED NOT NULL DEFAULT 0'), + $this->migration->db->addColumn('site_setting', 'json_encoded', 'TINYINT UNSIGNED NOT NULL DEFAULT 0'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/3.5.0-rc2.php b/core/Updates/3.5.0-rc2.php new file mode 100644 index 0000000000000000000000000000000000000000..41276e4315738a19b137e57a64e814c9dcea50a2 --- /dev/null +++ b/core/Updates/3.5.0-rc2.php @@ -0,0 +1,25 @@ +isPluginActivated('GeoIP2')) { + @Manager::getInstance()->deactivatePlugin('GeoIP2'); + $notification = new Notification('GeoIP2 plugin from Marketplace has been removed due to compatibility issues. Please check your geolocation settings.'); + $notification->context = Notification::CONTEXT_WARNING; + $notification->type = Notification::TYPE_PERSISTENT; + Notification\Manager::notify('GeoIP2_update_warning', $notification); + } + + // uninstall the plugin to remove it from config + @Manager::getInstance()->uninstallPlugin('GeoIP2'); + } + } catch (\Exception $e) { + } + } +} diff --git a/core/Updates/3.6.0-b2.php b/core/Updates/3.6.0-b2.php new file mode 100644 index 0000000000000000000000000000000000000000..c6348a897af15d4e64dff8f4d337557c9febe6ff --- /dev/null +++ b/core/Updates/3.6.0-b2.php @@ -0,0 +1,117 @@ +migration = $factory; + } + + /** + * Here you can define one or multiple SQL statements that should be executed during the update. + * @return Migration[] + */ + public function getMigrations(Updater $updater) + { + $migrations = []; + + // in the previous 2.14.0-b2 idsite was added w/ AUTO_INCREMENT, but it should not have been. (note: this + // should have been undone in the 3.0.0-b1 update, but at least one instance out there still has the + // AUTO_INCREMENT modifier). + $migrations[] = $this->migration->db->changeColumn($this->siteSettingsTable, 'idsite', 'idsite', 'INTEGER(10) UNSIGNED NOT NULL'); + + $migrations = $this->getPluginSettingsMigrations($migrations); + $migrations = $this->getSiteSettingsMigrations($migrations); + $migrations = $this->getLogProfilingMigrations($migrations); + + $accessColumns = DbHelper::getTableColumns(Common::prefixTable('access')); + + // changes for ACL + $migrations[] = $this->migration->db->changeColumnType('access', 'access', 'VARCHAR(50) NULL'); + if (!isset($accessColumns['idaccess'])) { + // the test UpdaterTest::testUpdateWorksAfterPiwikIsAlreadyUpToDate() runs this update on the new DB schema which + // already includes the idaccess column including auto_increment statement. It then fails cause it cannot drop + // the primary key from idaccess as it also has an auto_increment. But in normal case when not executed in that test + // it would remove the primary key (login,idsite). So we ensure to execute this only if the idaccess column not already + // exists + $migrations[] = $this->migration->db->dropPrimaryKey('access'); + $migrations[] = $this->migration->db->addColumn('access', 'idaccess', 'INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT'); + $migrations[] = $this->migration->db->addIndex('access', array('login', 'idsite'), 'index_loginidsite'); + } + + // changes for session auth + $migrations[] = $this->migration->db->addColumn( + 'user', + 'ts_password_modified', + 'TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP' + ); + + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } + + /** + * @param Migration[] $queries + * @return Migration[] + */ + private function getPluginSettingsMigrations($queries) + { + $queries[] = $this->migration->db->addColumn($this->pluginSettingsTable, 'idplugin_setting', 'BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT'); + + return $queries; + } + + /** + * @param Migration[] $queries + * @return Migration[] + */ + private function getSiteSettingsMigrations($queries) + { + $queries[] = $this->migration->db->addColumn($this->siteSettingsTable, 'idsite_setting', 'BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT'); + + return $queries; + } + + /** + * @param Migration[] $queries + * @return Migration[] + */ + private function getLogProfilingMigrations($queries) + { + $queries[] = $this->migration->db->addColumn($this->logProfilingTable, 'idprofiling', 'BIGINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT'); + + return $queries; + } +} diff --git a/core/Updates/3.6.0-b3.php b/core/Updates/3.6.0-b3.php new file mode 100644 index 0000000000000000000000000000000000000000..2477452d27664de526fb37f07938e335d726abf4 --- /dev/null +++ b/core/Updates/3.6.0-b3.php @@ -0,0 +1,50 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $columns = array( + 'idreport' => 'INT(11) NOT NULL', + 'token' => ' VARCHAR(100) NULL', + 'email' => 'VARCHAR(100) NOT NULL', + 'ts_subscribed' => 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP', + 'ts_unsubscribed' => 'TIMESTAMP NULL', + ); + return array( + $this->migration->db->createTable('report_subscriptions', $columns, ['idreport', 'email']), + $this->migration->db->addUniqueKey('report_subscriptions', 'token', 'unique_token'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/3.6.0-b4.php b/core/Updates/3.6.0-b4.php new file mode 100644 index 0000000000000000000000000000000000000000..d39fc1a6bdecf84755d5079fa8d0115d6b4c8e78 --- /dev/null +++ b/core/Updates/3.6.0-b4.php @@ -0,0 +1,52 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->changeColumn('user', 'ts_password_modified', 'ts_password_modified', 'TIMESTAMP NULL'), + $this->migration->db->sql('UPDATE `' . Common::prefixTable('user') . '` SET ts_password_modified = NULL'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + + // the MySQL client experiences an odd race condition with this update. after running the migration script, when + // UsersManager\Model::getUser is called, the fetch segfaults and simply exits. resetting the DB connection + // after the update appears to circumvent this issue. + Db::get()->closeConnection(); + Db::setDatabaseObject(null); + Db::get(); + } +} diff --git a/core/Updates/3.6.1-b2.php b/core/Updates/3.6.1-b2.php new file mode 100644 index 0000000000000000000000000000000000000000..9a8fdf3479e8b8c5432daf6e05b9d5c8ed952da1 --- /dev/null +++ b/core/Updates/3.6.1-b2.php @@ -0,0 +1,43 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return array( + $this->migration->db->addColumn('site', 'creator_login', ' VARCHAR(100) NULL'), + $this->migration->plugin->activate('IntranetMeasurable'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/3.6.1-b3.php b/core/Updates/3.6.1-b3.php new file mode 100644 index 0000000000000000000000000000000000000000..da3180dc3b54c0af4ad553d0adc8b504950d98ea --- /dev/null +++ b/core/Updates/3.6.1-b3.php @@ -0,0 +1,42 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return [ + $this->migration->db->addColumn('goal', 'event_value_as_revenue', "tinyint(4) NOT NULL default '0'"), + ]; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/3.7.0-b1.php b/core/Updates/3.7.0-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..a84ca892c189db4e7148911f657391fa96f5d6c3 --- /dev/null +++ b/core/Updates/3.7.0-b1.php @@ -0,0 +1,40 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + return [ + $this->migration->db->addColumn('report', 'evolution_graph_within_period', 'TINYINT(4) NOT NULL DEFAULT 0'), + $this->migration->db->addColumn('report', 'evolution_graph_period_n', 'INT(11) NULL'), + ]; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/3.8.0-b3.php b/core/Updates/3.8.0-b3.php new file mode 100644 index 0000000000000000000000000000000000000000..0a2a1c19710743039cd6095475fbe627b28eac7b --- /dev/null +++ b/core/Updates/3.8.0-b3.php @@ -0,0 +1,62 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $userColumn = $this->migration->db->addColumn('user', 'twofactor_secret', "VARCHAR(40) NOT NULL DEFAULT ''"); + $backupCode = $this->migration->db->createTable('twofactor_recovery_code', array( + 'idrecoverycode' => 'BIGINT UNSIGNED NOT NULL AUTO_INCREMENT', + 'login' => 'VARCHAR(100) NOT NULL', + 'recovery_code' => 'VARCHAR(40) NOT NULL', + ), array('idrecoverycode')); + $twoFactorAuth = $this->migration->plugin->activate('TwoFactorAuth'); + $googleAuth = $this->migration->plugin->deactivate('GoogleAuthenticator'); + + return array($userColumn, $backupCode, $twoFactorAuth, $googleAuth); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + + if (Plugin\Manager::getInstance()->isPluginActivated('GoogleAuthenticator')) { + foreach (Option::getLike('GoogleAuthentication.%') as $name => $value) { + $value = @Common::safe_unserialize($value); + if (!empty($value['isActive']) && !empty($value['secret'])) { + $login = str_replace('GoogleAuthentication.', '', $name); + + $table = Common::prefixTable('user'); + Db::query("UPDATE $table SET twofactor_secret = ? where login = ?", array($value['secret'], $login)); + } + } + } + } +} diff --git a/core/Updates/3.8.0-b4.php b/core/Updates/3.8.0-b4.php new file mode 100644 index 0000000000000000000000000000000000000000..c209cb80b1edfaa5e1e05b5c9b54b9deeb8e6075 --- /dev/null +++ b/core/Updates/3.8.0-b4.php @@ -0,0 +1,55 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $trackingFailureTable = $this->migration->db->createTable( + 'tracking_failure', + array('idsite' => 'BIGINT(20) UNSIGNED NOT NULL', + 'idfailure' => 'SMALLINT UNSIGNED NOT NULL', + 'date_first_occurred' => 'DATETIME NOT NULL', + 'request_url' => 'MEDIUMTEXT NOT NULL'), + array('idsite', 'idfailure') + ); + + $columns = array( + 'id_brute_force_log' => 'bigint(11) NOT NULL AUTO_INCREMENT', + 'ip_address' => 'VARCHAR(60) DEFAULT NULL', + 'attempted_at' => 'datetime NOT NULL', + ); + return array( + $trackingFailureTable, + $this->migration->db->createTable('brute_force_log', $columns, 'id_brute_force_log'), + $this->migration->db->addIndex('brute_force_log', 'ip_address', 'index_ip_address'), + ); + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/4.0.0-b1.php b/core/Updates/4.0.0-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..05457a2bf0606466059f9a6ae098fc0de06740f5 --- /dev/null +++ b/core/Updates/4.0.0-b1.php @@ -0,0 +1,315 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $tableMetadata = new TableMetadata(); + + $columnsToAdd = []; + + $migrations = []; + + $domain = Config::getLocalConfigPath() === Config::getDefaultLocalConfigPath() ? '' : Config::getHostname(); + $domainArg = !empty($domain) ? "--matomo-domain=" . escapeshellarg($domain) . " " : ''; + $toString = sprintf('./console %score:matomo4-migrate-token-auths', $domainArg); + $custom = new CustomMigration(array(MigrateTokenAuths::class, 'migrate'), $toString); + + $migrations[] = $custom; + + // invalidations table + $migrations[] = $this->migration->db->createTable('archive_invalidations', [ + 'idinvalidation' => 'BIGINT UNSIGNED NOT NULL AUTO_INCREMENT', + 'idarchive' => 'INTEGER UNSIGNED NULL', + 'name' => 'VARCHAR(255) NOT NULL', + 'idsite' => 'INTEGER NOT NULL', + 'date1' => 'DATE NOT NULL', + 'date2' => 'DATE NOT NULL', + 'period' => 'TINYINT UNSIGNED NOT NULL', + 'ts_invalidated' => 'DATETIME NOT NULL', + 'status' => 'TINYINT(1) UNSIGNED DEFAULT 0', + 'report' => 'VARCHAR(255) NULL', + ], ['idinvalidation']); + + $migrations[] = $this->migration->db->addIndex('archive_invalidations', ['idsite', 'date1', 'period'], 'index_idsite_dates_period_name'); + + $migrations[] = $this->migration->db->dropColumn('user', 'alias'); + + // prevent possible duplicates when shorting session id + $migrations[] = $this->migration->db->sql('DELETE FROM `' . Common::prefixTable('session') . '` WHERE length(id) > 190'); + + $migrations[] = $this->migration->db->changeColumnType('session', 'id', 'VARCHAR(191)'); + $migrations[] = $this->migration->db->changeColumnType('site_url', 'url', 'VARCHAR(190)'); + $migrations[] = $this->migration->db->changeColumnType('option', 'option_name', 'VARCHAR(191)'); + + $migrations[] = $this->migration->db->changeColumnType('log_action', 'name', 'VARCHAR(4096)'); + $migrations[] = $this->migration->db->changeColumnType('log_conversion', 'url', 'VARCHAR(4096)'); + $migrations[] = $this->migration->db->changeColumn('log_link_visit_action', 'interaction_position', 'pageview_position', 'MEDIUMINT UNSIGNED DEFAULT NULL'); + + $customTrackerPluginActive = false; + if (in_array('CustomPiwikJs', Config::getInstance()->Plugins['Plugins'])) { + $customTrackerPluginActive = true; + } + + $migrations[] = $this->migration->plugin->activate('BulkTracking'); + $migrations[] = $this->migration->plugin->deactivate('CustomPiwikJs'); + $migrations[] = $this->migration->plugin->uninstall('CustomPiwikJs'); + + if ($customTrackerPluginActive) { + $migrations[] = $this->migration->plugin->activate('CustomJsTracker'); + } + + // Prepare all installed tables for utf8mb4 conversions. e.g. make some indexed fields smaller so they don't exceed the maximum key length + $allTables = DbHelper::getTablesInstalled(); + + foreach ($allTables as $table) { + if (preg_match('/archive_/', $table) == 1) { + $tableNameUnprefixed = Common::unprefixTable($table); + $migrations[] = $this->migration->db->changeColumnType($tableNameUnprefixed, 'name', 'VARCHAR(190)'); + } + } + + // Move the site search fields of log_visit out of custom variables into their own fields + $columnsToAdd['log_link_visit_action']['search_cat'] = 'VARCHAR(200) NULL'; + $columnsToAdd['log_link_visit_action']['search_count'] = 'INTEGER(10) UNSIGNED NULL'; + + // replace days to ... dimensions w/ seconds dimensions + foreach (['log_visit', 'log_conversion'] as $table) { + $columnsToAdd[$table]['visitor_seconds_since_first'] = VisitorSecondsSinceFirst::COLUMN_TYPE; + $columnsToAdd[$table]['visitor_seconds_since_order'] = VisitorSecondsSinceOrder::COLUMN_TYPE; + } + $columnsToAdd['log_visit']['visitor_seconds_since_last'] = VisitorSecondsSinceLast::COLUMN_TYPE; + $columnsToAdd['log_visit']['profilable'] = Profilable::COLUMN_TYPE; + $columnsToAdd['log_link_visit_action'][TimeDomCompletion::COLUMN_NAME] = TimeDomCompletion::COLUMN_TYPE; + $columnsToAdd['log_link_visit_action'][TimeDomProcessing::COLUMN_NAME] = TimeDomProcessing::COLUMN_TYPE; + $columnsToAdd['log_link_visit_action'][TimeNetwork::COLUMN_NAME] = TimeNetwork::COLUMN_TYPE; + $columnsToAdd['log_link_visit_action'][TimeOnLoad::COLUMN_NAME] = TimeOnLoad::COLUMN_TYPE; + $columnsToAdd['log_link_visit_action'][TimeServer::COLUMN_NAME] = TimeServer::COLUMN_TYPE; + $columnsToAdd['log_link_visit_action'][TimeTransfer::COLUMN_NAME] = TimeTransfer::COLUMN_TYPE; + + $columnsToMaybeAdd = ['revenue', 'revenue_discount', 'revenue_shipping', 'revenue_subtotal', 'revenue_tax']; + $columnsLogConversion = $tableMetadata->getColumns(Common::prefixTable('log_conversion')); + foreach ($columnsToMaybeAdd as $columnToMaybeAdd) { + if (!in_array($columnToMaybeAdd, $columnsLogConversion, true)) { + $columnsToAdd['log_conversion'][$columnToMaybeAdd] = 'DOUBLE NULL DEFAULT NULL'; + } + } + + foreach ($columnsToAdd as $table => $columns) { + $migrations[] = $this->migration->db->addColumns($table, $columns); + + foreach ($columns as $columnName => $columnType) { + $optionKey = 'version_' . $table . '.' . $columnName; + $optionValue = $columnType; + + if ($table == 'log_visit' && isset($columnsToAdd['log_conversion'][$columnName])) { + $optionValue .= '1'; // column is in log_conversion too + } + + $migrations[] = $this->migration->db->sql("INSERT IGNORE INTO `" . Common::prefixTable('option') + . "` (option_name, option_value) VALUES ('$optionKey', '$optionValue')"); + } + } + + if (Manager::getInstance()->isPluginInstalled('CustomVariables')) { + $visitActionTable = Common::prefixTable('log_link_visit_action'); + $migrations[] = $this->migration->db->sql("UPDATE $visitActionTable SET search_cat = if(custom_var_k4 = '_pk_scat', custom_var_v4, search_cat), search_count = if(custom_var_k5 = '_pk_scount', custom_var_v5, search_count) WHERE custom_var_k4 = '_pk_scat' or custom_var_k5 = '_pk_scount'"); + } + + if ($this->usesGeoIpLegacyLocationProvider()) { + // activate GeoIp2 plugin for users still using GeoIp2 Legacy (others might have it disabled on purpose) + $migrations[] = $this->migration->plugin->activate('GeoIp2'); + } + + // remove old options + $migrations[] = $this->migration->db->sql('DELETE FROM `' . Common::prefixTable('option') . '` WHERE option_name IN ("geoip.updater_period", "geoip.loc_db_url", "geoip.isp_db_url", "geoip.org_db_url")'); + + // init seconds_to_... columns + $logVisitColumns = $tableMetadata->getColumns(Common::prefixTable('log_visit')); + $hasDaysColumnInVisit = in_array('visitor_days_since_first', $logVisitColumns); + + if ($hasDaysColumnInVisit) { + $migrations[] = $this->migration->db->sql("UPDATE " . Common::prefixTable('log_visit') + . " SET visitor_seconds_since_first = visitor_days_since_first * 86400, + visitor_seconds_since_order = visitor_days_since_order * 86400, + visitor_seconds_since_last = visitor_days_since_last * 86400"); + } + + $logConvColumns = $tableMetadata->getColumns(Common::prefixTable('log_conversion')); + $hasDaysColumnInConv = in_array('visitor_days_since_first', $logConvColumns); + + if ($hasDaysColumnInConv) { + $migrations[] = $this->migration->db->sql("UPDATE " . Common::prefixTable('log_conversion') + . " SET visitor_seconds_since_first = visitor_days_since_first * 86400, + visitor_seconds_since_order = visitor_days_since_order * 86400"); + } + + // remove old days_to_... columns + $migrations[] = $this->migration->db->dropColumns('log_visit', [ + 'config_gears', + 'config_director', + 'visitor_days_since_first', + 'visitor_days_since_order', + 'visitor_days_since_last', + ]); + $migrations[] = $this->migration->db->dropColumns('log_conversion', [ + 'visitor_days_since_first', + 'visitor_days_since_order', + ]); + + $config = Config::getInstance(); + + if (!empty($config->mail['type']) && $config->mail['type'] === 'Crammd5') { + $migrations[] = $this->migration->config->set('mail', 'type', 'Cram-md5'); + } + + // keep piwik_ignore for existing installs + $migrations[] = $this->migration->config->set('Tracker', 'ignore_visits_cookie_name', 'piwik_ignore'); + + $migrations[] = $this->migration->plugin->activate('PagePerformance'); + if (!Manager::getInstance()->isPluginActivated('CustomDimensions')) { + $migrations[] = $this->migration->plugin->activate('CustomDimensions'); + } + + $configTableLimit = Config::getInstance()->getFromLocalConfig('General')['datatable_archiving_maximum_rows_custom_variables'] ?? null; + $configSubTableLimit = Config::getInstance()->getFromLocalConfig('General')['datatable_archiving_maximum_rows_subtable_custom_variables'] ?? null; + + if ($configTableLimit) { + $migrations[] = $this->migration->config->set('General', 'datatable_archiving_maximum_rows_custom_dimensions', $configTableLimit); + } + if ($configSubTableLimit) { + $migrations[] = $this->migration->config->set('General', 'datatable_archiving_maximum_rows_subtable_custom_dimensions', $configSubTableLimit); + } + + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $salt = SettingsPiwik::getSalt(); + $sessions = Db::fetchAll('SELECT id from `' . Common::prefixTable('session') . '`'); + + foreach ($sessions as $session) { + if (!empty($session['id']) && mb_strlen($session['id']) != 128) { + $bind = [ hash('sha512', $session['id'] . $salt), $session['id'] ]; + try { + Db::query(sprintf('UPDATE `%s` SET id = ? WHERE id = ?', Common::prefixTable('session')), $bind); + } catch (\Exception $e) { + // ignore possible duplicate key errors + } + } + } + + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + + if ($this->usesGeoIpLegacyLocationProvider()) { + // switch to default provider if GeoIp Legacy was still in use + LocationProvider::setCurrentProvider(LocationProvider\DefaultProvider::ID); + } + + // eg the case when not updating from most recent Matomo 3.X and when not using the UI updater + // afterwards the should receive a notification that the plugins are outdated + self::ensureCorePluginsThatWereMovedToMarketplaceCanBeUpdated(); + ServerFilesGenerator::createFilesForSecurity(); + } + + public static function ensureCorePluginsThatWereMovedToMarketplaceCanBeUpdated() + { + $plugins = ['Provider', 'CustomVariables']; + $pluginManager = Manager::getInstance(); + foreach ($plugins as $plugin) { + if ($pluginManager->isPluginThirdPartyAndBogus($plugin)) { + $pluginDir = Manager::getPluginDirectory($plugin); + + if ( + is_dir($pluginDir) && + file_exists($pluginDir . '/' . $plugin . '.php') && + !file_exists($pluginDir . '/plugin.json') && + is_writable($pluginDir) + ) { + file_put_contents($pluginDir . '/plugin.json', '{ + "name": "' . $plugin . '", + "description": "' . $plugin . '", + "version": "3.14.1", + "theme": false, + "require": { + "piwik": ">=3.0.0,<4.0.0-b1" + }, + "authors": [ + { + "name": "Matomo", + "email": "hello@matomo.org", + "homepage": "https:\/\/matomo.org" + } + ], + "homepage": "https:\/\/matomo.org", + "license": "GPL v3+", + "keywords": ["' . $plugin . '"] +}'); + // otherwise cached information might be used and it won't be loaded otherwise within same request + $pluginObj = $pluginManager->loadPlugin($plugin); + $pluginObj->reloadPluginInformation(); + $pluginManager->unloadPlugin($pluginObj); // prevent any events being posted to it somehow + } + } + } + } + + protected function usesGeoIpLegacyLocationProvider() + { + $currentProvider = LocationProvider::getCurrentProviderId(); + + return in_array($currentProvider, [ + 'geoip_pecl', + 'geoip_php', + 'geoip_serverbased', + ]); + } +} diff --git a/core/Updates/4.0.0-b3.php b/core/Updates/4.0.0-b3.php new file mode 100644 index 0000000000000000000000000000000000000000..7ec34ad71933205300be192dc1235e745fdd538e --- /dev/null +++ b/core/Updates/4.0.0-b3.php @@ -0,0 +1,58 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migrations = []; + + $config = Config::getInstance(); + $general = $config->General; + if (empty($general['login_whitelist_apply_to_reporting_api_requests'])) { + $migrations[] = $this->migration->config->set('General', 'login_allowlist_apply_to_reporting_api_requests', '0'); + } + + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + + $config = Config::getInstance(); + $general = $config->General; + if (!empty($general['login_whitelist_ip'])) { + // the migration->config->set does not support arrays yet so we do it here. + $general['login_allowlist_ip'] = $general['login_whitelist_ip']; + $config->General = $general; + $config->forceSave(); + } + } +} diff --git a/core/Updates/4.0.0-rc3.php b/core/Updates/4.0.0-rc3.php new file mode 100644 index 0000000000000000000000000000000000000000..6b0da3f51560516584a3d6173bf84baa05163dbc --- /dev/null +++ b/core/Updates/4.0.0-rc3.php @@ -0,0 +1,42 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migrations = []; + $migrations[] = $this->migration->db->addColumn('archive_invalidations', 'ts_started', 'DATETIME NULL'); + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/4.0.0-rc4.php b/core/Updates/4.0.0-rc4.php new file mode 100644 index 0000000000000000000000000000000000000000..7c31678d24e6ca5daecc087a80a199589176286d --- /dev/null +++ b/core/Updates/4.0.0-rc4.php @@ -0,0 +1,73 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migrations = []; + + $migrations[] = $this->migration->plugin->deactivate('ExampleTheme'); + + $channel = StaticContainer::get(ReleaseChannels::class)->getActiveReleaseChannel()->getId(); + $isBeta = stripos($channel, 'beta') !== false; + + if ($isBeta) { + $dates = ['2020-01-01', '2020-11-01', '2020-10-01']; + foreach ($dates as $date) { + $date = Date::factory($date); + $numericTable = ArchiveTableCreator::getBlobTable($date, false); + $blobTable = ArchiveTableCreator::getNumericTable($date, false); + + if ( + $blobTable !== null + && $numericTable !== null + && DbHelper::tableExists($blobTable) + && DbHelper::tableExists($numericTable) + ) { + $migrations[] = $this->migration->db->sql( + "DELETE FROM `$blobTable` WHERE idarchive NOT IN (SELECT idarchive FROM `$numericTable`)", + [] + ); + } + } + } + + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/4.0.1-b1.php b/core/Updates/4.0.1-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..7e6bbe5da907006e2a6add791e73a958ae957ed1 --- /dev/null +++ b/core/Updates/4.0.1-b1.php @@ -0,0 +1,49 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migrations = []; + + $table = Common::prefixTable('user_token_auth'); + $migrations[] = $this->migration->db->sql('UPDATE ' . $table . ' SET hash_algo = "sha512" where hash_algo is null or hash_algo = "" '); + + if (SettingsPiwik::isGitDeployment()) { + return $migrations; + } + + $migrations[] = $this->migration->plugin->uninstall('ExampleTheme'); + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/4.0.4-b1.php b/core/Updates/4.0.4-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..645461bcd29f031f97373ec36d3685b37935158e --- /dev/null +++ b/core/Updates/4.0.4-b1.php @@ -0,0 +1,63 @@ +migration = $factory; + } + + public function getMigrations(Updater $updater) + { + $migrations = []; + + if (SettingsPiwik::isGitDeployment()) { + return $migrations; + } + + $migrations[] = $this->migration->plugin->deactivate('ExamplePlugin'); + $migrations[] = $this->migration->plugin->deactivate('ExampleLogTables'); + $migrations[] = $this->migration->plugin->deactivate('ExampleUI'); + $migrations[] = $this->migration->plugin->deactivate('ExampleReport'); + $migrations[] = $this->migration->plugin->deactivate('ExampleAPI'); + $migrations[] = $this->migration->plugin->deactivate('ExampleCommand'); + $migrations[] = $this->migration->plugin->deactivate('ExampleSettingsPlugin'); + $migrations[] = $this->migration->plugin->deactivate('ExampleTracker'); + $migrations[] = $this->migration->plugin->deactivate('ExampleVisualization'); + + $migrations[] = $this->migration->plugin->uninstall('ExamplePlugin'); + $migrations[] = $this->migration->plugin->uninstall('ExampleLogTables'); + $migrations[] = $this->migration->plugin->uninstall('ExampleUI'); + $migrations[] = $this->migration->plugin->uninstall('ExampleReport'); + $migrations[] = $this->migration->plugin->uninstall('ExampleAPI'); + $migrations[] = $this->migration->plugin->uninstall('ExampleCommand'); + $migrations[] = $this->migration->plugin->uninstall('ExampleSettingsPlugin'); + $migrations[] = $this->migration->plugin->uninstall('ExampleTracker'); + $migrations[] = $this->migration->plugin->uninstall('ExampleVisualization'); + return $migrations; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/4.1.2-b1.php b/core/Updates/4.1.2-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..75b9d25827c4d7c79dc2d29e318c1cd09b2dad92 --- /dev/null +++ b/core/Updates/4.1.2-b1.php @@ -0,0 +1,84 @@ +migration = $factory; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } + + public function getMigrations(Updater $updater) + { + $migrations = []; + + if (!Rules::isBrowserTriggerEnabled()) { + $dateOfMatomo4Release = Date::factory('2020-11-23'); + + $cmdStr = $this->getInvalidateCommand($dateOfMatomo4Release); + + $migrations[] = new Updater\Migration\Custom(function () use ($dateOfMatomo4Release) { + $invalidator = StaticContainer::get(ArchiveInvalidator::class); + $invalidator->scheduleReArchiving('all', 'VisitFrequency', null, $dateOfMatomo4Release); + }, $cmdStr); + } + + $migrations[] = new Updater\Migration\Custom(function () { + $segmentArchiving = StaticContainer::get(CronArchive\SegmentArchiving::class); + $timeOfLastInvalidateTime = CronArchive::getLastInvalidationTime(); + + $segments = API::getInstance()->getAll(); + foreach ($segments as $segment) { + try { + $tsCreated = !empty($segment['ts_created']) ? Date::factory($segment['ts_created'])->getTimestamp() : 0; + $tsLastEdit = !empty($segment['ts_last_edit']) ? Date::factory($segment['ts_last_edit'])->getTimestamp() : null; + $timeToUse = max($tsCreated, $tsLastEdit); + + if ($timeToUse > $timeOfLastInvalidateTime) { + $segmentArchiving->reArchiveSegment($segment); + } + } catch (\Exception $ex) { + // ignore + } + } + }, ''); + + return $migrations; + } + + private function getInvalidateCommand(Date $dateOfMatomo4Release) + { + $command = "php " . PIWIK_INCLUDE_PATH . '/console core:invalidate-report-data --sites=all'; + $command .= ' --dates=' . $dateOfMatomo4Release->toString() . ',' . Date::factory('today')->toString(); + $command .= ' --plugin=VisitFrequency'; + return $command; + } +} diff --git a/core/Updates/4.1.2-b2.php b/core/Updates/4.1.2-b2.php new file mode 100644 index 0000000000000000000000000000000000000000..e15a66f53efd6e946e77d94ad71f268bb98e3928 --- /dev/null +++ b/core/Updates/4.1.2-b2.php @@ -0,0 +1,45 @@ +migration = $factory; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } + + public function getMigrations(Updater $updater) + { + $migrations = []; + + $tables = ArchiveTableCreator::getTablesArchivesInstalled('numeric'); + foreach ($tables as $table) { + $migrations[] = $this->migration->db->sql("UPDATE `$table` SET `name` = 'done' WHERE `name` = 'done.'"); + } + + return $migrations; + } +} diff --git a/core/Updates/4.10.0-b1.php b/core/Updates/4.10.0-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..0c7152d6e354a5dd298933ac2554148eafeefd7d --- /dev/null +++ b/core/Updates/4.10.0-b1.php @@ -0,0 +1,58 @@ +migration = $factory; + } + + /** + * @return Migration[] + */ + public function getMigrations(Updater $updater) + { + $table = Common::prefixTable('report'); + $invalidCount = Db::fetchOne( + "SELECT COUNT(*) FROM `$table` WHERE reports = ? OR parameters = ?", + ['Array', 'Array'] + ); + + if (0 === (int) $invalidCount) { + return []; + } + + return [ + $this->migration->db->sql("DELETE FROM `$table` WHERE reports = 'Array' OR parameters = 'Array'"), + ]; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/4.11.0-b1.php b/core/Updates/4.11.0-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..dd5d0cfa409bf1fed5cc62ef07583ffcca8edd26 --- /dev/null +++ b/core/Updates/4.11.0-b1.php @@ -0,0 +1,49 @@ +migration = $factory; + } + + /** + * @return Migration[] + */ + public function getMigrations(Updater $updater) + { + + return [ + $this->migration->db->addColumns('user', [ + 'invite_status' => "ENUM('accept','pending','decline','expired') DEFAULT 'accept'", + ]), + ]; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +} diff --git a/core/Updates/4.11.0-rc2.php b/core/Updates/4.11.0-rc2.php new file mode 100644 index 0000000000000000000000000000000000000000..233a7a4baa0b0f52686a3665e1fd9c8e2d9a5edd --- /dev/null +++ b/core/Updates/4.11.0-rc2.php @@ -0,0 +1,101 @@ +migration = $factory; + $this->userTable = Common::prefixTable('user'); + } + + /** + * @return Migration[] + */ + public function getMigrations(Updater $updater) + { + try { + $this->pendingUsers = Db::fetchAll( + "SELECT * FROM `$this->userTable` WHERE invite_status = ? ", + ['pending'] + ); + } catch (\Exception $e) { + // ignore any errors. The column might not exist when updating from an older version, + // so there wouldn't be anything to update anyway + } + return [ + $this->migration->db->dropColumn('user', 'invite_status'), + $this->migration->db->addColumns('user', ['invite_token' => 'VARCHAR(191) DEFAULT null']), + $this->migration->db->addColumns('user', ['invited_by' => 'VARCHAR(100) DEFAULT null']), + $this->migration->db->addColumns('user', ['invite_expired_at' => 'TIMESTAMP null DEFAULT null']), + $this->migration->db->addColumns('user', ['invite_accept_at' => 'TIMESTAMP null DEFAULT null']), + ]; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + + $model = new Model(); + if (!empty($this->pendingUsers)) { + foreach ($this->pendingUsers as $user) { + $model->deleteAllTokensForUser($user['login']); + + $site = $model->getSitesAccessFromUser($user['login']); + if (isset($site[0])) { + $site = new Site($site[0]['site']); + $siteName = $site->getName(); + } else { + $siteName = "Default Site"; + } + //generate Token + $generatedToken = $model->generateRandomTokenAuth(); + + //attach token to user + $model->attachInviteToken($user['login'], $generatedToken, 7); + + // send email + $email = StaticContainer::getContainer()->make(UserInviteEmail::class, [ + 'currentUser' => Piwik::getCurrentUserLogin(), + 'invitedUser' => $user, + 'siteName' => $siteName, + 'token' => $generatedToken, + 'expiryInDays' => 7, + ]); + $email->safeSend(); + } + } + } +} diff --git a/core/Updates/4.12.0-b1.php b/core/Updates/4.12.0-b1.php new file mode 100644 index 0000000000000000000000000000000000000000..9c4a2b475b0f47034681c06b2f44de5bd3634f9b --- /dev/null +++ b/core/Updates/4.12.0-b1.php @@ -0,0 +1,46 @@ +migration = $factory; + } + + /** + * @return Migration[] + */ + public function getMigrations(Updater $updater) + { + return [ + $this->migration->db->addColumn('site', 'excluded_referrers', 'TEXT NOT NULL', 'excluded_user_agents'), + ]; + } + + public function doUpdate(Updater $updater) + { + $updater->executeMigrations(__FILE__, $this->getMigrations($updater)); + } +}