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