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