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