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