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