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