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