]> git.mxchange.org Git - friendica.git/blob - src/Database/DBStructure.php
Merge pull request #12615 from MrPetovan/task/12601-update-gserver-block
[friendica.git] / src / Database / DBStructure.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
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\Logger;
26 use Friendica\DI;
27 use Friendica\Model\Item;
28 use Friendica\Model\User;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\Writer\DbaDefinitionSqlWriter;
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          * Set a database version to trigger update functions
46          *
47          * @param string $version
48          * @return void
49          */
50         public static function setDatabaseVersion(string $version)
51         {
52                 if (!is_numeric($version)) {
53                         throw new \Asika\SimpleConsole\CommandArgsException('The version number must be numeric');
54                 }
55
56                 DI::keyValue()->set('build', $version);
57                 echo DI::l10n()->t('The database version had been set to %s.', $version);
58         }
59
60         /**
61          * Drop unused tables
62          *
63          * @param boolean $execute
64          * @return void
65          */
66         public static function dropTables(bool $execute)
67         {
68                 $postupdate = DI::keyValue()->get('post_update_version') ?? PostUpdate::VERSION;
69                 if ($postupdate < PostUpdate::VERSION) {
70                         echo DI::l10n()->t('The post update is at version %d, it has to be at %d to safely drop the tables.', $postupdate, PostUpdate::VERSION);
71                         return;
72                 }
73
74                 $old_tables = ['fserver', 'gcign', 'gcontact', 'gcontact-relation', 'gfollower' ,'glink', 'item-delivery-data',
75                         'item-activity', 'item-content', 'item_id', 'participation', 'poll', 'poll_result', 'queue', 'retriever_rule',
76                         'deliverq', 'dsprphotoq', 'ffinder', 'sign', 'spam', 'term', 'user-item', 'thread', 'item', 'challenge',
77                         'auth_codes', 'tokens', 'clients', 'profile_check', 'host', 'conversation', 'fcontact', 'config', 'addon'];
78
79                 $tables = DBA::selectToArray('INFORMATION_SCHEMA.TABLES', ['TABLE_NAME'],
80                         ['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_TYPE' => 'BASE TABLE']);
81
82                 if (empty($tables)) {
83                         echo DI::l10n()->t('No unused tables found.');
84                         return;
85                 }
86
87                 if (!$execute) {
88                         echo DI::l10n()->t('These tables are not used for friendica and will be deleted when you execute "dbstructure drop -e":') . "\n\n";
89                 }
90
91                 foreach ($old_tables as $table) {
92                         if (in_array($table, array_column($tables, 'TABLE_NAME'))) {
93                                 if ($execute) {
94                                         $sql = 'DROP TABLE ' . DBA::quoteIdentifier($table) . ';';
95                                         echo $sql . "\n";
96
97                                         $result = DBA::e($sql);
98                                         if (!DBA::isResult($result)) {
99                                                 self::printUpdateError($sql);
100                                         }
101                                 } else {
102                                         echo $table . "\n";
103                                 }
104                         }
105                 }
106         }
107
108         /**
109          * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
110          */
111         public static function convertToInnoDB()
112         {
113                 $tables = DBA::selectToArray(
114                         'information_schema.tables',
115                         ['table_name'],
116                         ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
117                 );
118
119                 $tables = array_merge($tables, DBA::selectToArray(
120                         'information_schema.tables',
121                         ['table_name'],
122                         ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
123                 ));
124
125                 if (!DBA::isResult($tables)) {
126                         echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
127                         return;
128                 }
129
130                 foreach ($tables as $table) {
131                         $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
132                         echo $sql . "\n";
133
134                         $result = DBA::e($sql);
135                         if (!DBA::isResult($result)) {
136                                 self::printUpdateError($sql);
137                         }
138                 }
139         }
140
141         /**
142          * Print out database error messages
143          *
144          * @param string $message Message to be added to the error message
145          *
146          * @return string Error message
147          */
148         private static function printUpdateError(string $message): string
149         {
150                 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
151                         DBA::errorNo(), DBA::errorMessage());
152
153                 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . '<br />';
154         }
155
156         /**
157          * Perform a database structure dryrun (means: just simulating)
158          *
159          * @return string Empty string if the update is successful, error messages otherwise
160          * @throws Exception
161          */
162         public static function dryRun(): string
163         {
164                 return self::update(true, false);
165         }
166
167         /**
168          * Updates DB structure and returns eventual errors messages
169          *
170          * @param bool $enable_maintenance_mode Set the maintenance mode
171          * @param bool $verbose                 Display the SQL commands
172          *
173          * @return string Empty string if the update is successful, error messages otherwise
174          * @throws Exception
175          */
176         public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false): string
177         {
178                 if ($enable_maintenance_mode) {
179                         DI::config()->set('system', 'maintenance', true);
180                 }
181
182                 $status = self::update($verbose, true);
183
184                 if ($enable_maintenance_mode) {
185                         DI::config()->beginTransaction()
186                                                 ->set('system', 'maintenance', false)
187                                                 ->delete('system', 'maintenance_reason')
188                                                 ->commit();
189                 }
190
191                 return $status;
192         }
193
194         /**
195          * Updates DB structure from the installation and returns eventual errors messages
196          *
197          * @return string Empty string if the update is successful, error messages otherwise
198          * @throws Exception
199          */
200         public static function install(): string
201         {
202                 return self::update(false, true, true);
203         }
204
205         /**
206          * Updates DB structure and returns eventual errors messages
207          *
208          * @param bool   $verbose
209          * @param bool   $action     Whether to actually apply the update
210          * @param bool   $install    Is this the initial update during the installation?
211          * @param array  $tables     An array of the database tables
212          * @param array  $definition An array of the definition tables
213          * @return string Empty string if the update is successful, error messages otherwise
214          * @throws Exception
215          */
216         private static function update(bool $verbose, bool $action, bool $install = false, array $tables = null, array $definition = null): string
217         {
218                 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
219
220                 if ($action && !$install && self::isUpdating()) {
221                         return DI::l10n()->t('Another database update is currently running.');
222                 }
223
224                 if ($in_maintenance_mode) {
225                         DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
226                 }
227
228                 // ensure that all initial values exist. This test has to be done prior and after the structure check.
229                 // Prior is needed if the specific tables already exists - after is needed when they had been created.
230                 self::checkInitialValues();
231
232                 $errors = '';
233
234                 Logger::info('updating structure');
235
236                 // Get the current structure
237                 $database = [];
238
239                 if (is_null($tables)) {
240                         $tables = DBA::toArray(DBA::p("SHOW TABLES"));
241                 }
242
243                 if (DBA::isResult($tables)) {
244                         foreach ($tables as $table) {
245                                 $table = current($table);
246
247                                 Logger::info('updating structure', ['table' => $table]);
248                                 $database[$table] = self::tableStructure($table);
249                         }
250                 }
251
252                 // Get the definition
253                 if (is_null($definition)) {
254                         // just for Update purpose, reload the DBA definition with addons to explicit get the whole definition
255                         $definition = DI::dbaDefinition()->load(true)->getAll();
256                 }
257
258                 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
259                 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
260                         !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
261                         $ignore = '';
262                 } else {
263                         $ignore = ' IGNORE';
264                 }
265
266                 // Compare it
267                 foreach ($definition as $name => $structure) {
268                         $is_new_table = false;
269                         $sql3         = "";
270                         if (!isset($database[$name])) {
271                                 $sql = DbaDefinitionSqlWriter::createTable($name, $structure, $verbose, $action);
272                                 if ($verbose) {
273                                         echo $sql;
274                                 }
275                                 if ($action) {
276                                         $r = DBA::e($sql);
277                                         if (!DBA::isResult($r)) {
278                                                 $errors .= self::printUpdateError($name);
279                                         }
280                                 }
281                                 $is_new_table = true;
282                         } else {
283                                 /*
284                                  * Drop the index if it isn't present in the definition
285                                  * or the definition differ from current status
286                                  * and index name doesn't start with "local_"
287                                  */
288                                 foreach ($database[$name]["indexes"] as $indexName => $fieldNames) {
289                                         $current_index_definition = implode(",", $fieldNames);
290                                         if (isset($structure["indexes"][$indexName])) {
291                                                 $new_index_definition = implode(",", $structure["indexes"][$indexName]);
292                                         } else {
293                                                 $new_index_definition = "__NOT_SET__";
294                                         }
295                                         if ($current_index_definition != $new_index_definition && substr($indexName, 0, 6) != 'local_') {
296                                                 $sql2 = DbaDefinitionSqlWriter::dropIndex($indexName);
297                                                 if ($sql3 == "") {
298                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
299                                                 } else {
300                                                         $sql3 .= ", " . $sql2;
301                                                 }
302                                         }
303                                 }
304                                 // Compare the field structure field by field
305                                 foreach ($structure["fields"] as $fieldName => $parameters) {
306                                         if (!isset($database[$name]["fields"][$fieldName])) {
307                                                 $sql2 = DbaDefinitionSqlWriter::addTableField($fieldName, $parameters);
308                                                 if ($sql3 == "") {
309                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
310                                                 } else {
311                                                         $sql3 .= ", " . $sql2;
312                                                 }
313                                         } else {
314                                                 // Compare the field definition
315                                                 $field_definition = $database[$name]["fields"][$fieldName];
316
317                                                 // Remove the relation data that is used for the referential integrity
318                                                 unset($parameters['relation']);
319                                                 unset($parameters['foreign']);
320
321                                                 // We change the collation after the indexes had been changed.
322                                                 // This is done to avoid index length problems.
323                                                 // So here we always ensure that there is no need to change it.
324                                                 unset($parameters['Collation']);
325                                                 unset($field_definition['Collation']);
326
327                                                 // Only update the comment when it is defined
328                                                 if (!isset($parameters['comment'])) {
329                                                         $parameters['comment'] = "";
330                                                 }
331
332                                                 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
333                                                 $new_field_definition     = DBA::cleanQuery(implode(",", $parameters));
334                                                 if ($current_field_definition != $new_field_definition) {
335                                                         $sql2 = DbaDefinitionSqlWriter::modifyTableField($fieldName, $parameters);
336                                                         if ($sql3 == "") {
337                                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
338                                                         } else {
339                                                                 $sql3 .= ", " . $sql2;
340                                                         }
341                                                 }
342                                         }
343                                 }
344                         }
345
346                         /*
347                          * Create the index if the index don't exists in database
348                          * or the definition differ from the current status.
349                          * Don't create keys if table is new
350                          */
351                         if (!$is_new_table) {
352                                 foreach ($structure["indexes"] as $indexName => $fieldNames) {
353                                         if (isset($database[$name]["indexes"][$indexName])) {
354                                                 $current_index_definition = implode(",", $database[$name]["indexes"][$indexName]);
355                                         } else {
356                                                 $current_index_definition = "__NOT_SET__";
357                                         }
358                                         $new_index_definition = implode(",", $fieldNames);
359                                         if ($current_index_definition != $new_index_definition) {
360                                                 $sql2 = DbaDefinitionSqlWriter::createIndex($indexName, $fieldNames);
361
362                                                 if ($sql2 != "") {
363                                                         if ($sql3 == "") {
364                                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
365                                                         } else {
366                                                                 $sql3 .= ", " . $sql2;
367                                                         }
368                                                 }
369                                         }
370                                 }
371
372                                 $existing_foreign_keys = $database[$name]['foreign_keys'];
373
374                                 // Foreign keys
375                                 // Compare the field structure field by field
376                                 foreach ($structure["fields"] as $fieldName => $parameters) {
377                                         if (empty($parameters['foreign'])) {
378                                                 continue;
379                                         }
380
381                                         $constraint = self::getConstraintName($name, $fieldName, $parameters);
382
383                                         unset($existing_foreign_keys[$constraint]);
384
385                                         if (empty($database[$name]['foreign_keys'][$constraint])) {
386                                                 $sql2 = DbaDefinitionSqlWriter::addForeignKey($fieldName, $parameters);
387
388                                                 if ($sql3 == "") {
389                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
390                                                 } else {
391                                                         $sql3 .= ", " . $sql2;
392                                                 }
393                                         }
394                                 }
395
396                                 foreach ($existing_foreign_keys as $param) {
397                                         $sql2 = DbaDefinitionSqlWriter::dropForeignKey($param['CONSTRAINT_NAME']);
398
399                                         if ($sql3 == "") {
400                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
401                                         } else {
402                                                 $sql3 .= ", " . $sql2;
403                                         }
404                                 }
405
406                                 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
407                                         $structurecomment = $structure["comment"] ?? '';
408                                         if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
409                                                 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
410
411                                                 if ($sql3 == "") {
412                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
413                                                 } else {
414                                                         $sql3 .= ", " . $sql2;
415                                                 }
416                                         }
417                                 }
418
419                                 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
420                                         if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
421                                                 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
422
423                                                 if ($sql3 == "") {
424                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
425                                                 } else {
426                                                         $sql3 .= ", " . $sql2;
427                                                 }
428                                         }
429                                 }
430
431                                 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
432                                         if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
433                                                 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
434
435                                                 if ($sql3 == "") {
436                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
437                                                 } else {
438                                                         $sql3 .= ", " . $sql2;
439                                                 }
440                                         }
441                                 }
442
443                                 if ($sql3 != "") {
444                                         $sql3 .= "; ";
445                                 }
446
447                                 // Now have a look at the field collations
448                                 // Compare the field structure field by field
449                                 foreach ($structure["fields"] as $fieldName => $parameters) {
450                                         // Compare the field definition
451                                         $field_definition = ($database[$name]["fields"][$fieldName] ?? '') ?: ['Collation' => ''];
452
453                                         // Define the default collation if not given
454                                         if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
455                                                 $parameters['Collation'] = 'utf8mb4_general_ci';
456                                         } else {
457                                                 $parameters['Collation'] = null;
458                                         }
459
460                                         if ($field_definition['Collation'] != $parameters['Collation']) {
461                                                 $sql2 = DbaDefinitionSqlWriter::modifyTableField($fieldName, $parameters);
462                                                 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
463                                                         $sql3 .= "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
464                                                 } else {
465                                                         $sql3 .= ", " . $sql2;
466                                                 }
467                                         }
468                                 }
469                         }
470
471                         if ($sql3 != "") {
472                                 if (substr($sql3, -2, 2) != "; ") {
473                                         $sql3 .= ";";
474                                 }
475
476                                 if ($verbose) {
477                                         echo $sql3 . "\n";
478                                 }
479
480                                 if ($action) {
481                                         if ($in_maintenance_mode) {
482                                                 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
483                                         }
484
485                                         $r = DBA::e($sql3);
486                                         if (!DBA::isResult($r)) {
487                                                 $errors .= self::printUpdateError($sql3);
488                                         }
489                                 }
490                         }
491                 }
492
493                 View::create(false, $action);
494
495                 self::checkInitialValues();
496
497                 if ($action && !$install) {
498                         if ($errors) {
499                                 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
500                         } else {
501                                 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
502                         }
503                 }
504
505                 return $errors;
506         }
507
508         /**
509          * Returns an array with table structure information
510          *
511          * @param string $table Name of table
512          * @return array Table structure information
513          */
514         private static function tableStructure(string $table): array
515         {
516                 // This query doesn't seem to be executable as a prepared statement
517                 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
518
519                 $fields = DBA::selectToArray('INFORMATION_SCHEMA.COLUMNS',
520                         ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
521                         'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
522                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
523                         DBA::databaseName(), $table]);
524
525                 $foreign_keys = DBA::selectToArray('INFORMATION_SCHEMA.KEY_COLUMN_USAGE',
526                         ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
527                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
528                         DBA::databaseName(), $table]);
529
530                 $table_status = DBA::selectFirst('INFORMATION_SCHEMA.TABLES',
531                         ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
532                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
533                         DBA::databaseName(), $table]);
534
535                 $fielddata = [];
536                 $indexdata = [];
537                 $foreigndata = [];
538
539                 if (DBA::isResult($foreign_keys)) {
540                         foreach ($foreign_keys as $foreign_key) {
541                                 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
542                                 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
543                                 $foreigndata[$constraint] = $foreign_key;
544                         }
545                 }
546
547                 if (DBA::isResult($indexes)) {
548                         foreach ($indexes as $index) {
549                                 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
550                                         $indexdata[$index["Key_name"]] = ["UNIQUE"];
551                                 }
552
553                                 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
554                                         $indexdata[$index["Key_name"]] = ["FULLTEXT"];
555                                 }
556
557                                 $column = $index["Column_name"];
558
559                                 if ($index["Sub_part"] != "") {
560                                         $column .= "(" . $index["Sub_part"] . ")";
561                                 }
562
563                                 $indexdata[$index["Key_name"]][] = $column;
564                         }
565                 }
566
567                 $fielddata = [];
568                 if (DBA::isResult($fields)) {
569                         foreach ($fields as $field) {
570                                 $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)'];
571                                 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
572                                 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
573
574                                 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
575
576                                 if ($field['IS_NULLABLE'] == 'NO') {
577                                         $fielddata[$field['COLUMN_NAME']]['not null'] = true;
578                                 }
579
580                                 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
581                                         $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
582                                 }
583
584                                 if (!empty($field['EXTRA'])) {
585                                         $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
586                                 }
587
588                                 if ($field['COLUMN_KEY'] == 'PRI') {
589                                         $fielddata[$field['COLUMN_NAME']]['primary'] = true;
590                                 }
591
592                                 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
593                                 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
594                         }
595                 }
596
597                 return [
598                         'fields' => $fielddata,
599                         'indexes' => $indexdata,
600                         'foreign_keys' => $foreigndata,
601                         'table_status' => $table_status
602                 ];
603         }
604
605         private static function getConstraintName(string $tableName, string $fieldName, array $parameters): string
606         {
607                 $foreign_table = array_keys($parameters['foreign'])[0];
608                 $foreign_field = array_values($parameters['foreign'])[0];
609
610                 return $tableName . '-' . $fieldName. '-' . $foreign_table. '-' . $foreign_field;
611         }
612
613         /**
614          * Renames columns or the primary key of a table
615          *
616          * @todo You cannot rename a primary key if "auto increment" is set
617          *
618          * @param string $table            Table name
619          * @param array  $columns          Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
620          *                                 Syntax for Primary Key: [ $col1, $col2, ...]
621          * @param int    $type             The type of renaming (Default is Column)
622          *
623          * @return boolean Was the renaming successful?
624          * @throws Exception
625          */
626         public static function rename(string $table, array $columns, int $type = self::RENAME_COLUMN): bool
627         {
628                 if (empty($table) || empty($columns)) {
629                         return false;
630                 }
631
632                 if (!is_array($columns)) {
633                         return false;
634                 }
635
636                 $table = DBA::escape($table);
637
638                 $sql = "ALTER TABLE `" . $table . "`";
639                 switch ($type) {
640                         case self::RENAME_COLUMN:
641                                 if (!self::existsColumn($table, array_keys($columns))) {
642                                         return false;
643                                 }
644                                 $sql .= implode(',', array_map(
645                                         function ($to, $from) {
646                                                 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
647                                         },
648                                         $columns,
649                                         array_keys($columns)
650                                 ));
651                                 break;
652                         case self::RENAME_PRIMARY_KEY:
653                                 if (!self::existsColumn($table, $columns)) {
654                                         return false;
655                                 }
656                                 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
657                                 break;
658                         default:
659                                 return false;
660                 }
661
662                 $sql .= ';';
663
664                 $stmt = DBA::p($sql);
665
666                 if (is_bool($stmt)) {
667                         $retval = $stmt;
668                 } else {
669                         $retval = true;
670                 }
671
672                 DBA::close($stmt);
673
674                 return $retval;
675         }
676
677         /**
678          *    Check if the columns of the table exists
679          *
680          * @param string $table   Table name
681          * @param array  $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
682          *
683          * @return boolean Does the table exist?
684          * @throws Exception
685          */
686         public static function existsColumn(string $table, array $columns = []): bool
687         {
688                 if (empty($table)) {
689                         return false;
690                 }
691
692                 if (is_null($columns) || empty($columns)) {
693                         return self::existsTable($table);
694                 }
695
696                 $table = DBA::escape($table);
697
698                 foreach ($columns as $column) {
699                         $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
700
701                         $stmt = DBA::p($sql);
702
703                         if (is_bool($stmt)) {
704                                 $retval = $stmt;
705                         } else {
706                                 $retval = (DBA::numRows($stmt) > 0);
707                         }
708
709                         DBA::close($stmt);
710
711                         if (!$retval) {
712                                 return false;
713                         }
714                 }
715
716                 return true;
717         }
718
719         /**
720          * Check if a foreign key exists for the given table field
721          *
722          * @param string $table Table name
723          * @param string $field Field name
724          * @return boolean Wether a foreign key exists
725          */
726         public static function existsForeignKeyForField(string $table, string $field): bool
727         {
728                 return DBA::exists('INFORMATION_SCHEMA.KEY_COLUMN_USAGE',
729                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
730                         DBA::databaseName(), $table, $field]);
731         }
732
733         /**
734          * Check if a table exists
735          *
736          * @param string $table Single table name (please loop yourself)
737          * @return boolean Does the table exist?
738          * @throws Exception
739          */
740         public static function existsTable(string $table): bool
741         {
742                 if (empty($table)) {
743                         return false;
744                 }
745
746                 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
747
748                 return DBA::exists('information_schema.tables', $condition);
749         }
750
751         /**
752          * Returns the columns of a table
753          *
754          * @param string $table Table name
755          *
756          * @return array An array of the table columns
757          * @throws Exception
758          */
759         public static function getColumns(string $table): array
760         {
761                 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
762                 return DBA::toArray($stmtColumns);
763         }
764
765         /**
766          * Check if initial database values do exist - or create them
767          *
768          * @param bool $verbose Whether to output messages
769          * @return void
770          */
771         public static function checkInitialValues(bool $verbose = false)
772         {
773                 if (self::existsTable('verb')) {
774                         if (!DBA::exists('verb', ['id' => 1])) {
775                                 foreach (Item::ACTIVITIES as $index => $activity) {
776                                         DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
777                                 }
778                                 if ($verbose) {
779                                         echo "verb: activities added\n";
780                                 }
781                         } elseif ($verbose) {
782                                 echo "verb: activities already added\n";
783                         }
784
785                         if (!DBA::exists('verb', ['id' => 0])) {
786                                 DBA::insert('verb', ['name' => '']);
787                                 $lastid = DBA::lastInsertId();
788                                 if ($lastid != 0) {
789                                         DBA::update('verb', ['id' => 0], ['id' => $lastid]);
790                                         if ($verbose) {
791                                                 echo "Zero verb added\n";
792                                         }
793                                 }
794                         } elseif ($verbose) {
795                                 echo "Zero verb already added\n";
796                         }
797                 } elseif ($verbose) {
798                         echo "verb: Table not found\n";
799                 }
800
801                 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
802                         $user = [
803                                 'verified' => true,
804                                 'page-flags' => User::PAGE_FLAGS_SOAPBOX,
805                                 'account-type' => User::ACCOUNT_TYPE_RELAY,
806                         ];
807                         DBA::insert('user', $user);
808                         $lastid = DBA::lastInsertId();
809                         if ($lastid != 0) {
810                                 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
811                                 if ($verbose) {
812                                         echo "Zero user added\n";
813                                 }
814                         }
815                 } elseif (self::existsTable('user') && $verbose) {
816                         echo "Zero user already added\n";
817                 } elseif ($verbose) {
818                         echo "user: Table not found\n";
819                 }
820
821                 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
822                         DBA::insert('contact', ['nurl' => '']);
823                         $lastid = DBA::lastInsertId();
824                         if ($lastid != 0) {
825                                 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
826                                 if ($verbose) {
827                                         echo "Zero contact added\n";
828                                 }
829                         }
830                 } elseif (self::existsTable('contact') && $verbose) {
831                         echo "Zero contact already added\n";
832                 } elseif ($verbose) {
833                         echo "contact: Table not found\n";
834                 }
835
836                 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
837                         DBA::insert('tag', ['name' => '']);
838                         $lastid = DBA::lastInsertId();
839                         if ($lastid != 0) {
840                                 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
841                                 if ($verbose) {
842                                         echo "Zero tag added\n";
843                                 }
844                         }
845                 } elseif (self::existsTable('tag') && $verbose) {
846                         echo "Zero tag already added\n";
847                 } elseif ($verbose) {
848                         echo "tag: Table not found\n";
849                 }
850
851                 if (self::existsTable('permissionset')) {
852                         if (!DBA::exists('permissionset', ['id' => 0])) {
853                                 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
854                                 $lastid = DBA::lastInsertId();
855                                 if ($lastid != 0) {
856                                         DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
857                                         if ($verbose) {
858                                                 echo "Zero permissionset added\n";
859                                         }
860                                 }
861                         } elseif ($verbose) {
862                                 echo "Zero permissionset already added\n";
863                         }
864                         if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
865                                 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
866                                         LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
867                                         WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
868                                 while ($set = DBA::fetch($sets)) {
869                                         if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
870                                                 $owner = User::getOwnerDataById($set['uid']);
871                                                 if ($owner) {
872                                                         $permission = '<' . $owner['id'] . '>';
873                                                 } else {
874                                                         $permission = '<>';
875                                                 }
876                                         } else {
877                                                 $permission = '';
878                                         }
879                                         $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
880                                                 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
881                                         DBA::insert('permissionset', $fields);
882                                 }
883                                 DBA::close($sets);
884                         }
885                 } elseif ($verbose) {
886                         echo "permissionset: Table not found\n";
887                 }
888
889                 if (self::existsTable('tokens') && self::existsTable('clients') && !self::existsForeignKeyForField('tokens', 'client_id')) {
890                         $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
891                                 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
892                                 WHERE `clients`.`client_id` IS NULL");
893                         while ($token = DBA::fetch($tokens)) {
894                                 DBA::delete('tokens', ['id' => $token['id']]);
895                         }
896                         DBA::close($tokens);
897                 }
898         }
899
900         /**
901          * Checks if a database update is currently running
902          *
903          * @return boolean
904          */
905         private static function isUpdating(): bool
906         {
907                 $isUpdate = false;
908
909                 $processes = DBA::select('information_schema.processlist', ['info'], [
910                         'db' => DBA::databaseName(),
911                         'command' => ['Query', 'Execute']
912                 ]);
913
914                 while ($process = DBA::fetch($processes)) {
915                         $parts = explode(' ', $process['info']);
916                         if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
917                                 $isUpdate = true;
918                         }
919                 }
920
921                 DBA::close($processes);
922
923                 return $isUpdate;
924         }
925 }