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