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