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