]> git.mxchange.org Git - friendica.git/blob - src/Database/DBStructure.php
Merge pull request #10318 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\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
246                                         $data[$field] = mb_substr($data[$field], 0, $result[1]);
247                                 } elseif (is_string($data[$field]) && preg_match("/binary\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
248                                         $data[$field] = substr($data[$field], 0, $result[1]);
249                                 }
250                                 $fields[$field] = $data[$field];
251                         }
252                 }
253
254                 return $fields;
255         }
256
257         private static function createTable($name, $structure, $verbose, $action)
258         {
259                 $r = true;
260
261                 $engine = "";
262                 $comment = "";
263                 $sql_rows = [];
264                 $primary_keys = [];
265                 $foreign_keys = [];
266
267                 foreach ($structure["fields"] AS $fieldname => $field) {
268                         $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
269                         if (!empty($field['primary'])) {
270                                 $primary_keys[] = $fieldname;
271                         }
272                         if (!empty($field['foreign'])) {
273                                 $foreign_keys[$fieldname] = $field;
274                         }
275                 }
276
277                 if (!empty($structure["indexes"])) {
278                         foreach ($structure["indexes"] AS $indexname => $fieldnames) {
279                                 $sql_index = self::createIndex($indexname, $fieldnames, "");
280                                 if (!is_null($sql_index)) {
281                                         $sql_rows[] = $sql_index;
282                                 }
283                         }
284                 }
285
286                 foreach ($foreign_keys AS $fieldname => $parameters) {
287                         $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
288                 }
289
290                 if (isset($structure["engine"])) {
291                         $engine = " ENGINE=" . $structure["engine"];
292                 }
293
294                 if (isset($structure["comment"])) {
295                         $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
296                 }
297
298                 $sql = implode(",\n\t", $sql_rows);
299
300                 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
301                         "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
302                 if ($verbose) {
303                         echo $sql . ";\n";
304                 }
305
306                 if ($action) {
307                         $r = DBA::e($sql);
308                 }
309
310                 return $r;
311         }
312
313         private static function FieldCommand($parameters, $create = true)
314         {
315                 $fieldstruct = $parameters["type"];
316
317                 if (isset($parameters["Collation"])) {
318                         $fieldstruct .= " COLLATE " . $parameters["Collation"];
319                 }
320
321                 if (isset($parameters["not null"])) {
322                         $fieldstruct .= " NOT NULL";
323                 }
324
325                 if (isset($parameters["default"])) {
326                         if (strpos(strtolower($parameters["type"]), "int") !== false) {
327                                 $fieldstruct .= " DEFAULT " . $parameters["default"];
328                         } else {
329                                 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
330                         }
331                 }
332                 if (isset($parameters["extra"])) {
333                         $fieldstruct .= " " . $parameters["extra"];
334                 }
335
336                 if (isset($parameters["comment"])) {
337                         $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
338                 }
339
340                 /*if (($parameters["primary"] != "") && $create)
341                         $fieldstruct .= " PRIMARY KEY";*/
342
343                 return ($fieldstruct);
344         }
345
346         private static function createIndex($indexname, $fieldnames, $method = "ADD")
347         {
348                 $method = strtoupper(trim($method));
349                 if ($method != "" && $method != "ADD") {
350                         throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
351                 }
352
353                 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
354                         $index_type = array_shift($fieldnames);
355                         $method .= " " . $index_type;
356                 }
357
358                 $names = "";
359                 foreach ($fieldnames AS $fieldname) {
360                         if ($names != "") {
361                                 $names .= ",";
362                         }
363
364                         if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
365                                 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
366                         } else {
367                                 $names .= "`" . DBA::escape($fieldname) . "`";
368                         }
369                 }
370
371                 if ($indexname == "PRIMARY") {
372                         return sprintf("%s PRIMARY KEY(%s)", $method, $names);
373                 }
374
375
376                 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
377                 return ($sql);
378         }
379
380         /**
381          * Perform a database structure dryrun (means: just simulating)
382          *
383          * @throws Exception
384          */
385         public static function dryRun()
386         {
387                 self::update(DI::app()->getBasePath(), true, false);
388         }
389
390         /**
391          * Updates DB structure and returns eventual errors messages
392          *
393          * @param bool $enable_maintenance_mode Set the maintenance mode
394          * @param bool $verbose                 Display the SQL commands
395          *
396          * @return string Empty string if the update is successful, error messages otherwise
397          * @throws Exception
398          */
399         public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false)
400         {
401                 if ($enable_maintenance_mode) {
402                         DI::config()->set('system', 'maintenance', 1);
403                 }
404
405                 $status = self::update(DI::app()->getBasePath(), $verbose, true);
406
407                 if ($enable_maintenance_mode) {
408                         DI::config()->set('system', 'maintenance', 0);
409                         DI::config()->set('system', 'maintenance_reason', '');
410                 }
411
412                 return $status;
413         }
414
415         /**
416          * Updates DB structure from the installation and returns eventual errors messages
417          *
418          * @param string $basePath   The base path of this application
419          *
420          * @return string Empty string if the update is successful, error messages otherwise
421          * @throws Exception
422          */
423         public static function install(string $basePath)
424         {
425                 return self::update($basePath, false, true, true);
426         }
427
428         /**
429          * Updates DB structure and returns eventual errors messages
430          *
431          * @param string $basePath   The base path of this application
432          * @param bool   $verbose
433          * @param bool   $action     Whether to actually apply the update
434          * @param bool   $install    Is this the initial update during the installation?
435          * @param array  $tables     An array of the database tables
436          * @param array  $definition An array of the definition tables
437          * @return string Empty string if the update is successful, error messages otherwise
438          * @throws Exception
439          */
440         private static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
441         {
442                 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
443
444                 if ($action && !$install && self::isUpdating()) {
445                         return DI::l10n()->t('Another database update is currently running.');
446                 }
447
448                 if ($in_maintenance_mode) {
449                         DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
450                 }
451
452                 // ensure that all initial values exist. This test has to be done prior and after the structure check.
453                 // Prior is needed if the specific tables already exists - after is needed when they had been created.
454                 self::checkInitialValues();
455
456                 $errors = '';
457
458                 Logger::info('updating structure');
459
460                 // Get the current structure
461                 $database = [];
462
463                 if (is_null($tables)) {
464                         $tables = DBA::toArray(DBA::p("SHOW TABLES"));
465                 }
466
467                 if (DBA::isResult($tables)) {
468                         foreach ($tables AS $table) {
469                                 $table = current($table);
470
471                                 Logger::info('updating structure', ['table' => $table]);
472                                 $database[$table] = self::tableStructure($table);
473                         }
474                 }
475
476                 // Get the definition
477                 if (is_null($definition)) {
478                         $definition = self::definition($basePath);
479                 }
480
481                 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
482                 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
483                         !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
484                         $ignore = '';
485                 } else {
486                         $ignore = ' IGNORE';
487                 }
488
489                 // Compare it
490                 foreach ($definition AS $name => $structure) {
491                         $is_new_table = false;
492                         $group_by = "";
493                         $sql3 = "";
494                         $is_unique = false;
495                         $temp_name = $name;
496                         if (!isset($database[$name])) {
497                                 $r = self::createTable($name, $structure, $verbose, $action);
498                                 if (!DBA::isResult($r)) {
499                                         $errors .= self::printUpdateError($name);
500                                 }
501                                 $is_new_table = true;
502                         } else {
503                                 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
504                                         if (isset($database[$name]["indexes"][$indexname])) {
505                                                 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
506                                         } else {
507                                                 $current_index_definition = "__NOT_SET__";
508                                         }
509                                         $new_index_definition = implode(",", $fieldnames);
510                                         if ($current_index_definition != $new_index_definition) {
511                                                 if ($fieldnames[0] == "UNIQUE") {
512                                                         $is_unique = true;
513                                                         if ($ignore == "") {
514                                                                 $temp_name = "temp-" . $name;
515                                                         }
516                                                 }
517                                         }
518                                 }
519
520                                 /*
521                                  * Drop the index if it isn't present in the definition
522                                  * or the definition differ from current status
523                                  * and index name doesn't start with "local_"
524                                  */
525                                 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
526                                         $current_index_definition = implode(",", $fieldnames);
527                                         if (isset($structure["indexes"][$indexname])) {
528                                                 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
529                                         } else {
530                                                 $new_index_definition = "__NOT_SET__";
531                                         }
532                                         if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
533                                                 $sql2 = self::dropIndex($indexname);
534                                                 if ($sql3 == "") {
535                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
536                                                 } else {
537                                                         $sql3 .= ", " . $sql2;
538                                                 }
539                                         }
540                                 }
541                                 // Compare the field structure field by field
542                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
543                                         if (!isset($database[$name]["fields"][$fieldname])) {
544                                                 $sql2 = self::addTableField($fieldname, $parameters);
545                                                 if ($sql3 == "") {
546                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
547                                                 } else {
548                                                         $sql3 .= ", " . $sql2;
549                                                 }
550                                         } else {
551                                                 // Compare the field definition
552                                                 $field_definition = $database[$name]["fields"][$fieldname];
553
554                                                 // Remove the relation data that is used for the referential integrity
555                                                 unset($parameters['relation']);
556                                                 unset($parameters['foreign']);
557
558                                                 // We change the collation after the indexes had been changed.
559                                                 // This is done to avoid index length problems.
560                                                 // So here we always ensure that there is no need to change it.
561                                                 unset($parameters['Collation']);
562                                                 unset($field_definition['Collation']);
563
564                                                 // Only update the comment when it is defined
565                                                 if (!isset($parameters['comment'])) {
566                                                         $parameters['comment'] = "";
567                                                 }
568
569                                                 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
570                                                 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
571                                                 if ($current_field_definition != $new_field_definition) {
572                                                         $sql2 = self::modifyTableField($fieldname, $parameters);
573                                                         if ($sql3 == "") {
574                                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
575                                                         } else {
576                                                                 $sql3 .= ", " . $sql2;
577                                                         }
578                                                 }
579                                         }
580                                 }
581                         }
582
583                         /*
584                          * Create the index if the index don't exists in database
585                          * or the definition differ from the current status.
586                          * Don't create keys if table is new
587                          */
588                         if (!$is_new_table) {
589                                 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
590                                         if (isset($database[$name]["indexes"][$indexname])) {
591                                                 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
592                                         } else {
593                                                 $current_index_definition = "__NOT_SET__";
594                                         }
595                                         $new_index_definition = implode(",", $fieldnames);
596                                         if ($current_index_definition != $new_index_definition) {
597                                                 $sql2 = self::createIndex($indexname, $fieldnames);
598
599                                                 // Fetch the "group by" fields for unique indexes
600                                                 $group_by = self::groupBy($fieldnames);
601                                                 if ($sql2 != "") {
602                                                         if ($sql3 == "") {
603                                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
604                                                         } else {
605                                                                 $sql3 .= ", " . $sql2;
606                                                         }
607                                                 }
608                                         }
609                                 }
610
611                                 $existing_foreign_keys = $database[$name]['foreign_keys'];
612
613                                 // Foreign keys
614                                 // Compare the field structure field by field
615                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
616                                         if (empty($parameters['foreign'])) {
617                                                 continue;
618                                         }
619
620                                         $constraint = self::getConstraintName($name, $fieldname, $parameters);
621
622                                         unset($existing_foreign_keys[$constraint]);
623
624                                         if (empty($database[$name]['foreign_keys'][$constraint])) {
625                                                 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
626
627                                                 if ($sql3 == "") {
628                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
629                                                 } else {
630                                                         $sql3 .= ", " . $sql2;
631                                                 }
632                                         }
633                                 }
634
635                                 foreach ($existing_foreign_keys as $param) {
636                                         $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
637
638                                         if ($sql3 == "") {
639                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
640                                         } else {
641                                                 $sql3 .= ", " . $sql2;
642                                         }
643                                 }
644
645                                 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
646                                         $structurecomment = $structure["comment"] ?? '';
647                                         if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
648                                                 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
649
650                                                 if ($sql3 == "") {
651                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
652                                                 } else {
653                                                         $sql3 .= ", " . $sql2;
654                                                 }
655                                         }
656                                 }
657
658                                 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
659                                         if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
660                                                 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
661
662                                                 if ($sql3 == "") {
663                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
664                                                 } else {
665                                                         $sql3 .= ", " . $sql2;
666                                                 }
667                                         }
668                                 }
669
670                                 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
671                                         if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
672                                                 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
673
674                                                 if ($sql3 == "") {
675                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
676                                                 } else {
677                                                         $sql3 .= ", " . $sql2;
678                                                 }
679                                         }
680                                 }
681
682                                 if ($sql3 != "") {
683                                         $sql3 .= "; ";
684                                 }
685
686                                 // Now have a look at the field collations
687                                 // Compare the field structure field by field
688                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
689                                         // Compare the field definition
690                                         $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
691
692                                         // Define the default collation if not given
693                                         if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
694                                                 $parameters['Collation'] = 'utf8mb4_general_ci';
695                                         } else {
696                                                 $parameters['Collation'] = null;
697                                         }
698
699                                         if ($field_definition['Collation'] != $parameters['Collation']) {
700                                                 $sql2 = self::modifyTableField($fieldname, $parameters);
701                                                 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
702                                                         $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
703                                                 } else {
704                                                         $sql3 .= ", " . $sql2;
705                                                 }
706                                         }
707                                 }
708                         }
709
710                         if ($sql3 != "") {
711                                 if (substr($sql3, -2, 2) != "; ") {
712                                         $sql3 .= ";";
713                                 }
714
715                                 $field_list = '';
716                                 if ($is_unique && $ignore == '') {
717                                         foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
718                                                 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
719                                         }
720                                         $field_list = rtrim($field_list, ',');
721                                 }
722
723                                 if ($verbose) {
724                                         // Ensure index conversion to unique removes duplicates
725                                         if ($is_unique && ($temp_name != $name)) {
726                                                 if ($ignore != "") {
727                                                         echo "SET session old_alter_table=1;\n";
728                                                 } else {
729                                                         echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
730                                                         echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
731                                                 }
732                                         }
733
734                                         echo $sql3 . "\n";
735
736                                         if ($is_unique && ($temp_name != $name)) {
737                                                 if ($ignore != "") {
738                                                         echo "SET session old_alter_table=0;\n";
739                                                 } else {
740                                                         echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
741                                                         echo "DROP TABLE `" . $name . "`;\n";
742                                                         echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
743                                                 }
744                                         }
745                                 }
746
747                                 if ($action) {
748                                         if ($in_maintenance_mode) {
749                                                 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
750                                         }
751
752                                         // Ensure index conversion to unique removes duplicates
753                                         if ($is_unique && ($temp_name != $name)) {
754                                                 if ($ignore != "") {
755                                                         DBA::e("SET session old_alter_table=1;");
756                                                 } else {
757                                                         $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
758                                                         if (!DBA::isResult($r)) {
759                                                                 $errors .= self::printUpdateError($sql3);
760                                                                 return $errors;
761                                                         }
762
763                                                         $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
764                                                         if (!DBA::isResult($r)) {
765                                                                 $errors .= self::printUpdateError($sql3);
766                                                                 return $errors;
767                                                         }
768                                                 }
769                                         }
770
771                                         $r = DBA::e($sql3);
772                                         if (!DBA::isResult($r)) {
773                                                 $errors .= self::printUpdateError($sql3);
774                                         }
775                                         if ($is_unique && ($temp_name != $name)) {
776                                                 if ($ignore != "") {
777                                                         DBA::e("SET session old_alter_table=0;");
778                                                 } else {
779                                                         $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
780                                                         if (!DBA::isResult($r)) {
781                                                                 $errors .= self::printUpdateError($sql3);
782                                                                 return $errors;
783                                                         }
784                                                         $r = DBA::e("DROP TABLE `" . $name . "`;");
785                                                         if (!DBA::isResult($r)) {
786                                                                 $errors .= self::printUpdateError($sql3);
787                                                                 return $errors;
788                                                         }
789                                                         $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
790                                                         if (!DBA::isResult($r)) {
791                                                                 $errors .= self::printUpdateError($sql3);
792                                                                 return $errors;
793                                                         }
794                                                 }
795                                         }
796                                 }
797                         }
798                 }
799
800                 View::create(false, $action);
801
802                 self::checkInitialValues();
803
804                 if ($action && !$install) {
805                         if ($errors) {
806                                 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
807                         } else {
808                                 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
809                         }
810                 }
811
812                 return $errors;
813         }
814
815         private static function tableStructure($table)
816         {
817                 // This query doesn't seem to be executable as a prepared statement
818                 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
819
820                 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
821                         ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
822                         'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
823                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
824                         DBA::databaseName(), $table]);
825
826                 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
827                         ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
828                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
829                         DBA::databaseName(), $table]);
830
831                 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
832                         ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
833                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
834                         DBA::databaseName(), $table]);
835
836                 $fielddata = [];
837                 $indexdata = [];
838                 $foreigndata = [];
839
840                 if (DBA::isResult($foreign_keys)) {
841                         foreach ($foreign_keys as $foreign_key) {
842                                 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
843                                 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
844                                 $foreigndata[$constraint] = $foreign_key;
845                         }
846                 }
847
848                 if (DBA::isResult($indexes)) {
849                         foreach ($indexes AS $index) {
850                                 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
851                                         $indexdata[$index["Key_name"]] = ["UNIQUE"];
852                                 }
853
854                                 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
855                                         $indexdata[$index["Key_name"]] = ["FULLTEXT"];
856                                 }
857
858                                 $column = $index["Column_name"];
859
860                                 if ($index["Sub_part"] != "") {
861                                         $column .= "(" . $index["Sub_part"] . ")";
862                                 }
863
864                                 $indexdata[$index["Key_name"]][] = $column;
865                         }
866                 }
867
868                 $fielddata = [];
869                 if (DBA::isResult($fields)) {
870                         foreach ($fields AS $field) {
871                                 $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)'];
872                                 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
873                                 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
874
875                                 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
876
877                                 if ($field['IS_NULLABLE'] == 'NO') {
878                                         $fielddata[$field['COLUMN_NAME']]['not null'] = true;
879                                 }
880
881                                 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
882                                         $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
883                                 }
884
885                                 if (!empty($field['EXTRA'])) {
886                                         $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
887                                 }
888
889                                 if ($field['COLUMN_KEY'] == 'PRI') {
890                                         $fielddata[$field['COLUMN_NAME']]['primary'] = true;
891                                 }
892
893                                 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
894                                 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
895                         }
896                 }
897
898                 return ["fields" => $fielddata, "indexes" => $indexdata,
899                         "foreign_keys" => $foreigndata, "table_status" => $table_status];
900         }
901
902         private static function dropIndex($indexname)
903         {
904                 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
905                 return ($sql);
906         }
907
908         private static function addTableField($fieldname, $parameters)
909         {
910                 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
911                 return ($sql);
912         }
913
914         private static function modifyTableField($fieldname, $parameters)
915         {
916                 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
917                 return ($sql);
918         }
919
920         private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
921         {
922                 $foreign_table = array_keys($parameters['foreign'])[0];
923                 $foreign_field = array_values($parameters['foreign'])[0];
924
925                 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
926         }
927
928         private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
929                 $foreign_table = array_keys($parameters['foreign'])[0];
930                 $foreign_field = array_values($parameters['foreign'])[0];
931
932                 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
933
934                 if (!empty($parameters['foreign']['on update'])) {
935                         $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
936                 } else {
937                         $sql .= " ON UPDATE RESTRICT";
938                 }
939
940                 if (!empty($parameters['foreign']['on delete'])) {
941                         $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
942                 } else {
943                         $sql .= " ON DELETE CASCADE";
944                 }
945
946                 return $sql;
947         }
948
949         private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
950         {
951                 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
952         }
953
954         private static function dropForeignKey(string $constraint)
955         {
956                 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
957         }
958
959         /**
960          * Constructs a GROUP BY clause from a UNIQUE index definition.
961          *
962          * @param array $fieldnames
963          * @return string
964          */
965         private static function groupBy(array $fieldnames)
966         {
967                 if ($fieldnames[0] != "UNIQUE") {
968                         return "";
969                 }
970
971                 array_shift($fieldnames);
972
973                 $names = "";
974                 foreach ($fieldnames AS $fieldname) {
975                         if ($names != "") {
976                                 $names .= ",";
977                         }
978
979                         if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
980                                 $names .= "`" . DBA::escape($matches[1]) . "`";
981                         } else {
982                                 $names .= "`" . DBA::escape($fieldname) . "`";
983                         }
984                 }
985
986                 $sql = sprintf(" GROUP BY %s", $names);
987                 return $sql;
988         }
989
990         /**
991          * Renames columns or the primary key of a table
992          *
993          * @todo You cannot rename a primary key if "auto increment" is set
994          *
995          * @param string $table            Table name
996          * @param array  $columns          Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
997          *                                 Syntax for Primary Key: [ $col1, $col2, ...]
998          * @param int    $type             The type of renaming (Default is Column)
999          *
1000          * @return boolean Was the renaming successful?
1001          * @throws Exception
1002          */
1003         public static function rename($table, $columns, $type = self::RENAME_COLUMN)
1004         {
1005                 if (empty($table) || empty($columns)) {
1006                         return false;
1007                 }
1008
1009                 if (!is_array($columns)) {
1010                         return false;
1011                 }
1012
1013                 $table = DBA::escape($table);
1014
1015                 $sql = "ALTER TABLE `" . $table . "`";
1016                 switch ($type) {
1017                         case self::RENAME_COLUMN:
1018                                 if (!self::existsColumn($table, array_keys($columns))) {
1019                                         return false;
1020                                 }
1021                                 $sql .= implode(',', array_map(
1022                                         function ($to, $from) {
1023                                                 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1024                                         },
1025                                         $columns,
1026                                         array_keys($columns)
1027                                 ));
1028                                 break;
1029                         case self::RENAME_PRIMARY_KEY:
1030                                 if (!self::existsColumn($table, $columns)) {
1031                                         return false;
1032                                 }
1033                                 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1034                                 break;
1035                         default:
1036                                 return false;
1037                 }
1038
1039                 $sql .= ";";
1040
1041                 $stmt = DBA::p($sql);
1042
1043                 if (is_bool($stmt)) {
1044                         $retval = $stmt;
1045                 } else {
1046                         $retval = true;
1047                 }
1048
1049                 DBA::close($stmt);
1050
1051                 return $retval;
1052         }
1053
1054         /**
1055          *    Check if the columns of the table exists
1056          *
1057          * @param string $table   Table name
1058          * @param array  $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1059          *
1060          * @return boolean Does the table exist?
1061          * @throws Exception
1062          */
1063         public static function existsColumn($table, $columns = [])
1064         {
1065                 if (empty($table)) {
1066                         return false;
1067                 }
1068
1069                 if (is_null($columns) || empty($columns)) {
1070                         return self::existsTable($table);
1071                 }
1072
1073                 $table = DBA::escape($table);
1074
1075                 foreach ($columns AS $column) {
1076                         $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1077
1078                         $stmt = DBA::p($sql);
1079
1080                         if (is_bool($stmt)) {
1081                                 $retval = $stmt;
1082                         } else {
1083                                 $retval = (DBA::numRows($stmt) > 0);
1084                         }
1085
1086                         DBA::close($stmt);
1087
1088                         if (!$retval) {
1089                                 return false;
1090                         }
1091                 }
1092
1093                 return true;
1094         }
1095
1096         /**
1097          * Check if a foreign key exists for the given table field
1098          *
1099          * @param string $table
1100          * @param string $field
1101          * @return boolean
1102          */
1103         public static function existsForeignKeyForField(string $table, string $field)
1104         {
1105                 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1106                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1107                         DBA::databaseName(), $table, $field]);
1108         }
1109         /**
1110          *    Check if a table exists
1111          *
1112          * @param string|array $table Table name
1113          *
1114          * @return boolean Does the table exist?
1115          * @throws Exception
1116          */
1117         public static function existsTable($table)
1118         {
1119                 if (empty($table)) {
1120                         return false;
1121                 }
1122
1123                 if (is_array($table)) {
1124                         $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1125                 } else {
1126                         $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1127                 }
1128
1129                 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1130
1131                 return $result;
1132         }
1133
1134         /**
1135          * Returns the columns of a table
1136          *
1137          * @param string $table Table name
1138          *
1139          * @return array An array of the table columns
1140          * @throws Exception
1141          */
1142         public static function getColumns($table)
1143         {
1144                 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1145                 return DBA::toArray($stmtColumns);
1146         }
1147
1148         /**
1149          * Check if initial database values do exist - or create them
1150          */
1151         public static function checkInitialValues(bool $verbose = false)
1152         {
1153                 if (self::existsTable('verb')) {
1154                         if (!DBA::exists('verb', ['id' => 1])) {
1155                                 foreach (Item::ACTIVITIES as $index => $activity) {
1156                                         DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1157                                 }
1158                                 if ($verbose) {
1159                                         echo "verb: activities added\n";
1160                                 }
1161                         } elseif ($verbose) {
1162                                 echo "verb: activities already added\n";
1163                         }
1164
1165                         if (!DBA::exists('verb', ['id' => 0])) {
1166                                 DBA::insert('verb', ['name' => '']);
1167                                 $lastid = DBA::lastInsertId();
1168                                 if ($lastid != 0) {
1169                                         DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1170                                         if ($verbose) {
1171                                                 echo "Zero verb added\n";
1172                                         }
1173                                 }
1174                         } elseif ($verbose) {
1175                                 echo "Zero verb already added\n";
1176                         }
1177                 } elseif ($verbose) {
1178                         echo "verb: Table not found\n";
1179                 }
1180
1181                 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1182                         $user = [
1183                                 "verified" => true,
1184                                 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1185                                 "account-type" => User::ACCOUNT_TYPE_RELAY,
1186                         ];
1187                         DBA::insert('user', $user);
1188                         $lastid = DBA::lastInsertId();
1189                         if ($lastid != 0) {
1190                                 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1191                                 if ($verbose) {
1192                                         echo "Zero user added\n";
1193                                 }
1194                         }
1195                 } elseif (self::existsTable('user') && $verbose) {
1196                         echo "Zero user already added\n";
1197                 } elseif ($verbose) {
1198                         echo "user: Table not found\n";
1199                 }
1200
1201                 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1202                         DBA::insert('contact', ['nurl' => '']);
1203                         $lastid = DBA::lastInsertId();
1204                         if ($lastid != 0) {
1205                                 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1206                                 if ($verbose) {
1207                                         echo "Zero contact added\n";
1208                                 }
1209                         }               
1210                 } elseif (self::existsTable('contact') && $verbose) {
1211                         echo "Zero contact already added\n";
1212                 } elseif ($verbose) {
1213                         echo "contact: Table not found\n";
1214                 }
1215
1216                 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1217                         DBA::insert('tag', ['name' => '']);
1218                         $lastid = DBA::lastInsertId();
1219                         if ($lastid != 0) {
1220                                 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1221                                 if ($verbose) {
1222                                         echo "Zero tag added\n";
1223                                 }
1224                         }
1225                 } elseif (self::existsTable('tag') && $verbose) {
1226                         echo "Zero tag already added\n";
1227                 } elseif ($verbose) {
1228                         echo "tag: Table not found\n";
1229                 }
1230
1231                 if (self::existsTable('permissionset')) {
1232                         if (!DBA::exists('permissionset', ['id' => 0])) {
1233                                 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);       
1234                                 $lastid = DBA::lastInsertId();
1235                                 if ($lastid != 0) {
1236                                         DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1237                                         if ($verbose) {
1238                                                 echo "Zero permissionset added\n";
1239                                         }
1240                                 }
1241                         } elseif ($verbose) {
1242                                 echo "Zero permissionset already added\n";
1243                         }
1244                         if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
1245                                 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1246                                         LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1247                                         WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1248                                 while ($set = DBA::fetch($sets)) {
1249                                         if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1250                                                 $owner = User::getOwnerDataById($set['uid']);
1251                                                 if ($owner) {
1252                                                         $permission = '<' . $owner['id'] . '>';
1253                                                 } else {
1254                                                         $permission = '<>';
1255                                                 }
1256                                         } else {
1257                                                 $permission = '';
1258                                         }
1259                                         $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1260                                                 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1261                                         DBA::insert('permissionset', $fields);
1262                                 }
1263                                 DBA::close($sets);
1264                         }
1265                 } elseif ($verbose) {
1266                         echo "permissionset: Table not found\n";
1267                 }
1268         
1269                 if (!self::existsForeignKeyForField('tokens', 'client_id')) {
1270                         $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1271                                 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1272                                 WHERE `clients`.`client_id` IS NULL");
1273                         while ($token = DBA::fetch($tokens)) {
1274                                 DBA::delete('tokens', ['id' => $token['id']]);
1275                         }
1276                         DBA::close($tokens);
1277                 }
1278         }
1279
1280         /**
1281          * Checks if a database update is currently running
1282          *
1283          * @return boolean
1284          */
1285         private static function isUpdating()
1286         {
1287                 $isUpdate = false;
1288
1289                 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1290                         ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1291
1292                 while ($process = DBA::fetch($processes)) {
1293                         $parts = explode(' ', $process['info']);
1294                         if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1295                                 $isUpdate = true;
1296                         }
1297                 }
1298
1299                 DBA::close($processes);
1300
1301                 return $isUpdate;
1302         }
1303 }