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