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