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