File: DbHelper.php

package info (click to toggle)
matomo 5.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 95,068 kB
  • sloc: php: 289,425; xml: 127,249; javascript: 112,130; python: 202; sh: 178; makefile: 20; sql: 10
file content (465 lines) | stat: -rw-r--r-- 14,190 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
<?php

/**
 * Matomo - free/libre analytics platform
 *
 * @link    https://matomo.org
 * @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

namespace Piwik;

use Exception;
use Piwik\Db\Schema;
use Piwik\DataAccess\ArchiveTableCreator;

/**
 * Contains database related helper functions.
 */
class DbHelper
{
    /**
     * Get list of tables installed
     *
     * @param bool $forceReload Invalidate cache
     * @return array  Tables installed
     */
    public static function getTablesInstalled($forceReload = true)
    {
        return Schema::getInstance()->getTablesInstalled($forceReload);
    }

    /**
     * Returns `true` if a table in the database, `false` if otherwise.
     *
     * @param string $tableName The name of the table to check for. Must be prefixed.
     *                          Avoid using user input, as the variable will be used in a query unescaped.
     * @return bool
     * @throws \Exception
     */
    public static function tableExists($tableName)
    {
        $tableName = str_replace(['%', '_', "'"], ['\%', '\_', '_'], $tableName);
        return Db::get()->query(sprintf("SHOW TABLES LIKE '%s'", $tableName))->rowCount() > 0;
    }

    /**
     * Get list of installed columns in a table
     *
     * @param  string $tableName The name of a table.
     *
     * @return array  Installed columns indexed by the column name.
     */
    public static function getTableColumns($tableName)
    {
        return Schema::getInstance()->getTableColumns($tableName);
    }

    /**
     * Creates a new table in the database.
     *
     * Example:
     * ```
     * $tableDefinition = "`age` INT(11) NOT NULL AUTO_INCREMENT,
     *                     `name` VARCHAR(255) NOT NULL";
     *
     * DbHelper::createTable('tablename', $tableDefinition);
     * ``
     *
     * @param string $nameWithoutPrefix   The name of the table without any piwik prefix.
     * @param string $createDefinition    The table create definition
     *
     * @api
     */
    public static function createTable($nameWithoutPrefix, $createDefinition)
    {
        Schema::getInstance()->createTable($nameWithoutPrefix, $createDefinition);
    }

    /**
     * Returns true if Piwik is installed
     *
     * @since 0.6.3
     *
     * @return bool  True if installed; false otherwise
     */
    public static function isInstalled()
    {
        try {
            return Schema::getInstance()->hasTables();
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Truncate all tables
     */
    public static function truncateAllTables()
    {
        Schema::getInstance()->truncateAllTables();
    }

    /**
     * Creates an entry in the User table for the "anonymous" user.
     */
    public static function createAnonymousUser()
    {
        Schema::getInstance()->createAnonymousUser();
    }

    /**
     * Records the Matomo version a user used when installing this Matomo for the first time
     */
    public static function recordInstallVersion()
    {
        Schema::getInstance()->recordInstallVersion();
    }

    /**
     * Returns which Matomo version was used to install this Matomo for the first time.
     */
    public static function getInstallVersion(): string
    {
        return Schema::getInstance()->getInstallVersion() ?? '0';
        // need string as usage is usually
        // version_compare(DbHelper::getInstallVersion(),'4.0.0-b1', '<') or similar
        // and PHP 8.1 throws a deprecation warning otherwise
        // @see https://github.com/matomo-org/matomo/pull/17989#issuecomment-921298360
    }

    public static function wasMatomoInstalledBeforeVersion($version)
    {
        $installVersion = self::getInstallVersion();
        if (empty($installVersion)) {
            return true; // we assume yes it was installed
        }
        return true === version_compare($version, $installVersion, '>');
    }

    /**
     * Create all tables
     */
    public static function createTables()
    {
        Schema::getInstance()->createTables();
    }

    /**
     * Drop database, used in tests
     */
    public static function dropDatabase($dbName = null)
    {
        if (defined('PIWIK_TEST_MODE') && PIWIK_TEST_MODE) {
            Schema::getInstance()->dropDatabase($dbName);
        }
    }


    /**
     * Checks the database server version against the required minimum
     * version.
     *
     * @see config/global.ini.php
     * @since 0.4.4
     * @throws Exception if server version is less than the required version
     */
    public static function checkDatabaseVersion()
    {
        Schema::getInstance()->unsetSchema();
        Db::get()->checkServerVersion();
    }

    /**
     * Disconnect from database
     */
    public static function disconnectDatabase()
    {
        Db::get()->closeConnection();
    }

    /**
     * Create database
     *
     * @param string|null $dbName
     */
    public static function createDatabase($dbName = null)
    {
        Schema::getInstance()->createDatabase($dbName);
    }

    /**
     * Returns if the given table has an index with the given name
     *
     * @param string $table
     * @param string $indexName
     *
     * @return bool
     * @throws Exception
     */
    public static function tableHasIndex($table, $indexName)
    {
        $result = Db::get()->fetchOne('SHOW INDEX FROM `' . $table . '` WHERE Key_name = ?', [$indexName]);
        return !empty($result);
    }

    /**
     * Returns the default database charset to use
     *
     * Returns utf8mb4 if supported, with fallback to utf8
     *
     * @throws Tracker\Db\DbException
     */
    public static function getDefaultCharset(): string
    {
        $result = Db::get()->fetchRow("SHOW CHARACTER SET LIKE 'utf8mb4'");

        if (empty($result)) {
            return 'utf8'; // charset not available
        }

        $result = Db::get()->fetchRow("SHOW VARIABLES LIKE 'character_set_database'");

        if (!empty($result) && $result['Value'] === 'utf8mb4') {
            return 'utf8mb4'; // database has utf8mb4 charset, so assume it can be used
        }

        $result = Db::get()->fetchRow("SHOW VARIABLES LIKE 'innodb_file_per_table'");

        if (empty($result) || $result['Value'] !== 'ON') {
            return 'utf8'; // innodb_file_per_table is required for utf8mb4
        }

        return 'utf8mb4';
    }

    /**
     * Returns the default collation for a charset.
     *
     *
     * @throws Exception
     */
    public static function getDefaultCollationForCharset(string $charset): string
    {
        return Schema::getInstance()->getDefaultCollationForCharset($charset);
    }

    /**
     * Returns sql queries to convert all installed tables to utf8mb4
     *
     * @return array
     */
    public static function getUtf8mb4ConversionQueries()
    {
        $allTables = DbHelper::getTablesInstalled();

        $queries   = [];

        foreach ($allTables as $table) {
            $queries[] = "ALTER TABLE `$table` CONVERT TO CHARACTER SET utf8mb4;";
        }

        return $queries;
    }

    /**
     * Get the SQL to create Piwik tables
     *
     * @return array  array of strings containing SQL
     */
    public static function getTablesCreateSql()
    {
        return Schema::getInstance()->getTablesCreateSql();
    }

    /**
     * Get the SQL to create a specific Piwik table
     *
     * @param string $tableName Unprefixed table name.
     * @return string  SQL
     */
    public static function getTableCreateSql($tableName)
    {
        return Schema::getInstance()->getTableCreateSql($tableName);
    }

    /**
     * Deletes archive tables. For use in tests.
     */
    public static function deleteArchiveTables()
    {
        foreach (ArchiveTableCreator::getTablesArchivesInstalled() as $table) {
            Log::debug("Dropping table $table");

            Db::query("DROP TABLE IF EXISTS `$table`");
        }

        ArchiveTableCreator::refreshTableList();
    }

    /**
     * Adds a MAX_EXECUTION_TIME hint into a SELECT query if $limit is bigger than 0
     *
     * @param string $sql  query to add hint to
     * @param float $limit  time limit in seconds
     */
    public static function addMaxExecutionTimeHintToQuery(string $sql, float $limit): string
    {
        return Schema::getInstance()->addMaxExecutionTimeHintToQuery($sql, $limit);
    }

    /**
     * Add an origin hint to the query to identify the main parameters and segment for debugging
     *
     * @param string        $sql        SQL query string
     * @param string        $origin     Origin string to describe the source of the query
     * @param Date|null     $dateStart  Start date used in the query, optional
     * @param Date|null     $dateEnd    End date used in the query, optional
     * @param array|null    $sites      Sites list used in the query, optional
     * @param Segment|null  $segment    Segment, the segment hash will be added if this is set
     *
     * @return string   Modified SQL query string with hint added
     */
    public static function addOriginHintToQuery(
        string $sql,
        string $origin,
        ?Date $dateStart = null,
        ?Date $dateEnd = null,
        ?array $sites = null,
        ?Segment $segment = null
    ): string {
        $select = 'SELECT';
        if ($origin && 0 === strpos(trim($sql), $select)) {
            $sql = trim($sql);
            $sql = 'SELECT /* ' . $origin . ' */' . substr($sql, strlen($select));
        }

        if ($dateStart !== null && $dateEnd !== null && 0 === strpos(trim($sql), $select)) {
            $sql = trim($sql);
            $sql = 'SELECT /* ' . $dateStart->toString() . ',' . $dateEnd->toString() . ' */' . substr($sql, strlen($select));
        }

        if ($sites && is_array($sites) && 0 === strpos(trim($sql), $select)) {
            $sql = trim($sql);
            $sql = 'SELECT /* ' . 'sites ' . implode(',', array_map('intval', $sites)) . ' */' . substr($sql, strlen($select));
        }

        if ($segment && !$segment->isEmpty() && 0 === strpos(trim($sql), $select)) {
            $sql = trim($sql);
            $sql = 'SELECT /* ' . 'segmenthash ' . $segment->getHash() . ' */' . substr($sql, strlen($select));
        }

        return $sql;
    }

    /**
     * Add an optimizer hint to the query to set the first table used by the MySQL join execution plan
     *
     * https://dev.mysql.com/doc/refman/8.0/en/optimizer-hints.html#optimizer-hints-join-order
     *
     * @param string $sql       SQL query string
     * @param string $prefix    Table prefix to be used as the first table in the plan
     *
     * @return string           Modified query string with hint added
     */
    public static function addJoinPrefixHintToQuery(string $sql, string $prefix): string
    {
        return self::addOptimizerHintToQuery($sql, 'JOIN_PREFIX(' . $prefix . ')');
    }

    /**
     * Add an optimizer hint to the query.
     *
     * Creating and using a "add_x_HintToQuery" functions is preferred
     * over using this function directly, as some optimizer hints depend
     * on the database used.
     *
     * If an optimizer hint is already present (check is done by name only)
     * in the query the new value will be silently discarded.
     *
     * @param string $sql   SQL query string
     * @param string $hint  Hint to add
     *
     * @return string       Modified query string with hint added
     */
    public static function addOptimizerHintToQuery(string $sql, string $hint): string
    {
        $sql = trim($sql);

        // only apply hints to SELECT queries
        if (0 !== stripos($sql, 'SELECT')) {
            return $sql;
        }

        $pattern =
            '@^SELECT\s+' .
            // ignore non-hint comments ("/* ... */")
            '(?:|/\*[^+]*?\*/\s*)' .
            // capture hint comments ("/*+ ... */")
            '(/\*\+\s*(.*?)\s*\*/)' .
            '@is';

        preg_match($pattern, $sql, $matches);

        if (empty($matches)) {
            return 'SELECT /*+ ' . $hint . ' */' . substr($sql, strlen('SELECT'));
        }

        $originalComment = $matches[1];
        $hints = $matches[2];

        $newHintNameEnd = stripos($hint, '(') ?: strlen($hint);
        $newHintName = substr($hint, 0, $newHintNameEnd);

        // only add new hints
        if (preg_match('/(?:^|\s)' . preg_quote($newHintName) . '(?:\\(|\s|$)/i', $hints)) {
            return $sql;
        }

        $hints = trim($hint . ' ' . $hints);

        return substr_replace(
            $sql,
            '/*+ ' . $hints . ' */',
            strpos($sql, $originalComment),
            strlen($originalComment)
        );
    }

    /**
     * Extracts the "ORDER BY" clause from a query.
     *
     * Will return null if no clause found or the extraction failed,
     * e.g. parentheses in the extracted clause are not balanced.
     */
    public static function extractOrderByFromQuery(string $sql): ?string
    {
        $pattern = '/.*ORDER\s+BY\s+(.*?)(?:\s+LIMIT|\s*;|\s*$)/is';

        if (preg_match($pattern, $sql, $matches)) {
            $orderBy = $matches[1];
            $openParentheses = substr_count($orderBy, '(');
            $closeParentheses = substr_count($orderBy, ')');

            if ($openParentheses === $closeParentheses) {
                return trim($orderBy);
            }
        }

        return null;
    }

    /**
     * Returns true if the string is a valid database name for MySQL. MySQL allows + in the database names.
     * Database names that start with a-Z or 0-9 and contain a-Z, 0-9, underscore(_), dash(-), plus(+), and dot(.) will be accepted.
     * File names beginning with anything but a-Z or 0-9 will be rejected (including .htaccess for example).
     * File names containing anything other than above mentioned will also be rejected (file names with spaces won't be accepted).
     *
     * @param string $dbname
     * @return bool
     */
    public static function isValidDbname($dbname)
    {
        return (0 !== preg_match('/(^[a-zA-Z0-9]+([a-zA-Z0-9\_\.\-\+]*))$/D', $dbname));
    }
}