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