PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 5.1.0
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v5.1.0
5.13.0 5.12.1 5.12.0 5.11.1 5.11.0 5.10.2 5.10.1 trunk 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.1.0 1.1.1 1.1.2 1.1.3 1.2.0 1.3.0 1.3.1 1.3.2 4.0.0 4.0.1 4.0.2 4.0.3 4.0.4 4.1.0 4.1.1 4.1.2 4.1.3 4.10.0 4.11.0 4.12.0 4.13.0 4.13.2 4.13.3 4.13.4 4.13.5 4.14.0 4.14.1 4.14.2 4.15.0 4.15.1 4.15.2 4.15.3 4.2.0 4.3.0 4.3.1 4.4.1 4.4.2 4.5.0 4.6.0 5.0.1 5.0.2 5.0.3 5.0.4 5.0.5 5.0.6 5.0.7 5.0.8 5.1.0 5.1.1 5.1.2 5.1.3 5.1.4 5.1.5 5.1.6 5.1.7 5.10.0 5.2.0 5.2.1 5.2.2 5.3.0 5.3.1 5.3.2 5.3.3 5.6.0 5.6.1 5.7.0 5.7.1 5.8.0 5.8.1 5.8.2
matomo / app / core / Db / Schema / Mysql.php
matomo / app / core / Db / Schema Last commit date
Mariadb.php 2 years ago Mysql.php 2 years ago Tidb.php 2 years ago
Mysql.php
317 lines
1 <?php
2
3 /**
4 * Matomo - free/libre analytics platform
5 *
6 * @link https://matomo.org
7 * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8 */
9 namespace Piwik\Db\Schema;
10
11 use Exception;
12 use Piwik\Common;
13 use Piwik\Concurrency\Lock;
14 use Piwik\Date;
15 use Piwik\Db\SchemaInterface;
16 use Piwik\Db;
17 use Piwik\DbHelper;
18 use Piwik\Option;
19 use Piwik\Piwik;
20 use Piwik\Plugin\Manager;
21 use Piwik\Plugins\UsersManager\Model;
22 use Piwik\Version;
23 /**
24 * MySQL schema
25 */
26 class Mysql implements SchemaInterface
27 {
28 public const OPTION_NAME_MATOMO_INSTALL_VERSION = 'install_version';
29 public const MAX_TABLE_NAME_LENGTH = 64;
30 private $tablesInstalled = null;
31 /**
32 * Get the SQL to create Piwik tables
33 *
34 * @return array array of strings containing SQL
35 */
36 public function getTablesCreateSql()
37 {
38 $engine = $this->getTableEngine();
39 $prefixTables = $this->getTablePrefix();
40 $dbSettings = new Db\Settings();
41 $charset = $dbSettings->getUsedCharset();
42 $tables = array('user' => "CREATE TABLE {$prefixTables}user (\n login VARCHAR(100) NOT NULL,\n password VARCHAR(255) NOT NULL,\n email VARCHAR(100) NOT NULL,\n twofactor_secret VARCHAR(40) NOT NULL DEFAULT '',\n superuser_access TINYINT(2) unsigned NOT NULL DEFAULT '0',\n date_registered TIMESTAMP NULL,\n ts_password_modified TIMESTAMP NULL,\n idchange_last_viewed INTEGER UNSIGNED NULL,\n invited_by VARCHAR(100) NULL,\n invite_token VARCHAR(191) NULL,\n invite_link_token VARCHAR(191) NULL,\n invite_expired_at TIMESTAMP NULL,\n invite_accept_at TIMESTAMP NULL,\n ts_changes_shown TIMESTAMP NULL,\n PRIMARY KEY(login),\n UNIQUE INDEX `uniq_email` (`email`)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'user_token_auth' => "CREATE TABLE {$prefixTables}user_token_auth (\n idusertokenauth BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,\n login VARCHAR(100) NOT NULL,\n description VARCHAR(" . Model::MAX_LENGTH_TOKEN_DESCRIPTION . ") NOT NULL,\n password VARCHAR(191) NOT NULL,\n hash_algo VARCHAR(30) NOT NULL,\n system_token TINYINT(1) NOT NULL DEFAULT 0,\n last_used DATETIME NULL,\n date_created DATETIME NOT NULL,\n date_expired DATETIME NULL,\n secure_only TINYINT(2) unsigned NOT NULL DEFAULT '0',\n PRIMARY KEY(idusertokenauth),\n UNIQUE KEY uniq_password(password)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'twofactor_recovery_code' => "CREATE TABLE {$prefixTables}twofactor_recovery_code (\n idrecoverycode BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,\n login VARCHAR(100) NOT NULL,\n recovery_code VARCHAR(40) NOT NULL,\n PRIMARY KEY(idrecoverycode)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'access' => "CREATE TABLE {$prefixTables}access (\n idaccess INTEGER(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n login VARCHAR(100) NOT NULL,\n idsite INTEGER UNSIGNED NOT NULL,\n access VARCHAR(50) NULL,\n PRIMARY KEY(idaccess),\n INDEX index_loginidsite (login, idsite)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'site' => "CREATE TABLE {$prefixTables}site (\n idsite INTEGER(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n name VARCHAR(90) NOT NULL,\n main_url VARCHAR(255) NOT NULL,\n ts_created TIMESTAMP NULL,\n ecommerce TINYINT DEFAULT 0,\n sitesearch TINYINT DEFAULT 1,\n sitesearch_keyword_parameters TEXT NOT NULL,\n sitesearch_category_parameters TEXT NOT NULL,\n timezone VARCHAR( 50 ) NOT NULL,\n currency CHAR( 3 ) NOT NULL,\n exclude_unknown_urls TINYINT(1) DEFAULT 0,\n excluded_ips TEXT NOT NULL,\n excluded_parameters TEXT NOT NULL,\n excluded_user_agents TEXT NOT NULL,\n excluded_referrers TEXT NOT NULL,\n `group` VARCHAR(250) NOT NULL,\n `type` VARCHAR(255) NOT NULL,\n keep_url_fragment TINYINT NOT NULL DEFAULT 0,\n creator_login VARCHAR(100) NULL,\n PRIMARY KEY(idsite)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'plugin_setting' => "CREATE TABLE {$prefixTables}plugin_setting (\n `plugin_name` VARCHAR(60) NOT NULL,\n `setting_name` VARCHAR(255) NOT NULL,\n `setting_value` LONGTEXT NOT NULL,\n `json_encoded` TINYINT UNSIGNED NOT NULL DEFAULT 0,\n `user_login` VARCHAR(100) NOT NULL DEFAULT '',\n `idplugin_setting` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,\n PRIMARY KEY (idplugin_setting),\n INDEX(plugin_name, user_login)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'site_setting' => "CREATE TABLE {$prefixTables}site_setting (\n idsite INTEGER(10) UNSIGNED NOT NULL,\n `plugin_name` VARCHAR(60) NOT NULL,\n `setting_name` VARCHAR(255) NOT NULL,\n `setting_value` LONGTEXT NOT NULL,\n `json_encoded` TINYINT UNSIGNED NOT NULL DEFAULT 0,\n `idsite_setting` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,\n PRIMARY KEY (idsite_setting),\n INDEX(idsite, plugin_name)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'site_url' => "CREATE TABLE {$prefixTables}site_url (\n idsite INTEGER(10) UNSIGNED NOT NULL,\n url VARCHAR(190) NOT NULL,\n PRIMARY KEY(idsite, url)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'goal' => "CREATE TABLE `{$prefixTables}goal` (\n `idsite` int(11) NOT NULL,\n `idgoal` int(11) NOT NULL,\n `name` varchar(50) NOT NULL,\n `description` varchar(255) NOT NULL DEFAULT '',\n `match_attribute` varchar(20) NOT NULL,\n `pattern` varchar(255) NOT NULL,\n `pattern_type` varchar(25) NOT NULL,\n `case_sensitive` tinyint(4) NOT NULL,\n `allow_multiple` tinyint(4) NOT NULL,\n `revenue` DOUBLE NOT NULL,\n `deleted` tinyint(4) NOT NULL default '0',\n `event_value_as_revenue` tinyint(4) NOT NULL default '0',\n PRIMARY KEY (`idsite`,`idgoal`)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'logger_message' => "CREATE TABLE {$prefixTables}logger_message (\n idlogger_message INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,\n tag VARCHAR(50) NULL,\n timestamp TIMESTAMP NULL,\n level VARCHAR(16) NULL,\n message TEXT NULL,\n PRIMARY KEY(idlogger_message)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'log_action' => "CREATE TABLE {$prefixTables}log_action (\n idaction INTEGER(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n name VARCHAR(4096),\n hash INTEGER(10) UNSIGNED NOT NULL,\n type TINYINT UNSIGNED NULL,\n url_prefix TINYINT(2) NULL,\n PRIMARY KEY(idaction),\n INDEX index_type_hash (type, hash)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'log_visit' => "CREATE TABLE {$prefixTables}log_visit (\n idvisit BIGINT(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n idsite INTEGER(10) UNSIGNED NOT NULL,\n idvisitor BINARY(8) NOT NULL,\n visit_last_action_time DATETIME NOT NULL,\n config_id BINARY(8) NOT NULL,\n location_ip VARBINARY(16) NOT NULL,\n PRIMARY KEY(idvisit),\n INDEX index_idsite_config_datetime (idsite, config_id, visit_last_action_time),\n INDEX index_idsite_datetime (idsite, visit_last_action_time),\n INDEX index_idsite_idvisitor_time (idsite, idvisitor, visit_last_action_time DESC)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'log_conversion_item' => "CREATE TABLE `{$prefixTables}log_conversion_item` (\n idsite int(10) UNSIGNED NOT NULL,\n idvisitor BINARY(8) NOT NULL,\n server_time DATETIME NOT NULL,\n idvisit BIGINT(10) UNSIGNED NOT NULL,\n idorder varchar(100) NOT NULL,\n idaction_sku INTEGER(10) UNSIGNED NOT NULL,\n idaction_name INTEGER(10) UNSIGNED NOT NULL,\n idaction_category INTEGER(10) UNSIGNED NOT NULL,\n idaction_category2 INTEGER(10) UNSIGNED NOT NULL,\n idaction_category3 INTEGER(10) UNSIGNED NOT NULL,\n idaction_category4 INTEGER(10) UNSIGNED NOT NULL,\n idaction_category5 INTEGER(10) UNSIGNED NOT NULL,\n price DOUBLE NOT NULL,\n quantity INTEGER(10) UNSIGNED NOT NULL,\n deleted TINYINT(1) UNSIGNED NOT NULL,\n PRIMARY KEY(idvisit, idorder, idaction_sku),\n INDEX index_idsite_servertime ( idsite, server_time )\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'log_conversion' => "CREATE TABLE `{$prefixTables}log_conversion` (\n idvisit BIGINT(10) unsigned NOT NULL,\n idsite int(10) unsigned NOT NULL,\n idvisitor BINARY(8) NOT NULL,\n server_time datetime NOT NULL,\n idaction_url INTEGER(10) UNSIGNED default NULL,\n idlink_va BIGINT(10) UNSIGNED default NULL,\n idgoal int(10) NOT NULL,\n buster int unsigned NOT NULL,\n idorder varchar(100) default NULL,\n items SMALLINT UNSIGNED DEFAULT NULL,\n url VARCHAR(4096) NOT NULL,\n revenue DOUBLE default NULL,\n revenue_shipping DOUBLE default NULL,\n revenue_subtotal DOUBLE default NULL,\n revenue_tax DOUBLE default NULL,\n revenue_discount DOUBLE default NULL,\n pageviews_before SMALLINT UNSIGNED DEFAULT NULL,\n PRIMARY KEY (idvisit, idgoal, buster),\n UNIQUE KEY unique_idsite_idorder (idsite, idorder),\n INDEX index_idsite_datetime ( idsite, server_time )\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'log_link_visit_action' => "CREATE TABLE {$prefixTables}log_link_visit_action (\n idlink_va BIGINT(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n idsite int(10) UNSIGNED NOT NULL,\n idvisitor BINARY(8) NOT NULL,\n idvisit BIGINT(10) UNSIGNED NOT NULL,\n idaction_url_ref INTEGER(10) UNSIGNED NULL DEFAULT 0,\n idaction_name_ref INTEGER(10) UNSIGNED NULL,\n custom_float DOUBLE NULL DEFAULT NULL,\n pageview_position MEDIUMINT UNSIGNED DEFAULT NULL,\n PRIMARY KEY(idlink_va),\n INDEX index_idvisit(idvisit)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'log_profiling' => "CREATE TABLE {$prefixTables}log_profiling (\n query TEXT NOT NULL,\n count INTEGER UNSIGNED NULL,\n sum_time_ms FLOAT NULL,\n idprofiling BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,\n PRIMARY KEY (idprofiling),\n UNIQUE KEY query(query(100))\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'option' => "CREATE TABLE `{$prefixTables}option` (\n option_name VARCHAR( 191 ) NOT NULL,\n option_value LONGTEXT NOT NULL,\n autoload TINYINT NOT NULL DEFAULT '1',\n PRIMARY KEY ( option_name ),\n INDEX autoload( autoload )\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'session' => "CREATE TABLE {$prefixTables}session (\n id VARCHAR( 191 ) NOT NULL,\n modified INTEGER,\n lifetime INTEGER,\n data MEDIUMTEXT,\n PRIMARY KEY ( id )\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'archive_numeric' => "CREATE TABLE {$prefixTables}archive_numeric (\n idarchive INTEGER UNSIGNED NOT NULL,\n name VARCHAR(190) NOT NULL,\n idsite INTEGER UNSIGNED NULL,\n date1 DATE NULL,\n date2 DATE NULL,\n period TINYINT UNSIGNED NULL,\n ts_archived DATETIME NULL,\n value DOUBLE NULL,\n PRIMARY KEY(idarchive, name),\n INDEX index_idsite_dates_period(idsite, date1, date2, period, name(6)),\n INDEX index_period_archived(period, ts_archived)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'archive_blob' => "CREATE TABLE {$prefixTables}archive_blob (\n idarchive INTEGER UNSIGNED NOT NULL,\n name VARCHAR(190) NOT NULL,\n idsite INTEGER UNSIGNED NULL,\n date1 DATE NULL,\n date2 DATE NULL,\n period TINYINT UNSIGNED NULL,\n ts_archived DATETIME NULL,\n value MEDIUMBLOB NULL,\n PRIMARY KEY(idarchive, name),\n INDEX index_period_archived(period, ts_archived)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'archive_invalidations' => "CREATE TABLE `{$prefixTables}archive_invalidations` (\n idinvalidation BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,\n idarchive INTEGER UNSIGNED NULL,\n name VARCHAR(255) NOT NULL,\n idsite INTEGER UNSIGNED NOT NULL,\n date1 DATE NOT NULL,\n date2 DATE NOT NULL,\n period TINYINT UNSIGNED NOT NULL,\n ts_invalidated DATETIME NULL,\n ts_started DATETIME NULL,\n status TINYINT(1) UNSIGNED DEFAULT 0,\n `report` VARCHAR(255) NULL,\n PRIMARY KEY(idinvalidation),\n INDEX index_idsite_dates_period_name(idsite, date1, period)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'sequence' => "CREATE TABLE {$prefixTables}sequence (\n `name` VARCHAR(120) NOT NULL,\n `value` BIGINT(20) UNSIGNED NOT NULL ,\n PRIMARY KEY(`name`)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'brute_force_log' => "CREATE TABLE {$prefixTables}brute_force_log (\n `id_brute_force_log` bigint(11) NOT NULL AUTO_INCREMENT,\n `ip_address` VARCHAR(60) DEFAULT NULL,\n `attempted_at` datetime NOT NULL,\n `login` VARCHAR(100) NULL,\n INDEX index_ip_address(ip_address),\n PRIMARY KEY(`id_brute_force_log`)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'tracking_failure' => "CREATE TABLE {$prefixTables}tracking_failure (\n `idsite` BIGINT(20) UNSIGNED NOT NULL ,\n `idfailure` SMALLINT UNSIGNED NOT NULL ,\n `date_first_occurred` DATETIME NOT NULL ,\n `request_url` MEDIUMTEXT NOT NULL ,\n PRIMARY KEY(`idsite`, `idfailure`)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'locks' => "CREATE TABLE `{$prefixTables}locks` (\n `key` VARCHAR(" . Lock::MAX_KEY_LEN . ") NOT NULL,\n `value` VARCHAR(255) NULL DEFAULT NULL,\n `expiry_time` BIGINT UNSIGNED DEFAULT 9999999999,\n PRIMARY KEY (`key`)\n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ", 'changes' => "CREATE TABLE `{$prefixTables}changes` (\n `idchange` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,\n `created_time` DATETIME NOT NULL,\n `plugin_name` VARCHAR(60) NOT NULL,\n `version` VARCHAR(20) NOT NULL, \n `title` VARCHAR(255) NOT NULL, \n `description` TEXT NULL,\n `link_name` VARCHAR(255) NULL,\n `link` VARCHAR(255) NULL, \n PRIMARY KEY(`idchange`),\n UNIQUE KEY unique_plugin_version_title (`plugin_name`, `version`, `title`(100)) \n ) ENGINE={$engine} DEFAULT CHARSET={$charset}\n ");
43 return $tables;
44 }
45 /**
46 * Get the SQL to create a specific Piwik table
47 *
48 * @param string $tableName
49 * @throws Exception
50 * @return string SQL
51 */
52 public function getTableCreateSql($tableName)
53 {
54 $tables = DbHelper::getTablesCreateSql();
55 if (!isset($tables[$tableName])) {
56 throw new Exception("The table '{$tableName}' SQL creation code couldn't be found.");
57 }
58 return $tables[$tableName];
59 }
60 /**
61 * Names of all the prefixed tables in piwik
62 * Doesn't use the DB
63 *
64 * @return array Table names
65 */
66 public function getTablesNames()
67 {
68 $aTables = array_keys($this->getTablesCreateSql());
69 $prefixTables = $this->getTablePrefix();
70 $return = array();
71 foreach ($aTables as $table) {
72 $return[] = $prefixTables . $table;
73 }
74 return $return;
75 }
76 /**
77 * Get list of installed columns in a table
78 *
79 * @param string $tableName The name of a table.
80 *
81 * @return array Installed columns indexed by the column name.
82 */
83 public function getTableColumns($tableName)
84 {
85 $db = $this->getDb();
86 $allColumns = $db->fetchAll("SHOW COLUMNS FROM " . $tableName);
87 $fields = array();
88 foreach ($allColumns as $column) {
89 $fields[trim($column['Field'])] = $column;
90 }
91 return $fields;
92 }
93 /**
94 * Get list of tables installed (including tables defined by deactivated plugins)
95 *
96 * @param bool $forceReload Invalidate cache
97 * @return array installed Tables
98 */
99 public function getTablesInstalled($forceReload = true)
100 {
101 if (is_null($this->tablesInstalled) || $forceReload === true) {
102 $db = $this->getDb();
103 $prefixTables = $this->getTablePrefixEscaped();
104 $allTables = $this->getAllExistingTables($prefixTables);
105 // all the tables to be installed
106 $allMyTables = $this->getTablesNames();
107 /**
108 * Triggered when detecting which tables have already been created by Matomo.
109 * This should be used by plugins to define it's database tables. Table names need to be added prefixed.
110 *
111 * **Example**
112 *
113 * Piwik::addAction('Db.getTablesInstalled', function(&$allTablesInstalled) {
114 * $allTablesInstalled = 'log_custom';
115 * });
116 * @param array $result
117 */
118 if (count($allTables) && empty($GLOBALS['DISABLE_GET_TABLES_INSTALLED_EVENTS_FOR_TEST'])) {
119 Manager::getInstance()->loadPlugins(Manager::getAllPluginsNames());
120 Piwik::postEvent('Db.getTablesInstalled', [&$allMyTables]);
121 Manager::getInstance()->unloadPlugins();
122 Manager::getInstance()->loadActivatedPlugins();
123 }
124 // we get the intersection between all the tables in the DB and the tables to be installed
125 $tablesInstalled = array_intersect($allMyTables, $allTables);
126 // at this point we have the static list of core tables, but let's add the monthly archive tables
127 $allArchiveNumeric = $db->fetchCol("SHOW TABLES LIKE '" . $prefixTables . "archive_numeric%'");
128 $allArchiveBlob = $db->fetchCol("SHOW TABLES LIKE '" . $prefixTables . "archive_blob%'");
129 $allTablesReallyInstalled = array_merge($tablesInstalled, $allArchiveNumeric, $allArchiveBlob);
130 $allTablesReallyInstalled = array_unique($allTablesReallyInstalled);
131 $this->tablesInstalled = $allTablesReallyInstalled;
132 }
133 return $this->tablesInstalled;
134 }
135 /**
136 * Checks whether any table exists
137 *
138 * @return bool True if tables exist; false otherwise
139 */
140 public function hasTables()
141 {
142 return count($this->getTablesInstalled()) != 0;
143 }
144 /**
145 * Create database
146 *
147 * @param string $dbName Name of the database to create
148 */
149 public function createDatabase($dbName = null)
150 {
151 if (is_null($dbName)) {
152 $dbName = $this->getDbName();
153 }
154 $dbName = str_replace('`', '', $dbName);
155 $charset = DbHelper::getDefaultCharset();
156 Db::exec("CREATE DATABASE IF NOT EXISTS `" . $dbName . "` DEFAULT CHARACTER SET " . $charset);
157 }
158 /**
159 * Creates a new table in the database.
160 *
161 * @param string $nameWithoutPrefix The name of the table without any piwik prefix.
162 * @param string $createDefinition The table create definition, see the "MySQL CREATE TABLE" specification for
163 * more information.
164 * @throws \Exception
165 */
166 public function createTable($nameWithoutPrefix, $createDefinition)
167 {
168 $dbSettings = new Db\Settings();
169 $charset = $dbSettings->getUsedCharset();
170 $statement = sprintf("CREATE TABLE IF NOT EXISTS `%s` ( %s ) ENGINE=%s DEFAULT CHARSET=%s %s;", Common::prefixTable($nameWithoutPrefix), $createDefinition, $this->getTableEngine(), $charset, $dbSettings->getRowFormat());
171 try {
172 Db::exec($statement);
173 } catch (Exception $e) {
174 // mysql code error 1050:table already exists
175 // see bug #153 https://github.com/piwik/piwik/issues/153
176 if (!$this->getDb()->isErrNo($e, '1050')) {
177 throw $e;
178 }
179 }
180 }
181 /**
182 * Drop database
183 */
184 public function dropDatabase($dbName = null)
185 {
186 $dbName = $dbName ?: $this->getDbName();
187 $dbName = str_replace('`', '', $dbName);
188 Db::exec("DROP DATABASE IF EXISTS `" . $dbName . "`");
189 }
190 /**
191 * Create all tables
192 */
193 public function createTables()
194 {
195 $db = $this->getDb();
196 $prefixTables = $this->getTablePrefix();
197 $tablesAlreadyInstalled = $this->getAllExistingTables($prefixTables);
198 $tablesToCreate = $this->getTablesCreateSql();
199 unset($tablesToCreate['archive_blob']);
200 unset($tablesToCreate['archive_numeric']);
201 foreach ($tablesToCreate as $tableName => $tableSql) {
202 $tableName = $prefixTables . $tableName;
203 if (!in_array($tableName, $tablesAlreadyInstalled)) {
204 $db->query($tableSql);
205 }
206 }
207 }
208 /**
209 * Creates an entry in the User table for the "anonymous" user.
210 */
211 public function createAnonymousUser()
212 {
213 $now = Date::factory('now')->getDatetime();
214 // The anonymous user is the user that is assigned by default
215 // note that the token_auth value is anonymous, which is assigned by default as well in the Login plugin
216 $db = $this->getDb();
217 $db->query("INSERT IGNORE INTO " . Common::prefixTable("user") . "\n (`login`, `password`, `email`, `twofactor_secret`, `superuser_access`, `date_registered`, `ts_password_modified`,\n `idchange_last_viewed`)\n VALUES ( 'anonymous', '', 'anonymous@example.org', '', 0, '{$now}', '{$now}' , NULL);");
218 $model = new Model();
219 $model->addTokenAuth('anonymous', 'anonymous', 'anonymous default token', $now);
220 }
221 /**
222 * Records the Matomo version a user used when installing this Matomo for the first time
223 */
224 public function recordInstallVersion()
225 {
226 if (!self::getInstallVersion()) {
227 Option::set(self::OPTION_NAME_MATOMO_INSTALL_VERSION, Version::VERSION);
228 }
229 }
230 /**
231 * Returns which Matomo version was used to install this Matomo for the first time.
232 */
233 public function getInstallVersion()
234 {
235 Option::clearCachedOption(self::OPTION_NAME_MATOMO_INSTALL_VERSION);
236 $version = Option::get(self::OPTION_NAME_MATOMO_INSTALL_VERSION);
237 if (!empty($version)) {
238 return $version;
239 }
240 }
241 /**
242 * Truncate all tables
243 */
244 public function truncateAllTables()
245 {
246 $tables = $this->getAllExistingTables();
247 foreach ($tables as $table) {
248 Db::query("TRUNCATE `{$table}`");
249 }
250 }
251 /**
252 * Adds a MAX_EXECUTION_TIME hint into a SELECT query if $limit is bigger than 0
253 *
254 * @param string $sql query to add hint to
255 * @param float $limit time limit in seconds
256 * @return string
257 */
258 public function addMaxExecutionTimeHintToQuery(string $sql, float $limit) : string
259 {
260 if ($limit <= 0) {
261 return $sql;
262 }
263 $sql = trim($sql);
264 $pos = stripos($sql, 'SELECT');
265 $isMaxExecutionTimeoutAlreadyPresent = stripos($sql, 'MAX_EXECUTION_TIME(') !== false;
266 if ($pos !== false && !$isMaxExecutionTimeoutAlreadyPresent) {
267 $timeInMs = $limit * 1000;
268 $timeInMs = (int) $timeInMs;
269 $maxExecutionTimeHint = ' /*+ MAX_EXECUTION_TIME(' . $timeInMs . ') */ ';
270 $sql = substr_replace($sql, 'SELECT ' . $maxExecutionTimeHint, $pos, strlen('SELECT'));
271 }
272 return $sql;
273 }
274 public function supportsComplexColumnUpdates() : bool
275 {
276 return true;
277 }
278 public function getDefaultPort() : int
279 {
280 return 3306;
281 }
282 private function getTablePrefix()
283 {
284 return $this->getDbSettings()->getTablePrefix();
285 }
286 private function getTableEngine()
287 {
288 return $this->getDbSettings()->getEngine();
289 }
290 private function getDb()
291 {
292 return Db::get();
293 }
294 private function getDbSettings()
295 {
296 return new Db\Settings();
297 }
298 private function getDbName()
299 {
300 return $this->getDbSettings()->getDbName();
301 }
302 private function getAllExistingTables($prefixTables = false)
303 {
304 if (empty($prefixTables)) {
305 $prefixTables = $this->getTablePrefixEscaped();
306 }
307 return Db::get()->fetchCol("SHOW TABLES LIKE '" . $prefixTables . "%'");
308 }
309 private function getTablePrefixEscaped()
310 {
311 $prefixTables = $this->getTablePrefix();
312 // '_' matches any character; force it to be literal
313 $prefixTables = str_replace('_', '\\_', $prefixTables);
314 return $prefixTables;
315 }
316 }
317