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