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