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