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