PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 4.0.2
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v4.0.2
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 / DbHelper.php
matomo / app / core Last commit date
API 5 years ago Access 5 years ago Application 5 years ago Archive 5 years ago ArchiveProcessor 5 years ago Archiver 5 years ago AssetManager 5 years ago Auth 5 years ago Category 5 years ago CliMulti 5 years ago Columns 5 years ago Composer 5 years ago Concurrency 5 years ago Config 5 years ago Container 5 years ago CronArchive 5 years ago DataAccess 5 years ago DataFiles 5 years ago DataTable 5 years ago Db 5 years ago DeviceDetector 5 years ago Email 5 years ago Exception 5 years ago Http 5 years ago Intl 5 years ago Mail 5 years ago Measurable 5 years ago Menu 5 years ago Metrics 5 years ago Notification 5 years ago Period 5 years ago Plugin 5 years ago ProfessionalServices 5 years ago Report 5 years ago ReportRenderer 5 years ago Scheduler 5 years ago Segment 5 years ago Session 5 years ago Settings 5 years ago Tracker 5 years ago Translation 5 years ago UpdateCheck 5 years ago Updater 5 years ago Updates 5 years ago Validators 5 years ago View 5 years ago ViewDataTable 5 years ago Visualization 5 years ago Widget 5 years ago .htaccess 6 years ago Access.php 5 years ago Archive.php 5 years ago ArchiveProcessor.php 5 years ago AssetManager.php 5 years ago Auth.php 5 years ago AuthResult.php 5 years ago BaseFactory.php 5 years ago Cache.php 5 years ago CacheId.php 5 years ago CliMulti.php 5 years ago Common.php 5 years ago Config.php 5 years ago Console.php 5 years ago Context.php 5 years ago Cookie.php 5 years ago CronArchive.php 5 years ago DataArray.php 5 years ago DataTable.php 5 years ago Date.php 5 years ago Db.php 5 years ago DbHelper.php 5 years ago Development.php 5 years ago ErrorHandler.php 5 years ago EventDispatcher.php 5 years ago ExceptionHandler.php 5 years ago FileIntegrity.php 5 years ago Filechecks.php 5 years ago Filesystem.php 5 years ago FrontController.php 5 years ago Http.php 5 years ago IP.php 5 years ago Log.php 5 years ago LogDeleter.php 5 years ago Mail.php 5 years ago Metrics.php 5 years ago NoAccessException.php 5 years ago Nonce.php 5 years ago Notification.php 5 years ago NumberFormatter.php 5 years ago Option.php 5 years ago Period.php 5 years ago Piwik.php 5 years ago Plugin.php 5 years ago Profiler.php 5 years ago ProxyHeaders.php 5 years ago ProxyHttp.php 5 years ago QuickForm2.php 5 years ago RankingQuery.php 5 years ago ReportRenderer.php 5 years ago Segment.php 5 years ago Sequence.php 5 years ago Session.php 5 years ago SettingsPiwik.php 5 years ago SettingsServer.php 5 years ago Singleton.php 5 years ago Site.php 5 years ago TCPDF.php 5 years ago Theme.php 5 years ago Timer.php 5 years ago Tracker.php 5 years ago Twig.php 5 years ago Unzip.php 5 years ago UpdateCheck.php 5 years ago Updater.php 5 years ago UpdaterErrorException.php 5 years ago Updates.php 5 years ago Url.php 5 years ago UrlHelper.php 5 years ago Version.php 5 years ago View.php 5 years ago bootstrap.php 5 years ago dispatch.php 5 years ago testMinimumPhpVersion.php 5 years ago
DbHelper.php
335 lines
1 <?php
2 /**
3 * Matomo - free/libre analytics platform
4 *
5 * @link https://matomo.org
6 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
7 *
8 */
9 namespace Piwik;
10
11 use Exception;
12 use Piwik\Db\Schema;
13 use Piwik\DataAccess\ArchiveTableCreator;
14
15 /**
16 * Contains database related helper functions.
17 */
18 class DbHelper
19 {
20 /**
21 * Get list of tables installed
22 *
23 * @param bool $forceReload Invalidate cache
24 * @return array Tables installed
25 */
26 public static function getTablesInstalled($forceReload = true)
27 {
28 return Schema::getInstance()->getTablesInstalled($forceReload);
29 }
30
31 /**
32 * Returns `true` if a table in the database, `false` if otherwise.
33 *
34 * @param string $tableName The name of the table to check for. Must be prefixed.
35 * Avoid using user input, as the variable will be used in a query unescaped.
36 * @return bool
37 * @throws \Exception
38 */
39 public static function tableExists($tableName)
40 {
41 $tableName = str_replace(['%', '_', "'"], ['\%', '\_', '_'], $tableName);
42 return Db::get()->query(sprintf("SHOW TABLES LIKE '%s'", $tableName))->rowCount() > 0;
43 }
44
45 /**
46 * Get list of installed columns in a table
47 *
48 * @param string $tableName The name of a table.
49 *
50 * @return array Installed columns indexed by the column name.
51 */
52 public static function getTableColumns($tableName)
53 {
54 return Schema::getInstance()->getTableColumns($tableName);
55 }
56
57 /**
58 * Creates a new table in the database.
59 *
60 * Example:
61 * ```
62 * $tableDefinition = "`age` INT(11) NOT NULL AUTO_INCREMENT,
63 * `name` VARCHAR(255) NOT NULL";
64 *
65 * DbHelper::createTable('tablename', $tableDefinition);
66 * ``
67 *
68 * @param string $nameWithoutPrefix The name of the table without any piwik prefix.
69 * @param string $createDefinition The table create definition
70 *
71 * @api
72 */
73 public static function createTable($nameWithoutPrefix, $createDefinition)
74 {
75 Schema::getInstance()->createTable($nameWithoutPrefix, $createDefinition);
76 }
77
78 /**
79 * Returns true if Piwik is installed
80 *
81 * @since 0.6.3
82 *
83 * @return bool True if installed; false otherwise
84 */
85 public static function isInstalled()
86 {
87 try {
88 return Schema::getInstance()->hasTables();
89 } catch (Exception $e) {
90 return false;
91 }
92 }
93
94 /**
95 * Truncate all tables
96 */
97 public static function truncateAllTables()
98 {
99 Schema::getInstance()->truncateAllTables();
100 }
101
102 /**
103 * Creates an entry in the User table for the "anonymous" user.
104 */
105 public static function createAnonymousUser()
106 {
107 Schema::getInstance()->createAnonymousUser();
108 }
109
110 /**
111 * Records the Matomo version a user used when installing this Matomo for the first time
112 */
113 public static function recordInstallVersion()
114 {
115 Schema::getInstance()->recordInstallVersion();
116 }
117
118 /**
119 * Returns which Matomo version was used to install this Matomo for the first time.
120 */
121 public static function getInstallVersion()
122 {
123 return Schema::getInstance()->getInstallVersion();
124 }
125
126 public static function wasMatomoInstalledBeforeVersion($version)
127 {
128 $installVersion = self::getInstallVersion();
129 if (empty($installVersion)) {
130 return true; // we assume yes it was installed
131 }
132 return true === version_compare($version, $installVersion, '>');
133 }
134
135 /**
136 * Create all tables
137 */
138 public static function createTables()
139 {
140 Schema::getInstance()->createTables();
141 }
142
143 /**
144 * Drop database, used in tests
145 */
146 public static function dropDatabase($dbName = null)
147 {
148 if (defined('PIWIK_TEST_MODE') && PIWIK_TEST_MODE) {
149 Schema::getInstance()->dropDatabase($dbName);
150 }
151 }
152
153 /**
154 * Check database connection character set is utf8.
155 *
156 * @return bool True if it is (or doesn't matter); false otherwise
157 */
158 public static function isDatabaseConnectionUTF8()
159 {
160 return Db::get()->isConnectionUTF8();
161 }
162
163 /**
164 * Checks the database server version against the required minimum
165 * version.
166 *
167 * @see config/global.ini.php
168 * @since 0.4.4
169 * @throws Exception if server version is less than the required version
170 */
171 public static function checkDatabaseVersion()
172 {
173 Db::get()->checkServerVersion();
174 }
175
176 /**
177 * Disconnect from database
178 */
179 public static function disconnectDatabase()
180 {
181 Db::get()->closeConnection();
182 }
183
184 /**
185 * Create database
186 *
187 * @param string|null $dbName
188 */
189 public static function createDatabase($dbName = null)
190 {
191 Schema::getInstance()->createDatabase($dbName);
192 }
193
194 /**
195 * Returns if the given table has an index with the given name
196 *
197 * @param string $table
198 * @param string $indexName
199 *
200 * @return bool
201 * @throws Exception
202 */
203 public static function tableHasIndex($table, $indexName)
204 {
205 $result = Db::get()->fetchOne('SHOW INDEX FROM '.$table.' WHERE Key_name = ?', [$indexName]);
206 return !empty($result);
207 }
208
209 /**
210 * Returns the default database charset to use
211 *
212 * Returns utf8mb4 if supported, with fallback to utf8
213 *
214 * @return string
215 * @throws Tracker\Db\DbException
216 */
217 public static function getDefaultCharset()
218 {
219 $result = Db::get()->fetchRow("SHOW CHARACTER SET LIKE 'utf8mb4'");
220
221 if (empty($result)) {
222 return 'utf8'; // charset not available
223 }
224
225 $result = Db::get()->fetchRow("SHOW VARIABLES LIKE 'character_set_database'");
226
227 if (!empty($result) && $result['Value'] === 'utf8mb4') {
228 return 'utf8mb4'; // database has utf8mb4 charset, so assume it can be used
229 }
230
231 $result = Db::get()->fetchRow("SHOW VARIABLES LIKE 'innodb_file_per_table'");
232
233 if (empty($result) || $result['Value'] !== 'ON') {
234 return 'utf8'; // innodb_file_per_table is required for utf8mb4
235 }
236
237 return 'utf8mb4';
238 }
239
240 /**
241 * Returns sql queries to convert all installed tables to utf8mb4
242 *
243 * @return array
244 */
245 public static function getUtf8mb4ConversionQueries()
246 {
247 $allTables = DbHelper::getTablesInstalled();
248
249 $queries = [];
250
251 foreach ($allTables as $table) {
252 $queries[] = "ALTER TABLE `$table` CONVERT TO CHARACTER SET utf8mb4;";
253 }
254
255 return $queries;
256 }
257
258 /**
259 * Get the SQL to create Piwik tables
260 *
261 * @return array array of strings containing SQL
262 */
263 public static function getTablesCreateSql()
264 {
265 return Schema::getInstance()->getTablesCreateSql();
266 }
267
268 /**
269 * Get the SQL to create a specific Piwik table
270 *
271 * @param string $tableName Unprefixed table name.
272 * @return string SQL
273 */
274 public static function getTableCreateSql($tableName)
275 {
276 return Schema::getInstance()->getTableCreateSql($tableName);
277 }
278
279 /**
280 * Deletes archive tables. For use in tests.
281 */
282 public static function deleteArchiveTables()
283 {
284 foreach (ArchiveTableCreator::getTablesArchivesInstalled() as $table) {
285 Log::debug("Dropping table $table");
286
287 Db::query("DROP TABLE IF EXISTS `$table`");
288 }
289
290 ArchiveTableCreator::refreshTableList($forceReload = true);
291 }
292
293 /**
294 * Adds a MAX_EXECUTION_TIME hint into a SELECT query if $limit is bigger than 1
295 *
296 * @param string $sql query to add hint to
297 * @param int $limit time limit in seconds
298 * @return string
299 */
300 public static function addMaxExecutionTimeHintToQuery($sql, $limit)
301 {
302 if ($limit <= 0) {
303 return $sql;
304 }
305
306 $sql = trim($sql);
307 $pos = stripos($sql, 'SELECT');
308 if ($pos !== false) {
309
310 $timeInMs = $limit * 1000;
311 $timeInMs = (int) $timeInMs;
312 $maxExecutionTimeHint = ' /*+ MAX_EXECUTION_TIME('.$timeInMs.') */ ';
313
314 $sql = substr_replace($sql, 'SELECT ' . $maxExecutionTimeHint, $pos, strlen('SELECT'));
315 }
316
317 return $sql;
318 }
319
320 /**
321 * Returns true if the string is a valid database name for MySQL. MySQL allows + in the database names.
322 * Database names that start with a-Z or 0-9 and contain a-Z, 0-9, underscore(_), dash(-), plus(+), and dot(.) will be accepted.
323 * File names beginning with anything but a-Z or 0-9 will be rejected (including .htaccess for example).
324 * File names containing anything other than above mentioned will also be rejected (file names with spaces won't be accepted).
325 *
326 * @param string $dbname
327 * @return bool
328 */
329 public static function isValidDbname($dbname)
330 {
331 return (0 !== preg_match('/(^[a-zA-Z0-9]+([a-zA-Z0-9\_\.\-\+]*))$/D', $dbname));
332 }
333
334 }
335