]> git.mxchange.org Git - friendica.git/blob - src/Database/DBStructure.php
The next boolean
[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                 $errors = '';
298
299                 Logger::log('updating structure', Logger::DEBUG);
300
301                 // Get the current structure
302                 $database = [];
303
304                 if (is_null($tables)) {
305                         $tables = DBA::toArray(DBA::p("SHOW TABLES"));
306                 }
307
308                 if (DBA::isResult($tables)) {
309                         foreach ($tables AS $table) {
310                                 $table = current($table);
311
312                                 Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
313                                 $database[$table] = self::tableStructure($table);
314                         }
315                 }
316
317                 // Get the definition
318                 if (is_null($definition)) {
319                         $definition = self::definition($basePath);
320                 }
321
322                 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
323                 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
324                         !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
325                         $ignore = '';
326                 } else {
327                         $ignore = ' IGNORE';
328                 }
329
330                 // Compare it
331                 foreach ($definition AS $name => $structure) {
332                         $is_new_table = false;
333                         $group_by = "";
334                         $sql3 = "";
335                         $is_unique = false;
336                         $temp_name = $name;
337                         if (!isset($database[$name])) {
338                                 $r = self::createTable($name, $structure, $verbose, $action);
339                                 if (!DBA::isResult($r)) {
340                                         $errors .= self::printUpdateError($name);
341                                 }
342                                 $is_new_table = true;
343                         } else {
344                                 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
345                                         if (isset($database[$name]["indexes"][$indexname])) {
346                                                 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
347                                         } else {
348                                                 $current_index_definition = "__NOT_SET__";
349                                         }
350                                         $new_index_definition = implode(",", $fieldnames);
351                                         if ($current_index_definition != $new_index_definition) {
352                                                 if ($fieldnames[0] == "UNIQUE") {
353                                                         $is_unique = true;
354                                                         if ($ignore == "") {
355                                                                 $temp_name = "temp-" . $name;
356                                                         }
357                                                 }
358                                         }
359                                 }
360
361                                 /*
362                                  * Drop the index if it isn't present in the definition
363                                  * or the definition differ from current status
364                                  * and index name doesn't start with "local_"
365                                  */
366                                 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
367                                         $current_index_definition = implode(",", $fieldnames);
368                                         if (isset($structure["indexes"][$indexname])) {
369                                                 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
370                                         } else {
371                                                 $new_index_definition = "__NOT_SET__";
372                                         }
373                                         if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
374                                                 $sql2 = self::dropIndex($indexname);
375                                                 if ($sql3 == "") {
376                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
377                                                 } else {
378                                                         $sql3 .= ", " . $sql2;
379                                                 }
380                                         }
381                                 }
382                                 // Compare the field structure field by field
383                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
384                                         if (!isset($database[$name]["fields"][$fieldname])) {
385                                                 $sql2 = self::addTableField($fieldname, $parameters);
386                                                 if ($sql3 == "") {
387                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
388                                                 } else {
389                                                         $sql3 .= ", " . $sql2;
390                                                 }
391                                         } else {
392                                                 // Compare the field definition
393                                                 $field_definition = $database[$name]["fields"][$fieldname];
394
395                                                 // Remove the relation data that is used for the referential integrity
396                                                 unset($parameters['relation']);
397                                                 unset($parameters['foreign']);
398
399                                                 // We change the collation after the indexes had been changed.
400                                                 // This is done to avoid index length problems.
401                                                 // So here we always ensure that there is no need to change it.
402                                                 unset($parameters['Collation']);
403                                                 unset($field_definition['Collation']);
404
405                                                 // Only update the comment when it is defined
406                                                 if (!isset($parameters['comment'])) {
407                                                         $parameters['comment'] = "";
408                                                 }
409
410                                                 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
411                                                 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
412                                                 if ($current_field_definition != $new_field_definition) {
413                                                         $sql2 = self::modifyTableField($fieldname, $parameters);
414                                                         if ($sql3 == "") {
415                                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
416                                                         } else {
417                                                                 $sql3 .= ", " . $sql2;
418                                                         }
419                                                 }
420                                         }
421                                 }
422                         }
423
424                         /*
425                          * Create the index if the index don't exists in database
426                          * or the definition differ from the current status.
427                          * Don't create keys if table is new
428                          */
429                         if (!$is_new_table) {
430                                 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
431                                         if (isset($database[$name]["indexes"][$indexname])) {
432                                                 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
433                                         } else {
434                                                 $current_index_definition = "__NOT_SET__";
435                                         }
436                                         $new_index_definition = implode(",", $fieldnames);
437                                         if ($current_index_definition != $new_index_definition) {
438                                                 $sql2 = self::createIndex($indexname, $fieldnames);
439
440                                                 // Fetch the "group by" fields for unique indexes
441                                                 $group_by = self::groupBy($fieldnames);
442                                                 if ($sql2 != "") {
443                                                         if ($sql3 == "") {
444                                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
445                                                         } else {
446                                                                 $sql3 .= ", " . $sql2;
447                                                         }
448                                                 }
449                                         }
450                                 }
451
452                                 $existing_foreign_keys = $database[$name]['foreign_keys'];
453
454                                 // Foreign keys
455                                 // Compare the field structure field by field
456                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
457                                         if (empty($parameters['foreign'])) {
458                                                 continue;
459                                         }
460
461                                         $constraint = self::getConstraintName($name, $fieldname, $parameters);
462
463                                         unset($existing_foreign_keys[$constraint]);
464
465                                         if (empty($database[$name]['foreign_keys'][$constraint])) {
466                                                 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
467
468                                                 if ($sql3 == "") {
469                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
470                                                 } else {
471                                                         $sql3 .= ", " . $sql2;
472                                                 }
473                                         }
474                                 }
475
476                                 foreach ($existing_foreign_keys as $constraint => $param) {
477                                         $sql2 = self::dropForeignKey($constraint);
478
479                                         if ($sql3 == "") {
480                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
481                                         } else {
482                                                 $sql3 .= ", " . $sql2;
483                                         }
484                                 }
485
486                                 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
487                                         $structurecomment = $structure["comment"] ?? '';
488                                         if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
489                                                 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
490
491                                                 if ($sql3 == "") {
492                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
493                                                 } else {
494                                                         $sql3 .= ", " . $sql2;
495                                                 }
496                                         }
497                                 }
498
499                                 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
500                                         if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
501                                                 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
502
503                                                 if ($sql3 == "") {
504                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
505                                                 } else {
506                                                         $sql3 .= ", " . $sql2;
507                                                 }
508                                         }
509                                 }
510
511                                 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
512                                         if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
513                                                 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
514
515                                                 if ($sql3 == "") {
516                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
517                                                 } else {
518                                                         $sql3 .= ", " . $sql2;
519                                                 }
520                                         }
521                                 }
522
523                                 if ($sql3 != "") {
524                                         $sql3 .= "; ";
525                                 }
526
527                                 // Now have a look at the field collations
528                                 // Compare the field structure field by field
529                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
530                                         // Compare the field definition
531                                         $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
532
533                                         // Define the default collation if not given
534                                         if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
535                                                 $parameters['Collation'] = 'utf8mb4_general_ci';
536                                         } else {
537                                                 $parameters['Collation'] = null;
538                                         }
539
540                                         if ($field_definition['Collation'] != $parameters['Collation']) {
541                                                 $sql2 = self::modifyTableField($fieldname, $parameters);
542                                                 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
543                                                         $sql3 .= "ALTER" . $ignore . " TABLE `" . $temp_name . "` " . $sql2;
544                                                 } else {
545                                                         $sql3 .= ", " . $sql2;
546                                                 }
547                                         }
548                                 }
549                         }
550
551                         if ($sql3 != "") {
552                                 if (substr($sql3, -2, 2) != "; ") {
553                                         $sql3 .= ";";
554                                 }
555
556                                 $field_list = '';
557                                 if ($is_unique && $ignore == '') {
558                                         foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
559                                                 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
560                                         }
561                                         $field_list = rtrim($field_list, ',');
562                                 }
563
564                                 if ($verbose) {
565                                         // Ensure index conversion to unique removes duplicates
566                                         if ($is_unique && ($temp_name != $name)) {
567                                                 if ($ignore != "") {
568                                                         echo "SET session old_alter_table=1;\n";
569                                                 } else {
570                                                         echo "DROP TABLE IF EXISTS `" . $temp_name . "`;\n";
571                                                         echo "CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;\n";
572                                                 }
573                                         }
574
575                                         echo $sql3 . "\n";
576
577                                         if ($is_unique && ($temp_name != $name)) {
578                                                 if ($ignore != "") {
579                                                         echo "SET session old_alter_table=0;\n";
580                                                 } else {
581                                                         echo "INSERT INTO `" . $temp_name . "` SELECT " . DBA::anyValueFallback($field_list) . " FROM `" . $name . "`" . $group_by . ";\n";
582                                                         echo "DROP TABLE `" . $name . "`;\n";
583                                                         echo "RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;\n";
584                                                 }
585                                         }
586                                 }
587
588                                 if ($action) {
589                                         if (!$install) {
590                                                 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
591                                         }
592
593                                         // Ensure index conversion to unique removes duplicates
594                                         if ($is_unique && ($temp_name != $name)) {
595                                                 if ($ignore != "") {
596                                                         DBA::e("SET session old_alter_table=1;");
597                                                 } else {
598                                                         $r = DBA::e("DROP TABLE IF EXISTS `" . $temp_name . "`;");
599                                                         if (!DBA::isResult($r)) {
600                                                                 $errors .= self::printUpdateError($sql3);
601                                                                 return $errors;
602                                                         }
603
604                                                         $r = DBA::e("CREATE TABLE `" . $temp_name . "` LIKE `" . $name . "`;");
605                                                         if (!DBA::isResult($r)) {
606                                                                 $errors .= self::printUpdateError($sql3);
607                                                                 return $errors;
608                                                         }
609                                                 }
610                                         }
611
612                                         $r = DBA::e($sql3);
613                                         if (!DBA::isResult($r)) {
614                                                 $errors .= self::printUpdateError($sql3);
615                                         }
616                                         if ($is_unique && ($temp_name != $name)) {
617                                                 if ($ignore != "") {
618                                                         DBA::e("SET session old_alter_table=0;");
619                                                 } else {
620                                                         $r = DBA::e("INSERT INTO `" . $temp_name . "` SELECT " . $field_list . " FROM `" . $name . "`" . $group_by . ";");
621                                                         if (!DBA::isResult($r)) {
622                                                                 $errors .= self::printUpdateError($sql3);
623                                                                 return $errors;
624                                                         }
625                                                         $r = DBA::e("DROP TABLE `" . $name . "`;");
626                                                         if (!DBA::isResult($r)) {
627                                                                 $errors .= self::printUpdateError($sql3);
628                                                                 return $errors;
629                                                         }
630                                                         $r = DBA::e("RENAME TABLE `" . $temp_name . "` TO `" . $name . "`;");
631                                                         if (!DBA::isResult($r)) {
632                                                                 $errors .= self::printUpdateError($sql3);
633                                                                 return $errors;
634                                                         }
635                                                 }
636                                         }
637                                 }
638                         }
639                 }
640
641                 View::create(false, $action);
642
643                 if ($action && !$install) {
644                         DI::config()->set('system', 'maintenance', 0);
645                         DI::config()->set('system', 'maintenance_reason', '');
646
647                         if ($errors) {
648                                 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
649                         } else {
650                                 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
651                         }
652                 }
653
654                 return $errors;
655         }
656
657         private static function tableStructure($table)
658         {
659                 // This query doesn't seem to be executable as a prepared statement
660                 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
661
662                 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
663                         ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
664                         'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
665                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
666                         DBA::databaseName(), $table]);
667
668                 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
669                         ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
670                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
671                         DBA::databaseName(), $table]);
672
673                 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
674                         ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
675                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
676                         DBA::databaseName(), $table]);
677
678                 $fielddata = [];
679                 $indexdata = [];
680                 $foreigndata = [];
681
682                 if (DBA::isResult($foreign_keys)) {
683                         foreach ($foreign_keys as $foreign_key) {
684                                 $constraint = $foreign_key['CONSTRAINT_NAME'];
685                                 unset($foreign_key['CONSTRAINT_NAME']); 
686                                 $foreigndata[$constraint] = $foreign_key;
687                         }
688                 }
689
690                 if (DBA::isResult($indexes)) {
691                         foreach ($indexes AS $index) {
692                                 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
693                                         $indexdata[$index["Key_name"]] = ["UNIQUE"];
694                                 }
695
696                                 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
697                                         $indexdata[$index["Key_name"]] = ["FULLTEXT"];
698                                 }
699
700                                 $column = $index["Column_name"];
701
702                                 if ($index["Sub_part"] != "") {
703                                         $column .= "(" . $index["Sub_part"] . ")";
704                                 }
705
706                                 $indexdata[$index["Key_name"]][] = $column;
707                         }
708                 }
709
710                 $fielddata = [];
711                 if (DBA::isResult($fields)) {
712                         foreach ($fields AS $field) {
713                                 $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)'];
714                                 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
715                                 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
716
717                                 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
718
719                                 if ($field['IS_NULLABLE'] == 'NO') {
720                                         $fielddata[$field['COLUMN_NAME']]['not null'] = true;
721                                 }
722
723                                 if (isset($field['COLUMN_DEFAULT'])) {
724                                         $fielddata[$field['COLUMN_NAME']]['default'] = $field['COLUMN_DEFAULT'];
725                                 }
726
727                                 if (!empty($field['EXTRA'])) {
728                                         $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
729                                 }
730
731                                 if ($field['COLUMN_KEY'] == 'PRI') {
732                                         $fielddata[$field['COLUMN_NAME']]['primary'] = true;
733                                 }
734
735                                 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
736                                 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
737                         }
738                 }
739
740                 return ["fields" => $fielddata, "indexes" => $indexdata,
741                         "foreign_keys" => $foreigndata, "table_status" => $table_status];
742         }
743
744         private static function dropIndex($indexname)
745         {
746                 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
747                 return ($sql);
748         }
749
750         private static function addTableField($fieldname, $parameters)
751         {
752                 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
753                 return ($sql);
754         }
755
756         private static function modifyTableField($fieldname, $parameters)
757         {
758                 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
759                 return ($sql);
760         }
761
762         private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
763         {
764                 $foreign_table = array_keys($parameters['foreign'])[0];
765                 $foreign_field = array_values($parameters['foreign'])[0];
766
767                 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
768         }
769
770         private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
771                 $foreign_table = array_keys($parameters['foreign'])[0];
772                 $foreign_field = array_values($parameters['foreign'])[0];
773
774                 $constraint = self::getConstraintName($tablename, $fieldname, $parameters);
775
776                 $sql = "CONSTRAINT `" . $constraint . "` FOREIGN KEY (`" . $fieldname . "`)" .
777                         " REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
778
779                 if (!empty($parameters['foreign']['on update'])) {
780                         $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
781                 } else {
782                         $sql .= " ON UPDATE RESTRICT";
783                 }
784
785                 if (!empty($parameters['foreign']['on delete'])) {
786                         $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
787                 } else {
788                         $sql .= " ON DELETE CASCADE";
789                 }
790
791                 return $sql;
792         }
793
794         private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
795         {
796                 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
797         }
798
799         private static function dropForeignKey(string $constraint)
800         {
801                 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
802         }
803
804         /**
805          * Constructs a GROUP BY clause from a UNIQUE index definition.
806          *
807          * @param array $fieldnames
808          * @return string
809          */
810         private static function groupBy(array $fieldnames)
811         {
812                 if ($fieldnames[0] != "UNIQUE") {
813                         return "";
814                 }
815
816                 array_shift($fieldnames);
817
818                 $names = "";
819                 foreach ($fieldnames AS $fieldname) {
820                         if ($names != "") {
821                                 $names .= ",";
822                         }
823
824                         if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
825                                 $names .= "`" . DBA::escape($matches[1]) . "`";
826                         } else {
827                                 $names .= "`" . DBA::escape($fieldname) . "`";
828                         }
829                 }
830
831                 $sql = sprintf(" GROUP BY %s", $names);
832                 return $sql;
833         }
834
835         /**
836          * Renames columns or the primary key of a table
837          *
838          * @todo You cannot rename a primary key if "auto increment" is set
839          *
840          * @param string $table            Table name
841          * @param array  $columns          Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
842          *                                 Syntax for Primary Key: [ $col1, $col2, ...]
843          * @param int    $type             The type of renaming (Default is Column)
844          *
845          * @return boolean Was the renaming successful?
846          * @throws Exception
847          */
848         public static function rename($table, $columns, $type = self::RENAME_COLUMN)
849         {
850                 if (empty($table) || empty($columns)) {
851                         return false;
852                 }
853
854                 if (!is_array($columns)) {
855                         return false;
856                 }
857
858                 $table = DBA::escape($table);
859
860                 $sql = "ALTER TABLE `" . $table . "`";
861                 switch ($type) {
862                         case self::RENAME_COLUMN:
863                                 if (!self::existsColumn($table, array_keys($columns))) {
864                                         return false;
865                                 }
866                                 $sql .= implode(',', array_map(
867                                         function ($to, $from) {
868                                                 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
869                                         },
870                                         $columns,
871                                         array_keys($columns)
872                                 ));
873                                 break;
874                         case self::RENAME_PRIMARY_KEY:
875                                 if (!self::existsColumn($table, $columns)) {
876                                         return false;
877                                 }
878                                 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
879                                 break;
880                         default:
881                                 return false;
882                 }
883
884                 $sql .= ";";
885
886                 $stmt = DBA::p($sql);
887
888                 if (is_bool($stmt)) {
889                         $retval = $stmt;
890                 } else {
891                         $retval = true;
892                 }
893
894                 DBA::close($stmt);
895
896                 return $retval;
897         }
898
899         /**
900          *    Check if the columns of the table exists
901          *
902          * @param string $table   Table name
903          * @param array  $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
904          *
905          * @return boolean Does the table exist?
906          * @throws Exception
907          */
908         public static function existsColumn($table, $columns = [])
909         {
910                 if (empty($table)) {
911                         return false;
912                 }
913
914                 if (is_null($columns) || empty($columns)) {
915                         return self::existsTable($table);
916                 }
917
918                 $table = DBA::escape($table);
919
920                 foreach ($columns AS $column) {
921                         $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
922
923                         $stmt = DBA::p($sql);
924
925                         if (is_bool($stmt)) {
926                                 $retval = $stmt;
927                         } else {
928                                 $retval = (DBA::numRows($stmt) > 0);
929                         }
930
931                         DBA::close($stmt);
932
933                         if (!$retval) {
934                                 return false;
935                         }
936                 }
937
938                 return true;
939         }
940
941         /**
942          *    Check if a table exists
943          *
944          * @param string|array $table Table name
945          *
946          * @return boolean Does the table exist?
947          * @throws Exception
948          */
949         public static function existsTable($table)
950         {
951                 if (empty($table)) {
952                         return false;
953                 }
954
955                 if (is_array($table)) {
956                         $condition = ['table_schema' => key($table), 'table_name' => current($table)];
957                 } else {
958                         $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
959                 }
960
961                 $result = DBA::exists(['information_schema' => 'tables'], $condition);
962
963                 return $result;
964         }
965
966         /**
967          * Returns the columns of a table
968          *
969          * @param string $table Table name
970          *
971          * @return array An array of the table columns
972          * @throws Exception
973          */
974         public static function getColumns($table)
975         {
976                 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
977                 return DBA::toArray($stmtColumns);
978         }
979 }