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