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