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