]> git.mxchange.org Git - friendica.git/blob - src/Database/DBStructure.php
Merge pull request #10316 from annando/issue-9926
[friendica.git] / src / Database / DBStructure.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Database;
23
24 use Exception;
25 use Friendica\Core\Hook;
26 use Friendica\Core\Logger;
27 use Friendica\DI;
28 use Friendica\Model\Item;
29 use Friendica\Model\User;
30 use Friendica\Util\DateTimeFormat;
31
32 /**
33  * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
34  */
35 class DBStructure
36 {
37         const UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
38         const UPDATE_SUCCESSFUL  = 1; // Database check was successful
39         const UPDATE_FAILED      = 2; // Database check failed
40
41         const RENAME_COLUMN      = 0;
42         const RENAME_PRIMARY_KEY = 1;
43
44         /**
45          * Database structure definition loaded from config/dbstructure.config.php
46          *
47          * @var array
48          */
49         private static $definition = [];
50
51         /**
52          * Set a database version to trigger update functions
53          *
54          * @param string $version
55          * @return void
56          */
57         public static function setDatabaseVersion(string $version)
58         {
59                 if (!is_numeric($version)) {
60                         throw new \Asika\SimpleConsole\CommandArgsException('The version number must be numeric');
61                 }
62
63                 DI::config()->set('system', 'build', $version);
64                 echo DI::l10n()->t('The database version had been set to %s.', $version);
65         }
66
67         /**
68          * Drop unused tables
69          *
70          * @param boolean $execute
71          * @return void
72          */
73         public static function dropTables(bool $execute)
74         {
75                 $postupdate = DI::config()->get("system", "post_update_version", PostUpdate::VERSION);
76                 if ($postupdate < PostUpdate::VERSION) {
77                         echo DI::l10n()->t('The post update is at version %d, it has to be at %d to safely drop the tables.', $postupdate, PostUpdate::VERSION);
78                         return;
79                 }
80
81                 $old_tables = ['fserver', 'gcign', 'gcontact', 'gcontact-relation', 'gfollower' ,'glink', 'item-delivery-data',
82                         'item-activity', 'item-content', 'item_id', 'participation', 'poll', 'poll_result', 'queue', 'retriever_rule',
83                         'deliverq', 'dsprphotoq', 'ffinder', 'sign', 'spam', 'term', 'user-item', 'thread', 'item'];
84
85                 $tables = DBA::selectToArray(['INFORMATION_SCHEMA' => 'TABLES'], ['TABLE_NAME'],
86                         ['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_TYPE' => 'BASE TABLE']);
87
88                 if (empty($tables)) {
89                         echo DI::l10n()->t('No unused tables found.');
90                         return;
91                 }
92
93                 if (!$execute) {
94                         echo DI::l10n()->t('These tables are not used for friendica and will be deleted when you execute "dbstructure drop -e":') . "\n\n";
95                 }
96
97                 foreach ($tables as $table) {
98                         if (in_array($table['TABLE_NAME'], $old_tables)) {
99                                 if ($execute) {
100                                         $sql = 'DROP TABLE ' . DBA::quoteIdentifier($table['TABLE_NAME']) . ';';
101                                         echo $sql . "\n";
102
103                                         $result = DBA::e($sql);
104                                         if (!DBA::isResult($result)) {
105                                                 self::printUpdateError($sql);
106                                         }
107                                 } else {
108                                         echo $table['TABLE_NAME'] . "\n";
109                                 }
110                         }
111                 }
112         }
113
114         /**
115          * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
116          */
117         public static function convertToInnoDB()
118         {
119                 $tables = DBA::selectToArray(
120                         ['information_schema' => 'tables'],
121                         ['table_name'],
122                         ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
123                 );
124
125                 $tables = array_merge($tables, DBA::selectToArray(
126                         ['information_schema' => 'tables'],
127                         ['table_name'],
128                         ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
129                 ));
130
131                 if (!DBA::isResult($tables)) {
132                         echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
133                         return;
134                 }
135
136                 foreach ($tables AS $table) {
137                         $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
138                         echo $sql . "\n";
139
140                         $result = DBA::e($sql);
141                         if (!DBA::isResult($result)) {
142                                 self::printUpdateError($sql);
143                         }
144                 }
145         }
146
147         /**
148          * Print out database error messages
149          *
150          * @param string $message Message to be added to the error message
151          *
152          * @return string Error message
153          */
154         private static function printUpdateError($message)
155         {
156                 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
157                         DBA::errorNo(), DBA::errorMessage());
158
159                 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
160         }
161
162         public static function printStructure($basePath)
163         {
164                 $database = self::definition($basePath, false);
165
166                 echo "-- ------------------------------------------\n";
167                 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
168                 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
169                 echo "-- ------------------------------------------\n\n\n";
170                 foreach ($database AS $name => $structure) {
171                         echo "--\n";
172                         echo "-- TABLE $name\n";
173                         echo "--\n";
174                         self::createTable($name, $structure, true, false);
175
176                         echo "\n";
177                 }
178
179                 View::printStructure($basePath);
180         }
181
182         /**
183          * Loads the database structure definition from the static/dbstructure.config.php file.
184          * On first pass, defines DB_UPDATE_VERSION constant.
185          *
186          * @see static/dbstructure.config.php
187          * @param boolean $with_addons_structure Whether to tack on addons additional tables
188          * @param string  $basePath              The base path of this application
189          * @return array
190          * @throws Exception
191          */
192         public static function definition($basePath, $with_addons_structure = true)
193         {
194                 if (!self::$definition) {
195                         if (empty($basePath)) {
196                                 $basePath = DI::app()->getBasePath();
197                         }
198
199                         $filename = $basePath . '/static/dbstructure.config.php';
200
201                         if (!is_readable($filename)) {
202                                 throw new Exception('Missing database structure config file static/dbstructure.config.php');
203                         }
204
205                         $definition = require $filename;
206
207                         if (!$definition) {
208                                 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
209                         }
210
211                         self::$definition = $definition;
212                 } else {
213                         $definition = self::$definition;
214                 }
215
216                 if ($with_addons_structure) {
217                         Hook::callAll('dbstructure_definition', $definition);
218                 }
219
220                 return $definition;
221         }
222
223         /**
224          * Get field data for the given table
225          *
226          * @param string $table
227          * @param array $data data fields
228          * @return array fields for the given
229          */
230         public static function getFieldsForTable(string $table, array $data = [])
231         {
232                 $definition = DBStructure::definition('', false);
233                 if (empty($definition[$table])) {
234                         return [];
235                 }
236
237                 $fieldnames = array_keys($definition[$table]['fields']);
238
239                 $fields = [];
240
241                 // Assign all field that are present in the table
242                 foreach ($fieldnames as $field) {
243                         if (isset($data[$field])) {
244                                 // Limit the length of varchar, varbinary, char and binrary fields
245                                 if (is_string($data[$field]) && preg_match("/[char|binary]\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
246                                         $data[$field] = mb_substr($data[$field], 0, $result[1]);
247                                 }
248                                 $fields[$field] = $data[$field];
249                         }
250                 }
251
252                 return $fields;
253         }
254
255         private static function createTable($name, $structure, $verbose, $action)
256         {
257                 $r = true;
258
259                 $engine = "";
260                 $comment = "";
261                 $sql_rows = [];
262                 $primary_keys = [];
263                 $foreign_keys = [];
264
265                 foreach ($structure["fields"] AS $fieldname => $field) {
266                         $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
267                         if (!empty($field['primary'])) {
268                                 $primary_keys[] = $fieldname;
269                         }
270                         if (!empty($field['foreign'])) {
271                                 $foreign_keys[$fieldname] = $field;
272                         }
273                 }
274
275                 if (!empty($structure["indexes"])) {
276                         foreach ($structure["indexes"] AS $indexname => $fieldnames) {
277                                 $sql_index = self::createIndex($indexname, $fieldnames, "");
278                                 if (!is_null($sql_index)) {
279                                         $sql_rows[] = $sql_index;
280                                 }
281                         }
282                 }
283
284                 foreach ($foreign_keys AS $fieldname => $parameters) {
285                         $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
286                 }
287
288                 if (isset($structure["engine"])) {
289                         $engine = " ENGINE=" . $structure["engine"];
290                 }
291
292                 if (isset($structure["comment"])) {
293                         $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
294                 }
295
296                 $sql = implode(",\n\t", $sql_rows);
297
298                 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
299                         "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
300                 if ($verbose) {
301                         echo $sql . ";\n";
302                 }
303
304                 if ($action) {
305                         $r = DBA::e($sql);
306                 }
307
308                 return $r;
309         }
310
311         private static function FieldCommand($parameters, $create = true)
312         {
313                 $fieldstruct = $parameters["type"];
314
315                 if (isset($parameters["Collation"])) {
316                         $fieldstruct .= " COLLATE " . $parameters["Collation"];
317                 }
318
319                 if (isset($parameters["not null"])) {
320                         $fieldstruct .= " NOT NULL";
321                 }
322
323                 if (isset($parameters["default"])) {
324                         if (strpos(strtolower($parameters["type"]), "int") !== false) {
325                                 $fieldstruct .= " DEFAULT " . $parameters["default"];
326                         } else {
327                                 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
328                         }
329                 }
330                 if (isset($parameters["extra"])) {
331                         $fieldstruct .= " " . $parameters["extra"];
332                 }
333
334                 if (isset($parameters["comment"])) {
335                         $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
336                 }
337
338                 /*if (($parameters["primary"] != "") && $create)
339                         $fieldstruct .= " PRIMARY KEY";*/
340
341                 return ($fieldstruct);
342         }
343
344         private static function createIndex($indexname, $fieldnames, $method = "ADD")
345         {
346                 $method = strtoupper(trim($method));
347                 if ($method != "" && $method != "ADD") {
348                         throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
349                 }
350
351                 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
352                         $index_type = array_shift($fieldnames);
353                         $method .= " " . $index_type;
354                 }
355
356                 $names = "";
357                 foreach ($fieldnames AS $fieldname) {
358                         if ($names != "") {
359                                 $names .= ",";
360                         }
361
362                         if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
363                                 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
364                         } else {
365                                 $names .= "`" . DBA::escape($fieldname) . "`";
366                         }
367                 }
368
369                 if ($indexname == "PRIMARY") {
370                         return sprintf("%s PRIMARY KEY(%s)", $method, $names);
371                 }
372
373
374                 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
375                 return ($sql);
376         }
377
378         /**
379          * Perform a database structure dryrun (means: just simulating)
380          *
381          * @throws Exception
382          */
383         public static function dryRun()
384         {
385                 self::update(DI::app()->getBasePath(), true, false);
386         }
387
388         /**
389          * Updates DB structure and returns eventual errors messages
390          *
391          * @param bool $enable_maintenance_mode Set the maintenance mode
392          * @param bool $verbose                 Display the SQL commands
393          *
394          * @return string Empty string if the update is successful, error messages otherwise
395          * @throws Exception
396          */
397         public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false)
398         {
399                 if ($enable_maintenance_mode) {
400                         DI::config()->set('system', 'maintenance', 1);
401                 }
402
403                 $status = self::update(DI::app()->getBasePath(), $verbose, true);
404
405                 if ($enable_maintenance_mode) {
406                         DI::config()->set('system', 'maintenance', 0);
407                         DI::config()->set('system', 'maintenance_reason', '');
408                 }
409
410                 return $status;
411         }
412
413         /**
414          * Updates DB structure from the installation and returns eventual errors messages
415          *
416          * @param string $basePath   The base path of this application
417          *
418          * @return string Empty string if the update is successful, error messages otherwise
419          * @throws Exception
420          */
421         public static function install(string $basePath)
422         {
423                 return self::update($basePath, false, true, true);
424         }
425
426         /**
427          * Updates DB structure and returns eventual errors messages
428          *
429          * @param string $basePath   The base path of this application
430          * @param bool   $verbose
431          * @param bool   $action     Whether to actually apply the update
432          * @param bool   $install    Is this the initial update during the installation?
433          * @param array  $tables     An array of the database tables
434          * @param array  $definition An array of the definition tables
435          * @return string Empty string if the update is successful, error messages otherwise
436          * @throws Exception
437          */
438         private static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
439         {
440                 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
441
442                 if ($action && !$install && self::isUpdating()) {
443                         return DI::l10n()->t('Another database update is currently running.');
444                 }
445
446                 if ($in_maintenance_mode) {
447                         DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
448                 }
449
450                 // ensure that all initial values exist. This test has to be done prior and after the structure check.
451                 // Prior is needed if the specific tables already exists - after is needed when they had been created.
452                 self::checkInitialValues();
453
454                 $errors = '';
455
456                 Logger::info('updating structure');
457
458                 // Get the current structure
459                 $database = [];
460
461                 if (is_null($tables)) {
462                         $tables = DBA::toArray(DBA::p("SHOW TABLES"));
463                 }
464
465                 if (DBA::isResult($tables)) {
466                         foreach ($tables AS $table) {
467                                 $table = current($table);
468
469                                 Logger::info('updating structure', ['table' => $table]);
470                                 $database[$table] = self::tableStructure($table);
471                         }
472                 }
473
474                 // Get the definition
475                 if (is_null($definition)) {
476                         $definition = self::definition($basePath);
477                 }
478
479                 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
480                 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
481                         !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
482                         $ignore = '';
483                 } else {
484                         $ignore = ' IGNORE';
485                 }
486
487                 // Compare it
488                 foreach ($definition AS $name => $structure) {
489                         $is_new_table = false;
490                         $group_by = "";
491                         $sql3 = "";
492                         $is_unique = false;
493                         $temp_name = $name;
494                         if (!isset($database[$name])) {
495                                 $r = self::createTable($name, $structure, $verbose, $action);
496                                 if (!DBA::isResult($r)) {
497                                         $errors .= self::printUpdateError($name);
498                                 }
499                                 $is_new_table = true;
500                         } else {
501                                 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
502                                         if (isset($database[$name]["indexes"][$indexname])) {
503                                                 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
504                                         } else {
505                                                 $current_index_definition = "__NOT_SET__";
506                                         }
507                                         $new_index_definition = implode(",", $fieldnames);
508                                         if ($current_index_definition != $new_index_definition) {
509                                                 if ($fieldnames[0] == "UNIQUE") {
510                                                         $is_unique = true;
511                                                         if ($ignore == "") {
512                                                                 $temp_name = "temp-" . $name;
513                                                         }
514                                                 }
515                                         }
516                                 }
517
518                                 /*
519                                  * Drop the index if it isn't present in the definition
520                                  * or the definition differ from current status
521                                  * and index name doesn't start with "local_"
522                                  */
523                                 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
524                                         $current_index_definition = implode(",", $fieldnames);
525                                         if (isset($structure["indexes"][$indexname])) {
526                                                 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
527                                         } else {
528                                                 $new_index_definition = "__NOT_SET__";
529                                         }
530                                         if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
531                                                 $sql2 = self::dropIndex($indexname);
532                                                 if ($sql3 == "") {
533                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
534                                                 } else {
535                                                         $sql3 .= ", " . $sql2;
536                                                 }
537                                         }
538                                 }
539                                 // Compare the field structure field by field
540                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
541                                         if (!isset($database[$name]["fields"][$fieldname])) {
542                                                 $sql2 = self::addTableField($fieldname, $parameters);
543                                                 if ($sql3 == "") {
544                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
545                                                 } else {
546                                                         $sql3 .= ", " . $sql2;
547                                                 }
548                                         } else {
549                                                 // Compare the field definition
550                                                 $field_definition = $database[$name]["fields"][$fieldname];
551
552                                                 // Remove the relation data that is used for the referential integrity
553                                                 unset($parameters['relation']);
554                                                 unset($parameters['foreign']);
555
556                                                 // We change the collation after the indexes had been changed.
557                                                 // This is done to avoid index length problems.
558                                                 // So here we always ensure that there is no need to change it.
559                                                 unset($parameters['Collation']);
560                                                 unset($field_definition['Collation']);
561
562                                                 // Only update the comment when it is defined
563                                                 if (!isset($parameters['comment'])) {
564                                                         $parameters['comment'] = "";
565                                                 }
566
567                                                 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
568                                                 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
569                                                 if ($current_field_definition != $new_field_definition) {
570                                                         $sql2 = self::modifyTableField($fieldname, $parameters);
571                                                         if ($sql3 == "") {
572                                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
573                                                         } else {
574                                                                 $sql3 .= ", " . $sql2;
575                                                         }
576                                                 }
577                                         }
578                                 }
579                         }
580
581                         /*
582                          * Create the index if the index don't exists in database
583                          * or the definition differ from the current status.
584                          * Don't create keys if table is new
585                          */
586                         if (!$is_new_table) {
587                                 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
588                                         if (isset($database[$name]["indexes"][$indexname])) {
589                                                 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
590                                         } else {
591                                                 $current_index_definition = "__NOT_SET__";
592                                         }
593                                         $new_index_definition = implode(",", $fieldnames);
594                                         if ($current_index_definition != $new_index_definition) {
595                                                 $sql2 = self::createIndex($indexname, $fieldnames);
596
597                                                 // Fetch the "group by" fields for unique indexes
598                                                 $group_by = self::groupBy($fieldnames);
599                                                 if ($sql2 != "") {
600                                                         if ($sql3 == "") {
601                                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
602                                                         } else {
603                                                                 $sql3 .= ", " . $sql2;
604                                                         }
605                                                 }
606                                         }
607                                 }
608
609                                 $existing_foreign_keys = $database[$name]['foreign_keys'];
610
611                                 // Foreign keys
612                                 // Compare the field structure field by field
613                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
614                                         if (empty($parameters['foreign'])) {
615                                                 continue;
616                                         }
617
618                                         $constraint = self::getConstraintName($name, $fieldname, $parameters);
619
620                                         unset($existing_foreign_keys[$constraint]);
621
622                                         if (empty($database[$name]['foreign_keys'][$constraint])) {
623                                                 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
624
625                                                 if ($sql3 == "") {
626                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
627                                                 } else {
628                                                         $sql3 .= ", " . $sql2;
629                                                 }
630                                         }
631                                 }
632
633                                 foreach ($existing_foreign_keys as $param) {
634                                         $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
635
636                                         if ($sql3 == "") {
637                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
638                                         } else {
639                                                 $sql3 .= ", " . $sql2;
640                                         }
641                                 }
642
643                                 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
644                                         $structurecomment = $structure["comment"] ?? '';
645                                         if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
646                                                 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
647
648                                                 if ($sql3 == "") {
649                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
650                                                 } else {
651                                                         $sql3 .= ", " . $sql2;
652                                                 }
653                                         }
654                                 }
655
656                                 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
657                                         if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
658                                                 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
659
660                                                 if ($sql3 == "") {
661                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
662                                                 } else {
663                                                         $sql3 .= ", " . $sql2;
664                                                 }
665                                         }
666                                 }
667
668                                 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
669                                         if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
670                                                 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
671
672                                                 if ($sql3 == "") {
673                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
674                                                 } else {
675                                                         $sql3 .= ", " . $sql2;
676                                                 }
677                                         }
678                                 }
679
680                                 if ($sql3 != "") {
681                                         $sql3 .= "; ";
682                                 }
683
684                                 // Now have a look at the field collations
685                                 // Compare the field structure field by field
686                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
687                                         // Compare the field definition
688                                         $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
689
690                                         // Define the default collation if not given
691                                         if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
692                                                 $parameters['Collation'] = 'utf8mb4_general_ci';
693                                         } else {
694                                                 $parameters['Collation'] = null;
695                                         }
696
697                                         if ($field_definition['Collation'] != $parameters['Collation']) {
698                                                 $sql2 = self::modifyTableField($fieldname, $parameters);
699                                                 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
700                                                         $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
701                                                 } else {
702                                                         $sql3 .= ", " . $sql2;
703                                                 }
704                                         }
705                                 }
706                         }
707
708                         if ($sql3 != "") {
709                                 if (substr($sql3, -2, 2) != "; ") {
710                                         $sql3 .= ";";
711                                 }
712
713                                 $field_list = '';
714                                 if ($is_unique && $ignore == '') {
715                                         foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
716                                                 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
717                                         }
718                                         $field_list = rtrim($field_list, ',');
719                                 }
720
721                                 if ($verbose) {
722                                         // Ensure index conversion to unique removes duplicates
723                                         if ($is_unique && ($temp_name != $name)) {
724                                                 if ($ignore != "") {
725                                                         echo "SET session old_alter_table=1;\n";
726                                                 } else {
727                                                         echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
728                                                         echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
729                                                 }
730                                         }
731
732                                         echo $sql3 . "\n";
733
734                                         if ($is_unique && ($temp_name != $name)) {
735                                                 if ($ignore != "") {
736                                                         echo "SET session old_alter_table=0;\n";
737                                                 } else {
738                                                         echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
739                                                         echo "DROP TABLE `" . $name . "`;\n";
740                                                         echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
741                                                 }
742                                         }
743                                 }
744
745                                 if ($action) {
746                                         if ($in_maintenance_mode) {
747                                                 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
748                                         }
749
750                                         // Ensure index conversion to unique removes duplicates
751                                         if ($is_unique && ($temp_name != $name)) {
752                                                 if ($ignore != "") {
753                                                         DBA::e("SET session old_alter_table=1;");
754                                                 } else {
755                                                         $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
756                                                         if (!DBA::isResult($r)) {
757                                                                 $errors .= self::printUpdateError($sql3);
758                                                                 return $errors;
759                                                         }
760
761                                                         $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
762                                                         if (!DBA::isResult($r)) {
763                                                                 $errors .= self::printUpdateError($sql3);
764                                                                 return $errors;
765                                                         }
766                                                 }
767                                         }
768
769                                         $r = DBA::e($sql3);
770                                         if (!DBA::isResult($r)) {
771                                                 $errors .= self::printUpdateError($sql3);
772                                         }
773                                         if ($is_unique && ($temp_name != $name)) {
774                                                 if ($ignore != "") {
775                                                         DBA::e("SET session old_alter_table=0;");
776                                                 } else {
777                                                         $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
778                                                         if (!DBA::isResult($r)) {
779                                                                 $errors .= self::printUpdateError($sql3);
780                                                                 return $errors;
781                                                         }
782                                                         $r = DBA::e("DROP TABLE `" . $name . "`;");
783                                                         if (!DBA::isResult($r)) {
784                                                                 $errors .= self::printUpdateError($sql3);
785                                                                 return $errors;
786                                                         }
787                                                         $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
788                                                         if (!DBA::isResult($r)) {
789                                                                 $errors .= self::printUpdateError($sql3);
790                                                                 return $errors;
791                                                         }
792                                                 }
793                                         }
794                                 }
795                         }
796                 }
797
798                 View::create(false, $action);
799
800                 self::checkInitialValues();
801
802                 if ($action && !$install) {
803                         if ($errors) {
804                                 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
805                         } else {
806                                 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
807                         }
808                 }
809
810                 return $errors;
811         }
812
813         private static function tableStructure($table)
814         {
815                 // This query doesn't seem to be executable as a prepared statement
816                 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
817
818                 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
819                         ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
820                         'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
821                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
822                         DBA::databaseName(), $table]);
823
824                 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
825                         ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
826                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
827                         DBA::databaseName(), $table]);
828
829                 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
830                         ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
831                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
832                         DBA::databaseName(), $table]);
833
834                 $fielddata = [];
835                 $indexdata = [];
836                 $foreigndata = [];
837
838                 if (DBA::isResult($foreign_keys)) {
839                         foreach ($foreign_keys as $foreign_key) {
840                                 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
841                                 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
842                                 $foreigndata[$constraint] = $foreign_key;
843                         }
844                 }
845
846                 if (DBA::isResult($indexes)) {
847                         foreach ($indexes AS $index) {
848                                 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
849                                         $indexdata[$index["Key_name"]] = ["UNIQUE"];
850                                 }
851
852                                 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
853                                         $indexdata[$index["Key_name"]] = ["FULLTEXT"];
854                                 }
855
856                                 $column = $index["Column_name"];
857
858                                 if ($index["Sub_part"] != "") {
859                                         $column .= "(" . $index["Sub_part"] . ")";
860                                 }
861
862                                 $indexdata[$index["Key_name"]][] = $column;
863                         }
864                 }
865
866                 $fielddata = [];
867                 if (DBA::isResult($fields)) {
868                         foreach ($fields AS $field) {
869                                 $search = ['tinyint(1)', 'tinyint(3) unsigned', 'tinyint(4)', 'smallint(5) unsigned', 'smallint(6)', 'mediumint(8) unsigned', 'mediumint(9)', 'bigint(20)', 'int(10) unsigned', 'int(11)'];
870                                 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
871                                 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
872
873                                 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
874
875                                 if ($field['IS_NULLABLE'] == 'NO') {
876                                         $fielddata[$field['COLUMN_NAME']]['not null'] = true;
877                                 }
878
879                                 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
880                                         $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
881                                 }
882
883                                 if (!empty($field['EXTRA'])) {
884                                         $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
885                                 }
886
887                                 if ($field['COLUMN_KEY'] == 'PRI') {
888                                         $fielddata[$field['COLUMN_NAME']]['primary'] = true;
889                                 }
890
891                                 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
892                                 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
893                         }
894                 }
895
896                 return ["fields" => $fielddata, "indexes" => $indexdata,
897                         "foreign_keys" => $foreigndata, "table_status" => $table_status];
898         }
899
900         private static function dropIndex($indexname)
901         {
902                 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
903                 return ($sql);
904         }
905
906         private static function addTableField($fieldname, $parameters)
907         {
908                 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
909                 return ($sql);
910         }
911
912         private static function modifyTableField($fieldname, $parameters)
913         {
914                 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
915                 return ($sql);
916         }
917
918         private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
919         {
920                 $foreign_table = array_keys($parameters['foreign'])[0];
921                 $foreign_field = array_values($parameters['foreign'])[0];
922
923                 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
924         }
925
926         private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
927                 $foreign_table = array_keys($parameters['foreign'])[0];
928                 $foreign_field = array_values($parameters['foreign'])[0];
929
930                 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
931
932                 if (!empty($parameters['foreign']['on update'])) {
933                         $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
934                 } else {
935                         $sql .= " ON UPDATE RESTRICT";
936                 }
937
938                 if (!empty($parameters['foreign']['on delete'])) {
939                         $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
940                 } else {
941                         $sql .= " ON DELETE CASCADE";
942                 }
943
944                 return $sql;
945         }
946
947         private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
948         {
949                 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
950         }
951
952         private static function dropForeignKey(string $constraint)
953         {
954                 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
955         }
956
957         /**
958          * Constructs a GROUP BY clause from a UNIQUE index definition.
959          *
960          * @param array $fieldnames
961          * @return string
962          */
963         private static function groupBy(array $fieldnames)
964         {
965                 if ($fieldnames[0] != "UNIQUE") {
966                         return "";
967                 }
968
969                 array_shift($fieldnames);
970
971                 $names = "";
972                 foreach ($fieldnames AS $fieldname) {
973                         if ($names != "") {
974                                 $names .= ",";
975                         }
976
977                         if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
978                                 $names .= "`" . DBA::escape($matches[1]) . "`";
979                         } else {
980                                 $names .= "`" . DBA::escape($fieldname) . "`";
981                         }
982                 }
983
984                 $sql = sprintf(" GROUP BY %s", $names);
985                 return $sql;
986         }
987
988         /**
989          * Renames columns or the primary key of a table
990          *
991          * @todo You cannot rename a primary key if "auto increment" is set
992          *
993          * @param string $table            Table name
994          * @param array  $columns          Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
995          *                                 Syntax for Primary Key: [ $col1, $col2, ...]
996          * @param int    $type             The type of renaming (Default is Column)
997          *
998          * @return boolean Was the renaming successful?
999          * @throws Exception
1000          */
1001         public static function rename($table, $columns, $type = self::RENAME_COLUMN)
1002         {
1003                 if (empty($table) || empty($columns)) {
1004                         return false;
1005                 }
1006
1007                 if (!is_array($columns)) {
1008                         return false;
1009                 }
1010
1011                 $table = DBA::escape($table);
1012
1013                 $sql = "ALTER TABLE `" . $table . "`";
1014                 switch ($type) {
1015                         case self::RENAME_COLUMN:
1016                                 if (!self::existsColumn($table, array_keys($columns))) {
1017                                         return false;
1018                                 }
1019                                 $sql .= implode(',', array_map(
1020                                         function ($to, $from) {
1021                                                 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1022                                         },
1023                                         $columns,
1024                                         array_keys($columns)
1025                                 ));
1026                                 break;
1027                         case self::RENAME_PRIMARY_KEY:
1028                                 if (!self::existsColumn($table, $columns)) {
1029                                         return false;
1030                                 }
1031                                 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1032                                 break;
1033                         default:
1034                                 return false;
1035                 }
1036
1037                 $sql .= ";";
1038
1039                 $stmt = DBA::p($sql);
1040
1041                 if (is_bool($stmt)) {
1042                         $retval = $stmt;
1043                 } else {
1044                         $retval = true;
1045                 }
1046
1047                 DBA::close($stmt);
1048
1049                 return $retval;
1050         }
1051
1052         /**
1053          *    Check if the columns of the table exists
1054          *
1055          * @param string $table   Table name
1056          * @param array  $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1057          *
1058          * @return boolean Does the table exist?
1059          * @throws Exception
1060          */
1061         public static function existsColumn($table, $columns = [])
1062         {
1063                 if (empty($table)) {
1064                         return false;
1065                 }
1066
1067                 if (is_null($columns) || empty($columns)) {
1068                         return self::existsTable($table);
1069                 }
1070
1071                 $table = DBA::escape($table);
1072
1073                 foreach ($columns AS $column) {
1074                         $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1075
1076                         $stmt = DBA::p($sql);
1077
1078                         if (is_bool($stmt)) {
1079                                 $retval = $stmt;
1080                         } else {
1081                                 $retval = (DBA::numRows($stmt) > 0);
1082                         }
1083
1084                         DBA::close($stmt);
1085
1086                         if (!$retval) {
1087                                 return false;
1088                         }
1089                 }
1090
1091                 return true;
1092         }
1093
1094         /**
1095          * Check if a foreign key exists for the given table field
1096          *
1097          * @param string $table
1098          * @param string $field
1099          * @return boolean
1100          */
1101         public static function existsForeignKeyForField(string $table, string $field)
1102         {
1103                 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1104                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1105                         DBA::databaseName(), $table, $field]);
1106         }
1107         /**
1108          *    Check if a table exists
1109          *
1110          * @param string|array $table Table name
1111          *
1112          * @return boolean Does the table exist?
1113          * @throws Exception
1114          */
1115         public static function existsTable($table)
1116         {
1117                 if (empty($table)) {
1118                         return false;
1119                 }
1120
1121                 if (is_array($table)) {
1122                         $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1123                 } else {
1124                         $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1125                 }
1126
1127                 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1128
1129                 return $result;
1130         }
1131
1132         /**
1133          * Returns the columns of a table
1134          *
1135          * @param string $table Table name
1136          *
1137          * @return array An array of the table columns
1138          * @throws Exception
1139          */
1140         public static function getColumns($table)
1141         {
1142                 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1143                 return DBA::toArray($stmtColumns);
1144         }
1145
1146         /**
1147          * Check if initial database values do exist - or create them
1148          */
1149         public static function checkInitialValues(bool $verbose = false)
1150         {
1151                 if (self::existsTable('verb')) {
1152                         if (!DBA::exists('verb', ['id' => 1])) {
1153                                 foreach (Item::ACTIVITIES as $index => $activity) {
1154                                         DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1155                                 }
1156                                 if ($verbose) {
1157                                         echo "verb: activities added\n";
1158                                 }
1159                         } elseif ($verbose) {
1160                                 echo "verb: activities already added\n";
1161                         }
1162
1163                         if (!DBA::exists('verb', ['id' => 0])) {
1164                                 DBA::insert('verb', ['name' => '']);
1165                                 $lastid = DBA::lastInsertId();
1166                                 if ($lastid != 0) {
1167                                         DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1168                                         if ($verbose) {
1169                                                 echo "Zero verb added\n";
1170                                         }
1171                                 }
1172                         } elseif ($verbose) {
1173                                 echo "Zero verb already added\n";
1174                         }
1175                 } elseif ($verbose) {
1176                         echo "verb: Table not found\n";
1177                 }
1178
1179                 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1180                         $user = [
1181                                 "verified" => true,
1182                                 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1183                                 "account-type" => User::ACCOUNT_TYPE_RELAY,
1184                         ];
1185                         DBA::insert('user', $user);
1186                         $lastid = DBA::lastInsertId();
1187                         if ($lastid != 0) {
1188                                 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1189                                 if ($verbose) {
1190                                         echo "Zero user added\n";
1191                                 }
1192                         }
1193                 } elseif (self::existsTable('user') && $verbose) {
1194                         echo "Zero user already added\n";
1195                 } elseif ($verbose) {
1196                         echo "user: Table not found\n";
1197                 }
1198
1199                 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1200                         DBA::insert('contact', ['nurl' => '']);
1201                         $lastid = DBA::lastInsertId();
1202                         if ($lastid != 0) {
1203                                 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1204                                 if ($verbose) {
1205                                         echo "Zero contact added\n";
1206                                 }
1207                         }               
1208                 } elseif (self::existsTable('contact') && $verbose) {
1209                         echo "Zero contact already added\n";
1210                 } elseif ($verbose) {
1211                         echo "contact: Table not found\n";
1212                 }
1213
1214                 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1215                         DBA::insert('tag', ['name' => '']);
1216                         $lastid = DBA::lastInsertId();
1217                         if ($lastid != 0) {
1218                                 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1219                                 if ($verbose) {
1220                                         echo "Zero tag added\n";
1221                                 }
1222                         }
1223                 } elseif (self::existsTable('tag') && $verbose) {
1224                         echo "Zero tag already added\n";
1225                 } elseif ($verbose) {
1226                         echo "tag: Table not found\n";
1227                 }
1228
1229                 if (self::existsTable('permissionset')) {
1230                         if (!DBA::exists('permissionset', ['id' => 0])) {
1231                                 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);       
1232                                 $lastid = DBA::lastInsertId();
1233                                 if ($lastid != 0) {
1234                                         DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1235                                         if ($verbose) {
1236                                                 echo "Zero permissionset added\n";
1237                                         }
1238                                 }
1239                         } elseif ($verbose) {
1240                                 echo "Zero permissionset already added\n";
1241                         }
1242                         if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
1243                                 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1244                                         LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1245                                         WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1246                                 while ($set = DBA::fetch($sets)) {
1247                                         if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1248                                                 $owner = User::getOwnerDataById($set['uid']);
1249                                                 if ($owner) {
1250                                                         $permission = '<' . $owner['id'] . '>';
1251                                                 } else {
1252                                                         $permission = '<>';
1253                                                 }
1254                                         } else {
1255                                                 $permission = '';
1256                                         }
1257                                         $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1258                                                 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1259                                         DBA::insert('permissionset', $fields);
1260                                 }
1261                                 DBA::close($sets);
1262                         }
1263                 } elseif ($verbose) {
1264                         echo "permissionset: Table not found\n";
1265                 }
1266         
1267                 if (!self::existsForeignKeyForField('tokens', 'client_id')) {
1268                         $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1269                                 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1270                                 WHERE `clients`.`client_id` IS NULL");
1271                         while ($token = DBA::fetch($tokens)) {
1272                                 DBA::delete('tokens', ['id' => $token['id']]);
1273                         }
1274                         DBA::close($tokens);
1275                 }
1276         }
1277
1278         /**
1279          * Checks if a database update is currently running
1280          *
1281          * @return boolean
1282          */
1283         private static function isUpdating()
1284         {
1285                 $isUpdate = false;
1286
1287                 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1288                         ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1289
1290                 while ($process = DBA::fetch($processes)) {
1291                         $parts = explode(' ', $process['info']);
1292                         if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1293                                 $isUpdate = true;
1294                         }
1295                 }
1296
1297                 DBA::close($processes);
1298
1299                 return $isUpdate;
1300         }
1301 }