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