]> git.mxchange.org Git - friendica.git/blob - src/Database/DBStructure.php
Move DB_UPDATE_VERSION from boot.php to config/dbstructure.php
[friendica.git] / src / Database / DBStructure.php
1 <?php
2 /**
3  * @file src/Database/DBStructure.php
4  */
5 namespace Friendica\Database;
6
7 use Exception;
8 use Friendica\Core\Config;
9 use Friendica\Core\Hook;
10 use Friendica\Core\L10n;
11 use Friendica\Util\DateTimeFormat;
12
13 require_once 'boot.php';
14 require_once 'include/dba.php';
15 require_once 'include/enotify.php';
16 require_once 'include/text.php';
17
18 /**
19  * @brief This class contain functions for the database management
20  *
21  * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
22  */
23 class DBStructure
24 {
25         /**
26          * Database structure definition loaded from config/dbstructure.php
27          *
28          * @var array
29          */
30         private static $definition = [];
31
32         /*
33          * Converts all tables from MyISAM to InnoDB
34          */
35         public static function convertToInnoDB() {
36                 $r = q("SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `engine` = 'MyISAM' AND `table_schema` = '%s'",
37                         DBA::escape(DBA::databaseName()));
38
39                 if (!DBA::isResult($r)) {
40                         echo L10n::t('There are no tables on MyISAM.')."\n";
41                         return;
42                 }
43
44                 foreach ($r AS $table) {
45                         $sql = sprintf("ALTER TABLE `%s` engine=InnoDB;", DBA::escape($table['TABLE_NAME']));
46                         echo $sql."\n";
47
48                         $result = DBA::e($sql);
49                         if (!DBA::isResult($result)) {
50                                 self::printUpdateError($sql);
51                         }
52                 }
53         }
54
55         /*
56          * send the email and do what is needed to do on update fails
57          *
58          * @param update_id             (int) number of failed update
59          * @param error_message (str) error message
60          */
61         public static function updateFail($update_id, $error_message) {
62                 $a = get_app();
63
64                 //send the administrators an e-mail
65                 $admin_mail_list = "'".implode("','", array_map(['Friendica\Database\DBA', 'escape'], explode(",", str_replace(" ", "", Config::get('config', 'admin_email')))))."'";
66                 $adminlist = q("SELECT uid, language, email FROM user WHERE email IN (%s)",
67                         $admin_mail_list
68                 );
69
70                 // No valid result?
71                 if (!DBA::isResult($adminlist)) {
72                         logger(sprintf('Cannot notify administrators about update_id=%d, error_message=%s', $update_id, $error_message), LOGGER_INFO);
73
74                         // Don't continue
75                         return;
76                 }
77
78                 // every admin could had different language
79                 foreach ($adminlist as $admin) {
80                         $lang = (($admin['language'])?$admin['language']:'en');
81                         L10n::pushLang($lang);
82
83                         $preamble = deindent(L10n::t("
84                                 The friendica developers released update %s recently,
85                                 but when I tried to install it, something went terribly wrong.
86                                 This needs to be fixed soon and I can't do it alone. Please contact a
87                                 friendica developer if you can not help me on your own. My database might be invalid.",
88                                 $update_id));
89                         $body = L10n::t("The error message is\n[pre]%s[/pre]", $error_message);
90
91                         notification([
92                                 'uid'      => $admin['uid'],
93                                 'type'     => SYSTEM_EMAIL,
94                                 'to_email' => $admin['email'],
95                                 'preamble' => $preamble,
96                                 'body'     => $body,
97                                 'language' => $lang]
98                         );
99                         L10n::popLang();
100                 }
101
102                 //try the logger
103                 logger("CRITICAL: Database structure update failed: ".$error_message);
104         }
105
106
107         private static function tableStructure($table) {
108                 $structures = q("DESCRIBE `%s`", $table);
109
110                 $full_columns = q("SHOW FULL COLUMNS FROM `%s`", $table);
111
112                 $indexes = q("SHOW INDEX FROM `%s`", $table);
113
114                 $table_status = q("SHOW TABLE STATUS WHERE `name` = '%s'", $table);
115
116                 if (DBA::isResult($table_status)) {
117                         $table_status = $table_status[0];
118                 } else {
119                         $table_status = [];
120                 }
121
122                 $fielddata = [];
123                 $indexdata = [];
124
125                 if (DBA::isResult($indexes)) {
126                         foreach ($indexes AS $index) {
127                                 if ($index['Key_name'] != 'PRIMARY' && $index['Non_unique'] == '0' && !isset($indexdata[$index["Key_name"]])) {
128                                         $indexdata[$index["Key_name"]] = ['UNIQUE'];
129                                 }
130
131                                 $column = $index["Column_name"];
132
133                                 if ($index["Sub_part"] != "") {
134                                         $column .= "(".$index["Sub_part"].")";
135                                 }
136
137                                 $indexdata[$index["Key_name"]][] = $column;
138                         }
139                 }
140                 if (DBA::isResult($structures)) {
141                         foreach ($structures AS $field) {
142                                 // Replace the default size values so that we don't have to define them
143                                 $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)'];
144                                 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
145                                 $field["Type"] = str_replace($search, $replace, $field["Type"]);
146
147                                 $fielddata[$field["Field"]]["type"] = $field["Type"];
148                                 if ($field["Null"] == "NO") {
149                                         $fielddata[$field["Field"]]["not null"] = true;
150                                 }
151
152                                 if (isset($field["Default"])) {
153                                         $fielddata[$field["Field"]]["default"] = $field["Default"];
154                                 }
155
156                                 if ($field["Extra"] != "") {
157                                         $fielddata[$field["Field"]]["extra"] = $field["Extra"];
158                                 }
159
160                                 if ($field["Key"] == "PRI") {
161                                         $fielddata[$field["Field"]]["primary"] = true;
162                                 }
163                         }
164                 }
165                 if (DBA::isResult($full_columns)) {
166                         foreach ($full_columns AS $column) {
167                                 $fielddata[$column["Field"]]["Collation"] = $column["Collation"];
168                                 $fielddata[$column["Field"]]["comment"] = $column["Comment"];
169                         }
170                 }
171
172                 return ["fields" => $fielddata, "indexes" => $indexdata, "table_status" => $table_status];
173         }
174
175         public static function printStructure() {
176                 $database = self::definition();
177
178                 echo "-- ------------------------------------------\n";
179                 echo "-- ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION." (".FRIENDICA_CODENAME,")\n";
180                 echo "-- DB_UPDATE_VERSION ".DB_UPDATE_VERSION."\n";
181                 echo "-- ------------------------------------------\n\n\n";
182                 foreach ($database AS $name => $structure) {
183                         echo "--\n";
184                         echo "-- TABLE $name\n";
185                         echo "--\n";
186                         self::createTable($name, $structure, true, false);
187
188                         echo "\n";
189                 }
190         }
191
192         /**
193          * @brief Print out database error messages
194          *
195          * @param string $message Message to be added to the error message
196          *
197          * @return string Error message
198          */
199         private static function printUpdateError($message) {
200                 echo L10n::t("\nError %d occurred during database update:\n%s\n",
201                         DBA::errorNo(), DBA::errorMessage());
202
203                 return L10n::t('Errors encountered performing database changes: ').$message.EOL;
204         }
205
206         /**
207          * Updates DB structure and returns eventual errors messages
208          *
209          * @param bool  $verbose
210          * @param bool  $action     Whether to actually apply the update
211          * @param bool  $install    Is this the initial update during the installation?
212          * @param array $tables     An array of the database tables
213          * @param array $definition An array of the definition tables
214          * @return string Empty string if the update is successful, error messages otherwise
215          */
216         public static function update($verbose, $action, $install = false, array $tables = null, array $definition = null) {
217                 if ($action && !$install) {
218                         Config::set('system', 'maintenance', 1);
219                         Config::set('system', 'maintenance_reason', L10n::t('%s: Database update', DateTimeFormat::utcNow().' '.date('e')));
220                 }
221
222                 $errors = '';
223
224                 logger('updating structure', LOGGER_DEBUG);
225
226                 // Get the current structure
227                 $database = [];
228
229                 if (is_null($tables)) {
230                         $tables = q("SHOW TABLES");
231                 }
232
233                 if (DBA::isResult($tables)) {
234                         foreach ($tables AS $table) {
235                                 $table = current($table);
236
237                                 logger(sprintf('updating structure for table %s ...', $table), LOGGER_DEBUG);
238                                 $database[$table] = self::tableStructure($table);
239                         }
240                 }
241
242                 // Get the definition
243                 if (is_null($definition)) {
244                         $definition = self::definition();
245                 }
246
247                 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
248                 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
249                         !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
250                         $ignore = '';
251                 } else {
252                         $ignore = ' IGNORE';
253                 }
254
255                 // Compare it
256                 foreach ($definition AS $name => $structure) {
257                         $is_new_table = false;
258                         $group_by = "";
259                         $sql3 = "";
260                         $is_unique = false;
261                         $temp_name = $name;
262                         if (!isset($database[$name])) {
263                                 $r = self::createTable($name, $structure, $verbose, $action);
264                                 if (!DBA::isResult($r)) {
265                                         $errors .= self::printUpdateError($name);
266                                 }
267                                 $is_new_table = true;
268                         } else {
269                                 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
270                                         if (isset($database[$name]["indexes"][$indexname])) {
271                                                 $current_index_definition = implode(",",$database[$name]["indexes"][$indexname]);
272                                         } else {
273                                                 $current_index_definition = "__NOT_SET__";
274                                         }
275                                         $new_index_definition = implode(",",$fieldnames);
276                                         if ($current_index_definition != $new_index_definition) {
277                                                 if ($fieldnames[0] == "UNIQUE") {
278                                                         $is_unique = true;
279                                                         if ($ignore == "") {
280                                                                 $temp_name = "temp-".$name;
281                                                         }
282                                                 }
283                                         }
284                                 }
285
286                                 /*
287                                  * Drop the index if it isn't present in the definition
288                                  * or the definition differ from current status
289                                  * and index name doesn't start with "local_"
290                                  */
291                                 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
292                                         $current_index_definition = implode(",",$fieldnames);
293                                         if (isset($structure["indexes"][$indexname])) {
294                                                 $new_index_definition = implode(",",$structure["indexes"][$indexname]);
295                                         } else {
296                                                 $new_index_definition = "__NOT_SET__";
297                                         }
298                                         if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
299                                                 $sql2=self::dropIndex($indexname);
300                                                 if ($sql3 == "") {
301                                                         $sql3 = "ALTER".$ignore." TABLE `".$temp_name."` ".$sql2;
302                                                 } else {
303                                                         $sql3 .= ", ".$sql2;
304                                                 }
305                                         }
306                                 }
307                                 // Compare the field structure field by field
308                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
309                                         if (!isset($database[$name]["fields"][$fieldname])) {
310                                                 $sql2=self::addTableField($fieldname, $parameters);
311                                                 if ($sql3 == "") {
312                                                         $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
313                                                 } else {
314                                                         $sql3 .= ", ".$sql2;
315                                                 }
316                                         } else {
317                                                 // Compare the field definition
318                                                 $field_definition = $database[$name]["fields"][$fieldname];
319
320                                                 // Remove the relation data that is used for the referential integrity
321                                                 unset($parameters['relation']);
322
323                                                 // We change the collation after the indexes had been changed.
324                                                 // This is done to avoid index length problems.
325                                                 // So here we always ensure that there is no need to change it.
326                                                 unset($parameters['Collation']);
327                                                 unset($field_definition['Collation']);
328
329                                                 // Only update the comment when it is defined
330                                                 if (!isset($parameters['comment'])) {
331                                                         $parameters['comment'] = "";
332                                                 }
333
334                                                 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
335                                                 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
336                                                 if ($current_field_definition != $new_field_definition) {
337                                                         $sql2 = self::modifyTableField($fieldname, $parameters);
338                                                         if ($sql3 == "") {
339                                                                 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
340                                                         } else {
341                                                                 $sql3 .= ", ".$sql2;
342                                                         }
343                                                 }
344                                         }
345                                 }
346                         }
347
348                         /*
349                          * Create the index if the index don't exists in database
350                          * or the definition differ from the current status.
351                          * Don't create keys if table is new
352                          */
353                         if (!$is_new_table) {
354                                 foreach ($structure["indexes"] AS $indexname => $fieldnames) {
355                                         if (isset($database[$name]["indexes"][$indexname])) {
356                                                 $current_index_definition = implode(",",$database[$name]["indexes"][$indexname]);
357                                         } else {
358                                                 $current_index_definition = "__NOT_SET__";
359                                         }
360                                         $new_index_definition = implode(",",$fieldnames);
361                                         if ($current_index_definition != $new_index_definition) {
362                                                 $sql2 = self::createIndex($indexname, $fieldnames);
363
364                                                 // Fetch the "group by" fields for unique indexes
365                                                 if ($fieldnames[0] == "UNIQUE") {
366                                                         $group_by = self::groupBy($indexname, $fieldnames);
367                                                 }
368                                                 if ($sql2 != "") {
369                                                         if ($sql3 == "") {
370                                                                 $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
371                                                         } else {
372                                                                 $sql3 .= ", ".$sql2;
373                                                         }
374                                                 }
375                                         }
376                                 }
377
378                                 if (isset($database[$name]["table_status"]["Comment"])) {
379                                         if ($database[$name]["table_status"]["Comment"] != $structure['comment']) {
380                                                 $sql2 = "COMMENT = '".DBA::escape($structure['comment'])."'";
381
382                                                 if ($sql3 == "") {
383                                                         $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
384                                                 } else {
385                                                         $sql3 .= ", ".$sql2;
386                                                 }
387                                         }
388                                 }
389
390                                 if (isset($database[$name]["table_status"]["Engine"]) && isset($structure['engine'])) {
391                                         if ($database[$name]["table_status"]["Engine"] != $structure['engine']) {
392                                                 $sql2 = "ENGINE = '".DBA::escape($structure['engine'])."'";
393
394                                                 if ($sql3 == "") {
395                                                         $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
396                                                 } else {
397                                                         $sql3 .= ", ".$sql2;
398                                                 }
399                                         }
400                                 }
401
402                                 if (isset($database[$name]["table_status"]["Collation"])) {
403                                         if ($database[$name]["table_status"]["Collation"] != 'utf8mb4_general_ci') {
404                                                 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
405
406                                                 if ($sql3 == "") {
407                                                         $sql3 = "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
408                                                 } else {
409                                                         $sql3 .= ", ".$sql2;
410                                                 }
411                                         }
412                                 }
413
414                                 if ($sql3 != "") {
415                                         $sql3 .= "; ";
416                                 }
417
418                                 // Now have a look at the field collations
419                                 // Compare the field structure field by field
420                                 foreach ($structure["fields"] AS $fieldname => $parameters) {
421                                         // Compare the field definition
422                                         $field_definition = defaults($database[$name]["fields"], $fieldname, ['Collation' => '']);
423
424                                         // Define the default collation if not given
425                                         if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
426                                                 $parameters['Collation'] = 'utf8mb4_general_ci';
427                                         } else {
428                                                 $parameters['Collation'] = null;
429                                         }
430
431                                         if ($field_definition['Collation'] != $parameters['Collation']) {
432                                                 $sql2 = self::modifyTableField($fieldname, $parameters);
433                                                 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
434                                                         $sql3 .= "ALTER" . $ignore . " TABLE `".$temp_name."` ".$sql2;
435                                                 } else {
436                                                         $sql3 .= ", ".$sql2;
437                                                 }
438                                         }
439                                 }
440                         }
441
442                         if ($sql3 != "") {
443                                 if (substr($sql3, -2, 2) != "; ") {
444                                         $sql3 .= ";";
445                                 }
446
447                                 $field_list = '';
448                                 if ($is_unique && $ignore == '') {
449                                         foreach ($database[$name]["fields"] AS $fieldname => $parameters) {
450                                                 $field_list .= 'ANY_VALUE(`' . $fieldname . '`),';
451                                         }
452                                         $field_list = rtrim($field_list, ',');
453                                 }
454
455                                 if ($verbose) {
456                                         // Ensure index conversion to unique removes duplicates
457                                         if ($is_unique && ($temp_name != $name)) {
458                                                 if ($ignore != "") {
459                                                         echo "SET session old_alter_table=1;\n";
460                                                 } else {
461                                                         echo "DROP TABLE IF EXISTS `".$temp_name."`;\n";
462                                                         echo "CREATE TABLE `".$temp_name."` LIKE `".$name."`;\n";
463                                                 }
464                                         }
465
466                                         echo $sql3."\n";
467
468                                         if ($is_unique && ($temp_name != $name)) {
469                                                 if ($ignore != "") {
470                                                         echo "SET session old_alter_table=0;\n";
471                                                 } else {
472                                                         echo "INSERT INTO `".$temp_name."` SELECT ".DBA::anyValueFallback($field_list)." FROM `".$name."`".$group_by.";\n";
473                                                         echo "DROP TABLE `".$name."`;\n";
474                                                         echo "RENAME TABLE `".$temp_name."` TO `".$name."`;\n";
475                                                 }
476                                         }
477                                 }
478
479                                 if ($action) {
480                                         if (!$install) {
481                                                 Config::set('system', 'maintenance_reason', L10n::t('%s: updating %s table.', DateTimeFormat::utcNow().' '.date('e'), $name));
482                                         }
483
484                                         // Ensure index conversion to unique removes duplicates
485                                         if ($is_unique && ($temp_name != $name)) {
486                                                 if ($ignore != "") {
487                                                         DBA::e("SET session old_alter_table=1;");
488                                                 } else {
489                                                         $r = DBA::e("DROP TABLE IF EXISTS `".$temp_name."`;");
490                                                         if (!DBA::isResult($r)) {
491                                                                 $errors .= self::printUpdateError($sql3);
492                                                                 return $errors;
493                                                         }
494
495                                                         $r = DBA::e("CREATE TABLE `".$temp_name."` LIKE `".$name."`;");
496                                                         if (!DBA::isResult($r)) {
497                                                                 $errors .= self::printUpdateError($sql3);
498                                                                 return $errors;
499                                                         }
500                                                 }
501                                         }
502
503                                         $r = DBA::e($sql3);
504                                         if (!DBA::isResult($r)) {
505                                                 $errors .= self::printUpdateError($sql3);
506                                         }
507                                         if ($is_unique && ($temp_name != $name)) {
508                                                 if ($ignore != "") {
509                                                         DBA::e("SET session old_alter_table=0;");
510                                                 } else {
511                                                         $r = DBA::e("INSERT INTO `".$temp_name."` SELECT ".$field_list." FROM `".$name."`".$group_by.";");
512                                                         if (!DBA::isResult($r)) {
513                                                                 $errors .= self::printUpdateError($sql3);
514                                                                 return $errors;
515                                                         }
516                                                         $r = DBA::e("DROP TABLE `".$name."`;");
517                                                         if (!DBA::isResult($r)) {
518                                                                 $errors .= self::printUpdateError($sql3);
519                                                                 return $errors;
520                                                         }
521                                                         $r = DBA::e("RENAME TABLE `".$temp_name."` TO `".$name."`;");
522                                                         if (!DBA::isResult($r)) {
523                                                                 $errors .= self::printUpdateError($sql3);
524                                                                 return $errors;
525                                                         }
526                                                 }
527                                         }
528                                 }
529                         }
530                 }
531
532                 if ($action && !$install) {
533                         Config::set('system', 'maintenance', 0);
534                         Config::set('system', 'maintenance_reason', '');
535
536                         if ($errors) {
537                                 Config::set('system', 'dbupdate', DB_UPDATE_FAILED);
538                         } else {
539                                 Config::set('system', 'dbupdate', DB_UPDATE_SUCCESSFUL);
540                         }
541                 }
542
543                 return $errors;
544         }
545
546         private static function FieldCommand($parameters, $create = true) {
547                 $fieldstruct = $parameters["type"];
548
549                 if (isset($parameters["Collation"])) {
550                         $fieldstruct .= " COLLATE ".$parameters["Collation"];
551                 }
552
553                 if (isset($parameters["not null"])) {
554                         $fieldstruct .= " NOT NULL";
555                 }
556
557                 if (isset($parameters["default"])) {
558                         if (strpos(strtolower($parameters["type"]),"int")!==false) {
559                                 $fieldstruct .= " DEFAULT ".$parameters["default"];
560                         } else {
561                                 $fieldstruct .= " DEFAULT '".$parameters["default"]."'";
562                         }
563                 }
564                 if (isset($parameters["extra"])) {
565                         $fieldstruct .= " ".$parameters["extra"];
566                 }
567
568                 if (isset($parameters["comment"])) {
569                         $fieldstruct .= " COMMENT '".DBA::escape($parameters["comment"])."'";
570                 }
571
572                 /*if (($parameters["primary"] != "") && $create)
573                         $fieldstruct .= " PRIMARY KEY";*/
574
575                 return($fieldstruct);
576         }
577
578         private static function createTable($name, $structure, $verbose, $action) {
579                 $r = true;
580
581                 $engine = "";
582                 $comment = "";
583                 $sql_rows = [];
584                 $primary_keys = [];
585                 foreach ($structure["fields"] AS $fieldname => $field) {
586                         $sql_rows[] = "`".DBA::escape($fieldname)."` ".self::FieldCommand($field);
587                         if (x($field,'primary') && $field['primary']!='') {
588                                 $primary_keys[] = $fieldname;
589                         }
590                 }
591
592                 if (!empty($structure["indexes"])) {
593                         foreach ($structure["indexes"] AS $indexname => $fieldnames) {
594                                 $sql_index = self::createIndex($indexname, $fieldnames, "");
595                                 if (!is_null($sql_index)) {
596                                         $sql_rows[] = $sql_index;
597                                 }
598                         }
599                 }
600
601                 if (isset($structure["engine"])) {
602                         $engine = " ENGINE=" . $structure["engine"];
603                 }
604
605                 if (isset($structure["comment"])) {
606                         $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
607                 }
608
609                 $sql = implode(",\n\t", $sql_rows);
610
611                 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)).$sql.
612                                 "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
613                 if ($verbose) {
614                         echo $sql.";\n";
615                 }
616
617                 if ($action) {
618                         $r = DBA::e($sql);
619                 }
620
621                 return $r;
622         }
623
624         private static function addTableField($fieldname, $parameters) {
625                 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
626                 return($sql);
627         }
628
629         private static function modifyTableField($fieldname, $parameters) {
630                 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
631                 return($sql);
632         }
633
634         private static function dropIndex($indexname) {
635                 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
636                 return($sql);
637         }
638
639         private static function createIndex($indexname, $fieldnames, $method = "ADD") {
640                 $method = strtoupper(trim($method));
641                 if ($method!="" && $method!="ADD") {
642                         throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
643                 }
644
645                 if ($fieldnames[0] == "UNIQUE") {
646                         array_shift($fieldnames);
647                         $method .= ' UNIQUE';
648                 }
649
650                 $names = "";
651                 foreach ($fieldnames AS $fieldname) {
652                         if ($names != "") {
653                                 $names .= ",";
654                         }
655
656                         if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
657                                 $names .= "`".DBA::escape($matches[1])."`(".intval($matches[2]).")";
658                         } else {
659                                 $names .= "`".DBA::escape($fieldname)."`";
660                         }
661                 }
662
663                 if ($indexname == "PRIMARY") {
664                         return sprintf("%s PRIMARY KEY(%s)", $method, $names);
665                 }
666
667
668                 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
669                 return($sql);
670         }
671
672         private static function groupBy($indexname, $fieldnames) {
673                 if ($fieldnames[0] != "UNIQUE") {
674                         return "";
675                 }
676
677                 array_shift($fieldnames);
678
679                 $names = "";
680                 foreach ($fieldnames AS $fieldname) {
681                         if ($names != "") {
682                                 $names .= ",";
683                         }
684
685                         if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
686                                 $names .= "`".DBA::escape($matches[1])."`";
687                         } else {
688                                 $names .= "`".DBA::escape($fieldname)."`";
689                         }
690                 }
691
692                 $sql = sprintf(" GROUP BY %s", $names);
693                 return $sql;
694         }
695
696         /**
697          *      Check if a table exists
698          *
699          * @param string $table Table name
700          *
701          * @return boolean Does the table exist?
702          */
703         public static function existsTable($table)
704         {
705                 if (empty($table)) {
706                         return false;
707                 }
708
709                 $table = DBA::escape($table);
710
711                 $sql = "SHOW TABLES LIKE '" . $table . "';";
712
713                 $stmt = DBA::p($sql);
714
715                 if (is_bool($stmt)) {
716                         $retval = $stmt;
717                 } else {
718                         $retval = (DBA::numRows($stmt) > 0);
719                 }
720
721                 DBA::close($stmt);
722
723                 return $retval;
724         }
725
726         /**
727          *      Check if the columns of the table exists
728          *
729          * @param string $table   Table name
730          * @param array  $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
731          *
732          * @return boolean Does the table exist?
733          */
734         public static function existsColumn($table, $columns = []) {
735                 if (empty($table)) {
736                         return false;
737                 }
738
739                 if (is_null($columns) || empty($columns)) {
740                         return self::existsTable($table);
741                 }
742
743                 $table = DBA::escape($table);
744
745                 foreach ($columns AS $column) {
746                         $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
747
748                         $stmt = DBA::p($sql);
749
750                         if (is_bool($stmt)) {
751                                 $retval = $stmt;
752                         } else {
753                                 $retval = (DBA::numRows($stmt) > 0);
754                         }
755
756                         DBA::close($stmt);
757
758                         if (!$retval) {
759                                 return false;
760                         }
761                 }
762
763                 return true;
764         }
765
766         const RENAME_COLUMN = 0;
767         const RENAME_PRIMARY_KEY = 1;
768
769         /**
770          * Renames columns or the primary key of a table
771          * @todo You cannot rename a primary key if "auto increment" is set
772          *
773          * @param string $table    Table name
774          * @param array  $columns  Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ] )
775          *                                 Syntax for Primary Key: [ $col1, $col2, ...] )
776          * @param int    $type     The type of renaming (Default is Column)
777          *
778          * @return boolean Was the renaming successful?
779          *
780          */
781         public static function rename($table, $columns, $type = self::RENAME_COLUMN) {
782                 if (empty($table) || empty($columns)) {
783                         return false;
784                 }
785
786                 if (!is_array($columns)) {
787                         return false;
788                 }
789
790                 $table = DBA::escape($table);
791
792                 $sql = "ALTER TABLE `" . $table . "`";
793                 switch ($type) {
794                         case self::RENAME_COLUMN:
795                                 if (!self::existsColumn($table, array_keys($columns))) {
796                                         return false;
797                                 }
798                                 $sql .= implode(',', array_map(
799                                         function ($to, $from) {
800                                                 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
801                                         },
802                                         $columns,
803                                         array_keys($columns)
804                                 ));
805                                 break;
806                         case self::RENAME_PRIMARY_KEY:
807                                 if (!self::existsColumn($table, $columns)) {
808                                         return false;
809                                 }
810                                 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
811                                 break;
812                         default:
813                                 return false;
814                 }
815
816                 $sql .= ";";
817
818                 $stmt = DBA::p($sql);
819
820                 if (is_bool($stmt)) {
821                         $retval = $stmt;
822                 } else {
823                         $retval = true;
824                 }
825
826                 DBA::close($stmt);
827
828                 return $retval;
829         }
830
831         /**
832          * Loads the database structure definition from the config/dbstructure.php file.
833          * On first pass, defines DB_UPDATE_VERSION constant.
834          *
835          * @see config/dbstructure.php
836          * @return array
837          * @throws Exception
838          */
839         public static function definition()
840         {
841                 if (!self::$definition) {
842                         $a = \Friendica\BaseObject::getApp();
843
844                         $filename = $a->getBasePath() . '/config/dbstructure.php';
845
846                         if (!is_readable($filename)) {
847                                 throw new Exception('Missing database structure config file config/dbstructure.php');
848                         }
849
850                         $definition = require $filename;
851
852                         if (!$definition) {
853                                 throw new Exception('Corrupted database structure config file config/dbstructure.php');
854                         }
855
856                         self::$definition = $definition;
857                 } else {
858                         $definition = self::$definition;
859                 }
860
861                 Hook::callAll('dbstructure_definition', $definition);
862
863                 return $definition;
864         }
865 }