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