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