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