]> git.mxchange.org Git - friendica.git/blob - src/Database/DBStructure.php
Merge pull request #11519 from MrPetovan/task/11511-console-domain-move
[friendica.git] / src / Database / DBStructure.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Database;
23
24 use Exception;
25 use Friendica\Core\Hook;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Renderer;
28 use Friendica\DI;
29 use Friendica\Model\Item;
30 use Friendica\Model\User;
31 use Friendica\Util\DateTimeFormat;
32
33 /**
34  * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
35  */
36 class DBStructure
37 {
38         const UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
39         const UPDATE_SUCCESSFUL  = 1; // Database check was successful
40         const UPDATE_FAILED      = 2; // Database check failed
41
42         const RENAME_COLUMN      = 0;
43         const RENAME_PRIMARY_KEY = 1;
44
45         /**
46          * Database structure definition loaded from config/dbstructure.config.php
47          *
48          * @var array
49          */
50         private static $definition = [];
51
52         /**
53          * Set a database version to trigger update functions
54          *
55          * @param string $version
56          * @return void
57          */
58         public static function setDatabaseVersion(string $version)
59         {
60                 if (!is_numeric($version)) {
61                         throw new \Asika\SimpleConsole\CommandArgsException('The version number must be numeric');
62                 }
63
64                 DI::config()->set('system', 'build', $version);
65                 echo DI::l10n()->t('The database version had been set to %s.', $version);
66         }
67
68         /**
69          * Drop unused tables
70          *
71          * @param boolean $execute
72          * @return void
73          */
74         public static function dropTables(bool $execute)
75         {
76                 $postupdate = DI::config()->get("system", "post_update_version", PostUpdate::VERSION);
77                 if ($postupdate < PostUpdate::VERSION) {
78                         echo DI::l10n()->t('The post update is at version %d, it has to be at %d to safely drop the tables.', $postupdate, PostUpdate::VERSION);
79                         return;
80                 }
81
82                 $old_tables = ['fserver', 'gcign', 'gcontact', 'gcontact-relation', 'gfollower' ,'glink', 'item-delivery-data',
83                         'item-activity', 'item-content', 'item_id', 'participation', 'poll', 'poll_result', 'queue', 'retriever_rule',
84                         'deliverq', 'dsprphotoq', 'ffinder', 'sign', 'spam', 'term', 'user-item', 'thread', 'item', 'challenge',
85                         'auth_codes', 'tokens', 'clients', 'profile_check', 'host'];
86
87                 $tables = DBA::selectToArray(['INFORMATION_SCHEMA' => 'TABLES'], ['TABLE_NAME'],
88                         ['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_TYPE' => 'BASE TABLE']);
89
90                 if (empty($tables)) {
91                         echo DI::l10n()->t('No unused tables found.');
92                         return;
93                 }
94
95                 if (!$execute) {
96                         echo DI::l10n()->t('These tables are not used for friendica and will be deleted when you execute "dbstructure drop -e":') . "\n\n";
97                 }
98
99                 foreach ($old_tables as $table) {
100                         if (in_array($table, array_column($tables, 'TABLE_NAME'))) {
101                                 if ($execute) {
102                                         $sql = 'DROP TABLE ' . DBA::quoteIdentifier($table) . ';';
103                                         echo $sql . "\n";
104
105                                         $result = DBA::e($sql);
106                                         if (!DBA::isResult($result)) {
107                                                 self::printUpdateError($sql);
108                                         }
109                                 } else {
110                                         echo $table . "\n";
111                                 }
112                         }
113                 }
114         }
115
116         /**
117          * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
118          */
119         public static function convertToInnoDB()
120         {
121                 $tables = DBA::selectToArray(
122                         ['information_schema' => 'tables'],
123                         ['table_name'],
124                         ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
125                 );
126
127                 $tables = array_merge($tables, DBA::selectToArray(
128                         ['information_schema' => 'tables'],
129                         ['table_name'],
130                         ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
131                 ));
132
133                 if (!DBA::isResult($tables)) {
134                         echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
135                         return;
136                 }
137
138                 foreach ($tables as $table) {
139                         $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
140                         echo $sql . "\n";
141
142                         $result = DBA::e($sql);
143                         if (!DBA::isResult($result)) {
144                                 self::printUpdateError($sql);
145                         }
146                 }
147         }
148
149         /**
150          * Print out database error messages
151          *
152          * @param string $message Message to be added to the error message
153          *
154          * @return string Error message
155          */
156         private static function printUpdateError($message)
157         {
158                 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
159                         DBA::errorNo(), DBA::errorMessage());
160
161                 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
162         }
163
164         public static function writeStructure()
165         {
166                 $tables = [];
167                 foreach (self::definition(null) as $name => $definition) {
168                         $indexes  = [[
169                                 'name'   => 'Name',
170                                 'fields' => 'Fields',
171                         ],
172                         [
173                                 'name'   => '-',
174                                 'fields' => '-',
175                         ]];
176
177                         $lengths = ['name' => 4, 'fields' => 6];
178                         foreach ($definition['indexes'] as $key => $value) {
179                                 $fieldlist = implode(', ', $value);
180                                 $indexes[] = ['name' => $key, 'fields' => $fieldlist];
181                                 $lengths['name']   = max($lengths['name'], strlen($key));
182                                 $lengths['fields'] = max($lengths['fields'], strlen($fieldlist));
183                         }
184
185                         array_walk_recursive($indexes, function(&$value, $key) use ($lengths)
186                         {
187                                 $value = str_pad($value, $lengths[$key], $value === '-' ? '-' : ' ');
188                         });
189
190                         $foreign = [];
191                         $fields  = [[
192                                 'name'    => 'Field',
193                                 'comment' => 'Description',
194                                 'type'    => 'Type',
195                                 'null'    => 'Null',
196                                 'primary' => 'Key',
197                                 'default' => 'Default',
198                                 'extra'   => 'Extra',
199                         ],
200                         [
201                                 'name'    => '-',
202                                 'comment' => '-',
203                                 'type'    => '-',
204                                 'null'    => '-',
205                                 'primary' => '-',
206                                 'default' => '-',
207                                 'extra'   => '-',
208                         ]];
209                         $lengths = [
210                                 'name'    => 5,
211                                 'comment' => 11,
212                                 'type'    => 4,
213                                 'null'    => 4,
214                                 'primary' => 3,
215                                 'default' => 7,
216                                 'extra'   => 5,
217                         ];
218                         foreach ($definition['fields'] as $key => $value) {
219                                 $field = [];
220                                 $field['name']    = $key;
221                                 $field['comment'] = $value['comment'] ?? '';
222                                 $field['type']    = $value['type'];
223                                 $field['null']    = ($value['not null'] ?? false) ? 'NO' : 'YES';
224                                 $field['primary'] = ($value['primary'] ?? false) ? 'PRI' : '';
225                                 $field['default'] = $value['default'] ?? 'NULL';
226                                 $field['extra']   = $value['extra'] ?? '';
227
228                                 foreach ($field as $fieldname => $fieldvalue) {
229                                         $lengths[$fieldname] = max($lengths[$fieldname] ?? 0, strlen($fieldvalue));
230                                 }
231                                 $fields[] = $field;
232
233                                 if (!empty($value['foreign'])) {
234                                         $foreign[] = [
235                                                 'field'       => $key,
236                                                 'targettable' => array_keys($value['foreign'])[0],
237                                                 'targetfield' => array_values($value['foreign'])[0]
238                                         ];
239                                 }
240                         }
241
242                         array_walk_recursive($fields, function(&$value, $key) use ($lengths)
243                         {
244                                 $value = str_pad($value, $lengths[$key], $value === '-' ? '-' : ' ');
245                         });
246
247                         $tables[] = ['name' => $name, 'comment' => $definition['comment']];
248                         $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('structure.tpl'), [
249                                 '$name'    => $name,
250                                 '$comment' => $definition['comment'],
251                                 '$fields'  => $fields,
252                                 '$indexes' => $indexes,
253                                 '$foreign' => $foreign,
254                         ]);
255                         $filename = DI::basePath() . '/doc/database/db_' . $name . '.md';
256                         file_put_contents($filename, $content);
257                 }
258                 asort($tables);
259                 $content = Renderer::replaceMacros(Renderer::getMarkupTemplate('tables.tpl'), [
260                         '$tables'  => $tables,
261                 ]);
262                 $filename = DI::basePath() . '/doc/database.md';
263                 file_put_contents($filename, $content);
264         }
265
266         public static function printStructure($basePath)
267         {
268                 $database = self::definition($basePath, false);
269
270                 echo "-- ------------------------------------------\n";
271                 echo "-- " . FRIENDICA_PLATFORM . " " . FRIENDICA_VERSION . " (" . FRIENDICA_CODENAME, ")\n";
272                 echo "-- DB_UPDATE_VERSION " . DB_UPDATE_VERSION . "\n";
273                 echo "-- ------------------------------------------\n\n\n";
274                 foreach ($database as $name => $structure) {
275                         echo "--\n";
276                         echo "-- TABLE $name\n";
277                         echo "--\n";
278                         self::createTable($name, $structure, true, false);
279
280                         echo "\n";
281                 }
282
283                 View::printStructure($basePath);
284         }
285
286         /**
287          * Loads the database structure definition from the static/dbstructure.config.php file.
288          * On first pass, defines DB_UPDATE_VERSION constant.
289          *
290          * @see static/dbstructure.config.php
291          * @param boolean $with_addons_structure Whether to tack on addons additional tables
292          * @param string  $basePath              The base path of this application
293          * @return array
294          * @throws Exception
295          */
296         public static function definition($basePath, $with_addons_structure = true)
297         {
298                 if (!self::$definition) {
299                         if (empty($basePath)) {
300                                 $basePath = DI::app()->getBasePath();
301                         }
302
303                         $filename = $basePath . '/static/dbstructure.config.php';
304
305                         if (!is_readable($filename)) {
306                                 throw new Exception('Missing database structure config file static/dbstructure.config.php');
307                         }
308
309                         $definition = require $filename;
310
311                         if (!$definition) {
312                                 throw new Exception('Corrupted database structure config file static/dbstructure.config.php');
313                         }
314
315                         self::$definition = $definition;
316                 } else {
317                         $definition = self::$definition;
318                 }
319
320                 if ($with_addons_structure) {
321                         Hook::callAll('dbstructure_definition', $definition);
322                 }
323
324                 return $definition;
325         }
326
327         /**
328          * Get field data for the given table
329          *
330          * @param string $table
331          * @param array $data data fields
332          * @return array fields for the given
333          */
334         public static function getFieldsForTable(string $table, array $data = [])
335         {
336                 $definition = DBStructure::definition('', false);
337                 if (empty($definition[$table])) {
338                         return [];
339                 }
340
341                 $fieldnames = array_keys($definition[$table]['fields']);
342
343                 $fields = [];
344
345                 // Assign all field that are present in the table
346                 foreach ($fieldnames as $field) {
347                         if (isset($data[$field])) {
348                                 // Limit the length of varchar, varbinary, char and binrary fields
349                                 if (is_string($data[$field]) && preg_match("/char\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
350                                         $data[$field] = mb_substr($data[$field], 0, $result[1]);
351                                 } elseif (is_string($data[$field]) && preg_match("/binary\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
352                                         $data[$field] = substr($data[$field], 0, $result[1]);
353                                 }
354                                 $fields[$field] = $data[$field];
355                         }
356                 }
357
358                 return $fields;
359         }
360
361         private static function createTable($name, $structure, $verbose, $action)
362         {
363                 $r = true;
364
365                 $engine = "";
366                 $comment = "";
367                 $sql_rows = [];
368                 $primary_keys = [];
369                 $foreign_keys = [];
370
371                 foreach ($structure["fields"] as $fieldname => $field) {
372                         $sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
373                         if (!empty($field['primary'])) {
374                                 $primary_keys[] = $fieldname;
375                         }
376                         if (!empty($field['foreign'])) {
377                                 $foreign_keys[$fieldname] = $field;
378                         }
379                 }
380
381                 if (!empty($structure["indexes"])) {
382                         foreach ($structure["indexes"] as $indexname => $fieldnames) {
383                                 $sql_index = self::createIndex($indexname, $fieldnames, "");
384                                 if (!is_null($sql_index)) {
385                                         $sql_rows[] = $sql_index;
386                                 }
387                         }
388                 }
389
390                 foreach ($foreign_keys as $fieldname => $parameters) {
391                         $sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
392                 }
393
394                 if (isset($structure["engine"])) {
395                         $engine = " ENGINE=" . $structure["engine"];
396                 }
397
398                 if (isset($structure["comment"])) {
399                         $comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
400                 }
401
402                 $sql = implode(",\n\t", $sql_rows);
403
404                 $sql = sprintf("CREATE TABLE IF NOT EXISTS `%s` (\n\t", DBA::escape($name)) . $sql .
405                         "\n)" . $engine . " DEFAULT COLLATE utf8mb4_general_ci" . $comment;
406                 if ($verbose) {
407                         echo $sql . ";\n";
408                 }
409
410                 if ($action) {
411                         $r = DBA::e($sql);
412                 }
413
414                 return $r;
415         }
416
417         private static function FieldCommand($parameters, $create = true)
418         {
419                 $fieldstruct = $parameters["type"];
420
421                 if (isset($parameters["Collation"])) {
422                         $fieldstruct .= " COLLATE " . $parameters["Collation"];
423                 }
424
425                 if (isset($parameters["not null"])) {
426                         $fieldstruct .= " NOT NULL";
427                 }
428
429                 if (isset($parameters["default"])) {
430                         if (strpos(strtolower($parameters["type"]), "int") !== false) {
431                                 $fieldstruct .= " DEFAULT " . $parameters["default"];
432                         } else {
433                                 $fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
434                         }
435                 }
436                 if (isset($parameters["extra"])) {
437                         $fieldstruct .= " " . $parameters["extra"];
438                 }
439
440                 if (isset($parameters["comment"])) {
441                         $fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
442                 }
443
444                 /*if (($parameters["primary"] != "") && $create)
445                         $fieldstruct .= " PRIMARY KEY";*/
446
447                 return ($fieldstruct);
448         }
449
450         private static function createIndex($indexname, $fieldnames, $method = "ADD")
451         {
452                 $method = strtoupper(trim($method));
453                 if ($method != "" && $method != "ADD") {
454                         throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
455                 }
456
457                 if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
458                         $index_type = array_shift($fieldnames);
459                         $method .= " " . $index_type;
460                 }
461
462                 $names = "";
463                 foreach ($fieldnames as $fieldname) {
464                         if ($names != "") {
465                                 $names .= ",";
466                         }
467
468                         if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
469                                 $names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
470                         } else {
471                                 $names .= "`" . DBA::escape($fieldname) . "`";
472                         }
473                 }
474
475                 if ($indexname == "PRIMARY") {
476                         return sprintf("%s PRIMARY KEY(%s)", $method, $names);
477                 }
478
479
480                 $sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
481                 return ($sql);
482         }
483
484         /**
485          * Perform a database structure dryrun (means: just simulating)
486          *
487          * @throws Exception
488          */
489         public static function dryRun()
490         {
491                 self::update(DI::app()->getBasePath(), true, false);
492         }
493
494         /**
495          * Updates DB structure and returns eventual errors messages
496          *
497          * @param bool $enable_maintenance_mode Set the maintenance mode
498          * @param bool $verbose                 Display the SQL commands
499          *
500          * @return string Empty string if the update is successful, error messages otherwise
501          * @throws Exception
502          */
503         public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false)
504         {
505                 if ($enable_maintenance_mode) {
506                         DI::config()->set('system', 'maintenance', 1);
507                 }
508
509                 $status = self::update(DI::app()->getBasePath(), $verbose, true);
510
511                 if ($enable_maintenance_mode) {
512                         DI::config()->set('system', 'maintenance', 0);
513                         DI::config()->set('system', 'maintenance_reason', '');
514                 }
515
516                 return $status;
517         }
518
519         /**
520          * Updates DB structure from the installation and returns eventual errors messages
521          *
522          * @param string $basePath   The base path of this application
523          *
524          * @return string Empty string if the update is successful, error messages otherwise
525          * @throws Exception
526          */
527         public static function install(string $basePath)
528         {
529                 return self::update($basePath, false, true, true);
530         }
531
532         /**
533          * Updates DB structure and returns eventual errors messages
534          *
535          * @param string $basePath   The base path of this application
536          * @param bool   $verbose
537          * @param bool   $action     Whether to actually apply the update
538          * @param bool   $install    Is this the initial update during the installation?
539          * @param array  $tables     An array of the database tables
540          * @param array  $definition An array of the definition tables
541          * @return string Empty string if the update is successful, error messages otherwise
542          * @throws Exception
543          */
544         private static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
545         {
546                 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
547
548                 if ($action && !$install && self::isUpdating()) {
549                         return DI::l10n()->t('Another database update is currently running.');
550                 }
551
552                 if ($in_maintenance_mode) {
553                         DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
554                 }
555
556                 // ensure that all initial values exist. This test has to be done prior and after the structure check.
557                 // Prior is needed if the specific tables already exists - after is needed when they had been created.
558                 self::checkInitialValues();
559
560                 $errors = '';
561
562                 Logger::info('updating structure');
563
564                 // Get the current structure
565                 $database = [];
566
567                 if (is_null($tables)) {
568                         $tables = DBA::toArray(DBA::p("SHOW TABLES"));
569                 }
570
571                 if (DBA::isResult($tables)) {
572                         foreach ($tables as $table) {
573                                 $table = current($table);
574
575                                 Logger::info('updating structure', ['table' => $table]);
576                                 $database[$table] = self::tableStructure($table);
577                         }
578                 }
579
580                 // Get the definition
581                 if (is_null($definition)) {
582                         $definition = self::definition($basePath);
583                 }
584
585                 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
586                 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
587                         !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
588                         $ignore = '';
589                 } else {
590                         $ignore = ' IGNORE';
591                 }
592
593                 // Compare it
594                 foreach ($definition as $name => $structure) {
595                         $is_new_table = false;
596                         $sql3 = "";
597                         if (!isset($database[$name])) {
598                                 $r = self::createTable($name, $structure, $verbose, $action);
599                                 if (!DBA::isResult($r)) {
600                                         $errors .= self::printUpdateError($name);
601                                 }
602                                 $is_new_table = true;
603                         } else {
604                                 /*
605                                  * Drop the index if it isn't present in the definition
606                                  * or the definition differ from current status
607                                  * and index name doesn't start with "local_"
608                                  */
609                                 foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
610                                         $current_index_definition = implode(",", $fieldnames);
611                                         if (isset($structure["indexes"][$indexname])) {
612                                                 $new_index_definition = implode(",", $structure["indexes"][$indexname]);
613                                         } else {
614                                                 $new_index_definition = "__NOT_SET__";
615                                         }
616                                         if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
617                                                 $sql2 = self::dropIndex($indexname);
618                                                 if ($sql3 == "") {
619                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
620                                                 } else {
621                                                         $sql3 .= ", " . $sql2;
622                                                 }
623                                         }
624                                 }
625                                 // Compare the field structure field by field
626                                 foreach ($structure["fields"] as $fieldname => $parameters) {
627                                         if (!isset($database[$name]["fields"][$fieldname])) {
628                                                 $sql2 = self::addTableField($fieldname, $parameters);
629                                                 if ($sql3 == "") {
630                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
631                                                 } else {
632                                                         $sql3 .= ", " . $sql2;
633                                                 }
634                                         } else {
635                                                 // Compare the field definition
636                                                 $field_definition = $database[$name]["fields"][$fieldname];
637
638                                                 // Remove the relation data that is used for the referential integrity
639                                                 unset($parameters['relation']);
640                                                 unset($parameters['foreign']);
641
642                                                 // We change the collation after the indexes had been changed.
643                                                 // This is done to avoid index length problems.
644                                                 // So here we always ensure that there is no need to change it.
645                                                 unset($parameters['Collation']);
646                                                 unset($field_definition['Collation']);
647
648                                                 // Only update the comment when it is defined
649                                                 if (!isset($parameters['comment'])) {
650                                                         $parameters['comment'] = "";
651                                                 }
652
653                                                 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
654                                                 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
655                                                 if ($current_field_definition != $new_field_definition) {
656                                                         $sql2 = self::modifyTableField($fieldname, $parameters);
657                                                         if ($sql3 == "") {
658                                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
659                                                         } else {
660                                                                 $sql3 .= ", " . $sql2;
661                                                         }
662                                                 }
663                                         }
664                                 }
665                         }
666
667                         /*
668                          * Create the index if the index don't exists in database
669                          * or the definition differ from the current status.
670                          * Don't create keys if table is new
671                          */
672                         if (!$is_new_table) {
673                                 foreach ($structure["indexes"] as $indexname => $fieldnames) {
674                                         if (isset($database[$name]["indexes"][$indexname])) {
675                                                 $current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
676                                         } else {
677                                                 $current_index_definition = "__NOT_SET__";
678                                         }
679                                         $new_index_definition = implode(",", $fieldnames);
680                                         if ($current_index_definition != $new_index_definition) {
681                                                 $sql2 = self::createIndex($indexname, $fieldnames);
682
683                                                 if ($sql2 != "") {
684                                                         if ($sql3 == "") {
685                                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
686                                                         } else {
687                                                                 $sql3 .= ", " . $sql2;
688                                                         }
689                                                 }
690                                         }
691                                 }
692
693                                 $existing_foreign_keys = $database[$name]['foreign_keys'];
694
695                                 // Foreign keys
696                                 // Compare the field structure field by field
697                                 foreach ($structure["fields"] as $fieldname => $parameters) {
698                                         if (empty($parameters['foreign'])) {
699                                                 continue;
700                                         }
701
702                                         $constraint = self::getConstraintName($name, $fieldname, $parameters);
703
704                                         unset($existing_foreign_keys[$constraint]);
705
706                                         if (empty($database[$name]['foreign_keys'][$constraint])) {
707                                                 $sql2 = self::addForeignKey($name, $fieldname, $parameters);
708
709                                                 if ($sql3 == "") {
710                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
711                                                 } else {
712                                                         $sql3 .= ", " . $sql2;
713                                                 }
714                                         }
715                                 }
716
717                                 foreach ($existing_foreign_keys as $param) {
718                                         $sql2 = self::dropForeignKey($param['CONSTRAINT_NAME']);
719
720                                         if ($sql3 == "") {
721                                                 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
722                                         } else {
723                                                 $sql3 .= ", " . $sql2;
724                                         }
725                                 }
726
727                                 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
728                                         $structurecomment = $structure["comment"] ?? '';
729                                         if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
730                                                 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
731
732                                                 if ($sql3 == "") {
733                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
734                                                 } else {
735                                                         $sql3 .= ", " . $sql2;
736                                                 }
737                                         }
738                                 }
739
740                                 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
741                                         if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
742                                                 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
743
744                                                 if ($sql3 == "") {
745                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
746                                                 } else {
747                                                         $sql3 .= ", " . $sql2;
748                                                 }
749                                         }
750                                 }
751
752                                 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
753                                         if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
754                                                 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
755
756                                                 if ($sql3 == "") {
757                                                         $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
758                                                 } else {
759                                                         $sql3 .= ", " . $sql2;
760                                                 }
761                                         }
762                                 }
763
764                                 if ($sql3 != "") {
765                                         $sql3 .= "; ";
766                                 }
767
768                                 // Now have a look at the field collations
769                                 // Compare the field structure field by field
770                                 foreach ($structure["fields"] as $fieldname => $parameters) {
771                                         // Compare the field definition
772                                         $field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
773
774                                         // Define the default collation if not given
775                                         if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
776                                                 $parameters['Collation'] = 'utf8mb4_general_ci';
777                                         } else {
778                                                 $parameters['Collation'] = null;
779                                         }
780
781                                         if ($field_definition['Collation'] != $parameters['Collation']) {
782                                                 $sql2 = self::modifyTableField($fieldname, $parameters);
783                                                 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
784                                                         $sql3 .= "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
785                                                 } else {
786                                                         $sql3 .= ", " . $sql2;
787                                                 }
788                                         }
789                                 }
790                         }
791
792                         if ($sql3 != "") {
793                                 if (substr($sql3, -2, 2) != "; ") {
794                                         $sql3 .= ";";
795                                 }
796
797                                 if ($verbose) {
798                                         echo $sql3 . "\n";
799                                 }
800
801                                 if ($action) {
802                                         if ($in_maintenance_mode) {
803                                                 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
804                                         }
805
806                                         $r = DBA::e($sql3);
807                                         if (!DBA::isResult($r)) {
808                                                 $errors .= self::printUpdateError($sql3);
809                                         }
810                                 }
811                         }
812                 }
813
814                 View::create(false, $action);
815
816                 self::checkInitialValues();
817
818                 if ($action && !$install) {
819                         if ($errors) {
820                                 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
821                         } else {
822                                 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
823                         }
824                 }
825
826                 return $errors;
827         }
828
829         private static function tableStructure($table)
830         {
831                 // This query doesn't seem to be executable as a prepared statement
832                 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
833
834                 $fields = DBA::selectToArray(['INFORMATION_SCHEMA' => 'COLUMNS'],
835                         ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
836                         'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
837                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
838                         DBA::databaseName(), $table]);
839
840                 $foreign_keys = DBA::selectToArray(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
841                         ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
842                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
843                         DBA::databaseName(), $table]);
844
845                 $table_status = DBA::selectFirst(['INFORMATION_SCHEMA' => 'TABLES'],
846                         ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
847                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
848                         DBA::databaseName(), $table]);
849
850                 $fielddata = [];
851                 $indexdata = [];
852                 $foreigndata = [];
853
854                 if (DBA::isResult($foreign_keys)) {
855                         foreach ($foreign_keys as $foreign_key) {
856                                 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
857                                 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
858                                 $foreigndata[$constraint] = $foreign_key;
859                         }
860                 }
861
862                 if (DBA::isResult($indexes)) {
863                         foreach ($indexes as $index) {
864                                 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
865                                         $indexdata[$index["Key_name"]] = ["UNIQUE"];
866                                 }
867
868                                 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
869                                         $indexdata[$index["Key_name"]] = ["FULLTEXT"];
870                                 }
871
872                                 $column = $index["Column_name"];
873
874                                 if ($index["Sub_part"] != "") {
875                                         $column .= "(" . $index["Sub_part"] . ")";
876                                 }
877
878                                 $indexdata[$index["Key_name"]][] = $column;
879                         }
880                 }
881
882                 $fielddata = [];
883                 if (DBA::isResult($fields)) {
884                         foreach ($fields as $field) {
885                                 $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)'];
886                                 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
887                                 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
888
889                                 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
890
891                                 if ($field['IS_NULLABLE'] == 'NO') {
892                                         $fielddata[$field['COLUMN_NAME']]['not null'] = true;
893                                 }
894
895                                 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
896                                         $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
897                                 }
898
899                                 if (!empty($field['EXTRA'])) {
900                                         $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
901                                 }
902
903                                 if ($field['COLUMN_KEY'] == 'PRI') {
904                                         $fielddata[$field['COLUMN_NAME']]['primary'] = true;
905                                 }
906
907                                 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
908                                 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
909                         }
910                 }
911
912                 return ["fields" => $fielddata, "indexes" => $indexdata,
913                         "foreign_keys" => $foreigndata, "table_status" => $table_status];
914         }
915
916         private static function dropIndex($indexname)
917         {
918                 $sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
919                 return ($sql);
920         }
921
922         private static function addTableField($fieldname, $parameters)
923         {
924                 $sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
925                 return ($sql);
926         }
927
928         private static function modifyTableField($fieldname, $parameters)
929         {
930                 $sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
931                 return ($sql);
932         }
933
934         private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
935         {
936                 $foreign_table = array_keys($parameters['foreign'])[0];
937                 $foreign_field = array_values($parameters['foreign'])[0];
938
939                 return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
940         }
941
942         private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
943                 $foreign_table = array_keys($parameters['foreign'])[0];
944                 $foreign_field = array_values($parameters['foreign'])[0];
945
946                 $sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
947
948                 if (!empty($parameters['foreign']['on update'])) {
949                         $sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
950                 } else {
951                         $sql .= " ON UPDATE RESTRICT";
952                 }
953
954                 if (!empty($parameters['foreign']['on delete'])) {
955                         $sql .= " ON DELETE " . strtoupper($parameters['foreign']['on delete']);
956                 } else {
957                         $sql .= " ON DELETE CASCADE";
958                 }
959
960                 return $sql;
961         }
962
963         private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
964         {
965                 return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
966         }
967
968         private static function dropForeignKey(string $constraint)
969         {
970                 return sprintf("DROP FOREIGN KEY `%s`", $constraint);
971         }
972
973         /**
974          * Renames columns or the primary key of a table
975          *
976          * @todo You cannot rename a primary key if "auto increment" is set
977          *
978          * @param string $table            Table name
979          * @param array  $columns          Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
980          *                                 Syntax for Primary Key: [ $col1, $col2, ...]
981          * @param int    $type             The type of renaming (Default is Column)
982          *
983          * @return boolean Was the renaming successful?
984          * @throws Exception
985          */
986         public static function rename($table, $columns, $type = self::RENAME_COLUMN)
987         {
988                 if (empty($table) || empty($columns)) {
989                         return false;
990                 }
991
992                 if (!is_array($columns)) {
993                         return false;
994                 }
995
996                 $table = DBA::escape($table);
997
998                 $sql = "ALTER TABLE `" . $table . "`";
999                 switch ($type) {
1000                         case self::RENAME_COLUMN:
1001                                 if (!self::existsColumn($table, array_keys($columns))) {
1002                                         return false;
1003                                 }
1004                                 $sql .= implode(',', array_map(
1005                                         function ($to, $from) {
1006                                                 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
1007                                         },
1008                                         $columns,
1009                                         array_keys($columns)
1010                                 ));
1011                                 break;
1012                         case self::RENAME_PRIMARY_KEY:
1013                                 if (!self::existsColumn($table, $columns)) {
1014                                         return false;
1015                                 }
1016                                 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
1017                                 break;
1018                         default:
1019                                 return false;
1020                 }
1021
1022                 $sql .= ";";
1023
1024                 $stmt = DBA::p($sql);
1025
1026                 if (is_bool($stmt)) {
1027                         $retval = $stmt;
1028                 } else {
1029                         $retval = true;
1030                 }
1031
1032                 DBA::close($stmt);
1033
1034                 return $retval;
1035         }
1036
1037         /**
1038          *    Check if the columns of the table exists
1039          *
1040          * @param string $table   Table name
1041          * @param array  $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
1042          *
1043          * @return boolean Does the table exist?
1044          * @throws Exception
1045          */
1046         public static function existsColumn($table, $columns = [])
1047         {
1048                 if (empty($table)) {
1049                         return false;
1050                 }
1051
1052                 if (is_null($columns) || empty($columns)) {
1053                         return self::existsTable($table);
1054                 }
1055
1056                 $table = DBA::escape($table);
1057
1058                 foreach ($columns as $column) {
1059                         $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
1060
1061                         $stmt = DBA::p($sql);
1062
1063                         if (is_bool($stmt)) {
1064                                 $retval = $stmt;
1065                         } else {
1066                                 $retval = (DBA::numRows($stmt) > 0);
1067                         }
1068
1069                         DBA::close($stmt);
1070
1071                         if (!$retval) {
1072                                 return false;
1073                         }
1074                 }
1075
1076                 return true;
1077         }
1078
1079         /**
1080          * Check if a foreign key exists for the given table field
1081          *
1082          * @param string $table
1083          * @param string $field
1084          * @return boolean
1085          */
1086         public static function existsForeignKeyForField(string $table, string $field)
1087         {
1088                 return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
1089                         ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
1090                         DBA::databaseName(), $table, $field]);
1091         }
1092         /**
1093          *    Check if a table exists
1094          *
1095          * @param string|array $table Table name
1096          *
1097          * @return boolean Does the table exist?
1098          * @throws Exception
1099          */
1100         public static function existsTable($table)
1101         {
1102                 if (empty($table)) {
1103                         return false;
1104                 }
1105
1106                 if (is_array($table)) {
1107                         $condition = ['table_schema' => key($table), 'table_name' => current($table)];
1108                 } else {
1109                         $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
1110                 }
1111
1112                 $result = DBA::exists(['information_schema' => 'tables'], $condition);
1113
1114                 return $result;
1115         }
1116
1117         /**
1118          * Returns the columns of a table
1119          *
1120          * @param string $table Table name
1121          *
1122          * @return array An array of the table columns
1123          * @throws Exception
1124          */
1125         public static function getColumns($table)
1126         {
1127                 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
1128                 return DBA::toArray($stmtColumns);
1129         }
1130
1131         /**
1132          * Check if initial database values do exist - or create them
1133          */
1134         public static function checkInitialValues(bool $verbose = false)
1135         {
1136                 if (self::existsTable('verb')) {
1137                         if (!DBA::exists('verb', ['id' => 1])) {
1138                                 foreach (Item::ACTIVITIES as $index => $activity) {
1139                                         DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
1140                                 }
1141                                 if ($verbose) {
1142                                         echo "verb: activities added\n";
1143                                 }
1144                         } elseif ($verbose) {
1145                                 echo "verb: activities already added\n";
1146                         }
1147
1148                         if (!DBA::exists('verb', ['id' => 0])) {
1149                                 DBA::insert('verb', ['name' => '']);
1150                                 $lastid = DBA::lastInsertId();
1151                                 if ($lastid != 0) {
1152                                         DBA::update('verb', ['id' => 0], ['id' => $lastid]);
1153                                         if ($verbose) {
1154                                                 echo "Zero verb added\n";
1155                                         }
1156                                 }
1157                         } elseif ($verbose) {
1158                                 echo "Zero verb already added\n";
1159                         }
1160                 } elseif ($verbose) {
1161                         echo "verb: Table not found\n";
1162                 }
1163
1164                 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
1165                         $user = [
1166                                 "verified" => true,
1167                                 "page-flags" => User::PAGE_FLAGS_SOAPBOX,
1168                                 "account-type" => User::ACCOUNT_TYPE_RELAY,
1169                         ];
1170                         DBA::insert('user', $user);
1171                         $lastid = DBA::lastInsertId();
1172                         if ($lastid != 0) {
1173                                 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
1174                                 if ($verbose) {
1175                                         echo "Zero user added\n";
1176                                 }
1177                         }
1178                 } elseif (self::existsTable('user') && $verbose) {
1179                         echo "Zero user already added\n";
1180                 } elseif ($verbose) {
1181                         echo "user: Table not found\n";
1182                 }
1183
1184                 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
1185                         DBA::insert('contact', ['nurl' => '']);
1186                         $lastid = DBA::lastInsertId();
1187                         if ($lastid != 0) {
1188                                 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
1189                                 if ($verbose) {
1190                                         echo "Zero contact added\n";
1191                                 }
1192                         }
1193                 } elseif (self::existsTable('contact') && $verbose) {
1194                         echo "Zero contact already added\n";
1195                 } elseif ($verbose) {
1196                         echo "contact: Table not found\n";
1197                 }
1198
1199                 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
1200                         DBA::insert('tag', ['name' => '']);
1201                         $lastid = DBA::lastInsertId();
1202                         if ($lastid != 0) {
1203                                 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
1204                                 if ($verbose) {
1205                                         echo "Zero tag added\n";
1206                                 }
1207                         }
1208                 } elseif (self::existsTable('tag') && $verbose) {
1209                         echo "Zero tag already added\n";
1210                 } elseif ($verbose) {
1211                         echo "tag: Table not found\n";
1212                 }
1213
1214                 if (self::existsTable('permissionset')) {
1215                         if (!DBA::exists('permissionset', ['id' => 0])) {
1216                                 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
1217                                 $lastid = DBA::lastInsertId();
1218                                 if ($lastid != 0) {
1219                                         DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
1220                                         if ($verbose) {
1221                                                 echo "Zero permissionset added\n";
1222                                         }
1223                                 }
1224                         } elseif ($verbose) {
1225                                 echo "Zero permissionset already added\n";
1226                         }
1227                         if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
1228                                 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
1229                                         LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
1230                                         WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
1231                                 while ($set = DBA::fetch($sets)) {
1232                                         if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
1233                                                 $owner = User::getOwnerDataById($set['uid']);
1234                                                 if ($owner) {
1235                                                         $permission = '<' . $owner['id'] . '>';
1236                                                 } else {
1237                                                         $permission = '<>';
1238                                                 }
1239                                         } else {
1240                                                 $permission = '';
1241                                         }
1242                                         $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
1243                                                 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
1244                                         DBA::insert('permissionset', $fields);
1245                                 }
1246                                 DBA::close($sets);
1247                         }
1248                 } elseif ($verbose) {
1249                         echo "permissionset: Table not found\n";
1250                 }
1251
1252                 if (self::existsTable('tokens') && self::existsTable('clients') && !self::existsForeignKeyForField('tokens', 'client_id')) {
1253                         $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
1254                                 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
1255                                 WHERE `clients`.`client_id` IS NULL");
1256                         while ($token = DBA::fetch($tokens)) {
1257                                 DBA::delete('tokens', ['id' => $token['id']]);
1258                         }
1259                         DBA::close($tokens);
1260                 }
1261         }
1262
1263         /**
1264          * Checks if a database update is currently running
1265          *
1266          * @return boolean
1267          */
1268         private static function isUpdating()
1269         {
1270                 $isUpdate = false;
1271
1272                 $processes = DBA::select(['information_schema' => 'processlist'], ['info'],
1273                         ['db' => DBA::databaseName(), 'command' => ['Query', 'Execute']]);
1274
1275                 while ($process = DBA::fetch($processes)) {
1276                         $parts = explode(' ', $process['info']);
1277                         if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
1278                                 $isUpdate = true;
1279                         }
1280                 }
1281
1282                 DBA::close($processes);
1283
1284                 return $isUpdate;
1285         }
1286 }