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