3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Database;
25 use Friendica\Core\Logger;
27 use Friendica\Model\Item;
28 use Friendica\Model\User;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\Writer\DbaDefinitionSqlWriter;
33 * This class contains functions that doesn't need to know if pdo, mysqli or whatever is used.
37 const UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
38 const UPDATE_SUCCESSFUL = 1; // Database check was successful
39 const UPDATE_FAILED = 2; // Database check failed
41 const RENAME_COLUMN = 0;
42 const RENAME_PRIMARY_KEY = 1;
45 * Set a database version to trigger update functions
47 * @param string $version
50 public static function setDatabaseVersion(string $version)
52 if (!is_numeric($version)) {
53 throw new \Asika\SimpleConsole\CommandArgsException('The version number must be numeric');
56 DI::config()->set('system', 'build', $version);
57 echo DI::l10n()->t('The database version had been set to %s.', $version);
63 * @param boolean $execute
66 public static function dropTables(bool $execute)
68 $postupdate = DI::config()->get('system', 'post_update_version', PostUpdate::VERSION);
69 if ($postupdate < PostUpdate::VERSION) {
70 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);
74 $old_tables = ['fserver', 'gcign', 'gcontact', 'gcontact-relation', 'gfollower' ,'glink', 'item-delivery-data',
75 'item-activity', 'item-content', 'item_id', 'participation', 'poll', 'poll_result', 'queue', 'retriever_rule',
76 'deliverq', 'dsprphotoq', 'ffinder', 'sign', 'spam', 'term', 'user-item', 'thread', 'item', 'challenge',
77 'auth_codes', 'tokens', 'clients', 'profile_check', 'host', 'conversation'];
79 $tables = DBA::selectToArray('INFORMATION_SCHEMA.TABLES', ['TABLE_NAME'],
80 ['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_TYPE' => 'BASE TABLE']);
83 echo DI::l10n()->t('No unused tables found.');
88 echo DI::l10n()->t('These tables are not used for friendica and will be deleted when you execute "dbstructure drop -e":') . "\n\n";
91 foreach ($old_tables as $table) {
92 if (in_array($table, array_column($tables, 'TABLE_NAME'))) {
94 $sql = 'DROP TABLE ' . DBA::quoteIdentifier($table) . ';';
97 $result = DBA::e($sql);
98 if (!DBA::isResult($result)) {
99 self::printUpdateError($sql);
109 * Converts all tables from MyISAM/InnoDB Antelope to InnoDB Barracuda
111 public static function convertToInnoDB()
113 $tables = DBA::selectToArray(
114 'information_schema.tables',
116 ['engine' => 'MyISAM', 'table_schema' => DBA::databaseName()]
119 $tables = array_merge($tables, DBA::selectToArray(
120 'information_schema.tables',
122 ['engine' => 'InnoDB', 'ROW_FORMAT' => ['COMPACT', 'REDUNDANT'], 'table_schema' => DBA::databaseName()]
125 if (!DBA::isResult($tables)) {
126 echo DI::l10n()->t('There are no tables on MyISAM or InnoDB with the Antelope file format.') . "\n";
130 foreach ($tables as $table) {
131 $sql = "ALTER TABLE " . DBA::quoteIdentifier($table['table_name']) . " ENGINE=InnoDB ROW_FORMAT=DYNAMIC;";
134 $result = DBA::e($sql);
135 if (!DBA::isResult($result)) {
136 self::printUpdateError($sql);
142 * Print out database error messages
144 * @param string $message Message to be added to the error message
146 * @return string Error message
148 private static function printUpdateError(string $message): string
150 echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
151 DBA::errorNo(), DBA::errorMessage());
153 return DI::l10n()->t('Errors encountered performing database changes: ') . $message . EOL;
157 * Perform a database structure dryrun (means: just simulating)
159 * @return string Empty string if the update is successful, error messages otherwise
162 public static function dryRun(): string
164 return self::update(true, false);
168 * Updates DB structure and returns eventual errors messages
170 * @param bool $enable_maintenance_mode Set the maintenance mode
171 * @param bool $verbose Display the SQL commands
173 * @return string Empty string if the update is successful, error messages otherwise
176 public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false): string
178 if ($enable_maintenance_mode) {
179 DI::config()->set('system', 'maintenance', 1);
182 $status = self::update($verbose, true);
184 if ($enable_maintenance_mode) {
185 DI::config()->set('system', 'maintenance', 0);
186 DI::config()->set('system', 'maintenance_reason', '');
193 * Updates DB structure from the installation and returns eventual errors messages
195 * @return string Empty string if the update is successful, error messages otherwise
198 public static function install(): string
200 return self::update(false, true, true);
204 * Updates DB structure and returns eventual errors messages
206 * @param bool $verbose
207 * @param bool $action Whether to actually apply the update
208 * @param bool $install Is this the initial update during the installation?
209 * @param array $tables An array of the database tables
210 * @param array $definition An array of the definition tables
211 * @return string Empty string if the update is successful, error messages otherwise
214 private static function update(bool $verbose, bool $action, bool $install = false, array $tables = null, array $definition = null): string
216 $in_maintenance_mode = DI::config()->get('system', 'maintenance');
218 if ($action && !$install && self::isUpdating()) {
219 return DI::l10n()->t('Another database update is currently running.');
222 if ($in_maintenance_mode) {
223 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: Database update', DateTimeFormat::utcNow() . ' ' . date('e')));
226 // ensure that all initial values exist. This test has to be done prior and after the structure check.
227 // Prior is needed if the specific tables already exists - after is needed when they had been created.
228 self::checkInitialValues();
232 Logger::info('updating structure');
234 // Get the current structure
237 if (is_null($tables)) {
238 $tables = DBA::toArray(DBA::p("SHOW TABLES"));
241 if (DBA::isResult($tables)) {
242 foreach ($tables as $table) {
243 $table = current($table);
245 Logger::info('updating structure', ['table' => $table]);
246 $database[$table] = self::tableStructure($table);
250 // Get the definition
251 if (is_null($definition)) {
252 $definition = DI::dbaDefinition()->getAll();
255 // MySQL >= 5.7.4 doesn't support the IGNORE keyword in ALTER TABLE statements
256 if ((version_compare(DBA::serverInfo(), '5.7.4') >= 0) &&
257 !(strpos(DBA::serverInfo(), 'MariaDB') !== false)) {
264 foreach ($definition as $name => $structure) {
265 $is_new_table = false;
267 if (!isset($database[$name])) {
268 $sql = DbaDefinitionSqlWriter::createTable($name, $structure, $verbose, $action);
274 if (!DBA::isResult($r)) {
275 $errors .= self::printUpdateError($name);
278 $is_new_table = true;
281 * Drop the index if it isn't present in the definition
282 * or the definition differ from current status
283 * and index name doesn't start with "local_"
285 foreach ($database[$name]["indexes"] as $indexName => $fieldNames) {
286 $current_index_definition = implode(",", $fieldNames);
287 if (isset($structure["indexes"][$indexName])) {
288 $new_index_definition = implode(",", $structure["indexes"][$indexName]);
290 $new_index_definition = "__NOT_SET__";
292 if ($current_index_definition != $new_index_definition && substr($indexName, 0, 6) != 'local_') {
293 $sql2 = DbaDefinitionSqlWriter::dropIndex($indexName);
295 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
297 $sql3 .= ", " . $sql2;
301 // Compare the field structure field by field
302 foreach ($structure["fields"] as $fieldName => $parameters) {
303 if (!isset($database[$name]["fields"][$fieldName])) {
304 $sql2 = DbaDefinitionSqlWriter::addTableField($fieldName, $parameters);
306 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
308 $sql3 .= ", " . $sql2;
311 // Compare the field definition
312 $field_definition = $database[$name]["fields"][$fieldName];
314 // Remove the relation data that is used for the referential integrity
315 unset($parameters['relation']);
316 unset($parameters['foreign']);
318 // We change the collation after the indexes had been changed.
319 // This is done to avoid index length problems.
320 // So here we always ensure that there is no need to change it.
321 unset($parameters['Collation']);
322 unset($field_definition['Collation']);
324 // Only update the comment when it is defined
325 if (!isset($parameters['comment'])) {
326 $parameters['comment'] = "";
329 $current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
330 $new_field_definition = DBA::cleanQuery(implode(",", $parameters));
331 if ($current_field_definition != $new_field_definition) {
332 $sql2 = DbaDefinitionSqlWriter::modifyTableField($fieldName, $parameters);
334 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
336 $sql3 .= ", " . $sql2;
344 * Create the index if the index don't exists in database
345 * or the definition differ from the current status.
346 * Don't create keys if table is new
348 if (!$is_new_table) {
349 foreach ($structure["indexes"] as $indexName => $fieldNames) {
350 if (isset($database[$name]["indexes"][$indexName])) {
351 $current_index_definition = implode(",", $database[$name]["indexes"][$indexName]);
353 $current_index_definition = "__NOT_SET__";
355 $new_index_definition = implode(",", $fieldNames);
356 if ($current_index_definition != $new_index_definition) {
357 $sql2 = DbaDefinitionSqlWriter::createIndex($indexName, $fieldNames);
361 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
363 $sql3 .= ", " . $sql2;
369 $existing_foreign_keys = $database[$name]['foreign_keys'];
372 // Compare the field structure field by field
373 foreach ($structure["fields"] as $fieldName => $parameters) {
374 if (empty($parameters['foreign'])) {
378 $constraint = self::getConstraintName($name, $fieldName, $parameters);
380 unset($existing_foreign_keys[$constraint]);
382 if (empty($database[$name]['foreign_keys'][$constraint])) {
383 $sql2 = DbaDefinitionSqlWriter::addForeignKey($fieldName, $parameters);
386 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
388 $sql3 .= ", " . $sql2;
393 foreach ($existing_foreign_keys as $param) {
394 $sql2 = DbaDefinitionSqlWriter::dropForeignKey($param['CONSTRAINT_NAME']);
397 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
399 $sql3 .= ", " . $sql2;
403 if (isset($database[$name]["table_status"]["TABLE_COMMENT"])) {
404 $structurecomment = $structure["comment"] ?? '';
405 if ($database[$name]["table_status"]["TABLE_COMMENT"] != $structurecomment) {
406 $sql2 = "COMMENT = '" . DBA::escape($structurecomment) . "'";
409 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
411 $sql3 .= ", " . $sql2;
416 if (isset($database[$name]["table_status"]["ENGINE"]) && isset($structure['engine'])) {
417 if ($database[$name]["table_status"]["ENGINE"] != $structure['engine']) {
418 $sql2 = "ENGINE = '" . DBA::escape($structure['engine']) . "'";
421 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
423 $sql3 .= ", " . $sql2;
428 if (isset($database[$name]["table_status"]["TABLE_COLLATION"])) {
429 if ($database[$name]["table_status"]["TABLE_COLLATION"] != 'utf8mb4_general_ci') {
430 $sql2 = "DEFAULT COLLATE utf8mb4_general_ci";
433 $sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
435 $sql3 .= ", " . $sql2;
444 // Now have a look at the field collations
445 // Compare the field structure field by field
446 foreach ($structure["fields"] as $fieldName => $parameters) {
447 // Compare the field definition
448 $field_definition = ($database[$name]["fields"][$fieldName] ?? '') ?: ['Collation' => ''];
450 // Define the default collation if not given
451 if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
452 $parameters['Collation'] = 'utf8mb4_general_ci';
454 $parameters['Collation'] = null;
457 if ($field_definition['Collation'] != $parameters['Collation']) {
458 $sql2 = DbaDefinitionSqlWriter::modifyTableField($fieldName, $parameters);
459 if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
460 $sql3 .= "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
462 $sql3 .= ", " . $sql2;
469 if (substr($sql3, -2, 2) != "; ") {
478 if ($in_maintenance_mode) {
479 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: updating %s table.', DateTimeFormat::utcNow() . ' ' . date('e'), $name));
483 if (!DBA::isResult($r)) {
484 $errors .= self::printUpdateError($sql3);
490 View::create(false, $action);
492 self::checkInitialValues();
494 if ($action && !$install) {
496 DI::config()->set('system', 'dbupdate', self::UPDATE_FAILED);
498 DI::config()->set('system', 'dbupdate', self::UPDATE_SUCCESSFUL);
506 * Returns an array with table structure information
508 * @param string $table Name of table
509 * @return array Table structure information
511 private static function tableStructure(string $table): array
513 // This query doesn't seem to be executable as a prepared statement
514 $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
516 $fields = DBA::selectToArray('INFORMATION_SCHEMA.COLUMNS',
517 ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
518 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
519 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
520 DBA::databaseName(), $table]);
522 $foreign_keys = DBA::selectToArray('INFORMATION_SCHEMA.KEY_COLUMN_USAGE',
523 ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
524 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
525 DBA::databaseName(), $table]);
527 $table_status = DBA::selectFirst('INFORMATION_SCHEMA.TABLES',
528 ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
529 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
530 DBA::databaseName(), $table]);
536 if (DBA::isResult($foreign_keys)) {
537 foreach ($foreign_keys as $foreign_key) {
538 $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]];
539 $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters);
540 $foreigndata[$constraint] = $foreign_key;
544 if (DBA::isResult($indexes)) {
545 foreach ($indexes as $index) {
546 if ($index["Key_name"] != "PRIMARY" && $index["Non_unique"] == "0" && !isset($indexdata[$index["Key_name"]])) {
547 $indexdata[$index["Key_name"]] = ["UNIQUE"];
550 if ($index["Index_type"] == "FULLTEXT" && !isset($indexdata[$index["Key_name"]])) {
551 $indexdata[$index["Key_name"]] = ["FULLTEXT"];
554 $column = $index["Column_name"];
556 if ($index["Sub_part"] != "") {
557 $column .= "(" . $index["Sub_part"] . ")";
560 $indexdata[$index["Key_name"]][] = $column;
565 if (DBA::isResult($fields)) {
566 foreach ($fields as $field) {
567 $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)'];
568 $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int'];
569 $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']);
571 $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE'];
573 if ($field['IS_NULLABLE'] == 'NO') {
574 $fielddata[$field['COLUMN_NAME']]['not null'] = true;
577 if (isset($field['COLUMN_DEFAULT']) && ($field['COLUMN_DEFAULT'] != 'NULL')) {
578 $fielddata[$field['COLUMN_NAME']]['default'] = trim($field['COLUMN_DEFAULT'], "'");
581 if (!empty($field['EXTRA'])) {
582 $fielddata[$field['COLUMN_NAME']]['extra'] = $field['EXTRA'];
585 if ($field['COLUMN_KEY'] == 'PRI') {
586 $fielddata[$field['COLUMN_NAME']]['primary'] = true;
589 $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME'];
590 $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT'];
595 'fields' => $fielddata,
596 'indexes' => $indexdata,
597 'foreign_keys' => $foreigndata,
598 'table_status' => $table_status
602 private static function getConstraintName(string $tableName, string $fieldName, array $parameters): string
604 $foreign_table = array_keys($parameters['foreign'])[0];
605 $foreign_field = array_values($parameters['foreign'])[0];
607 return $tableName . '-' . $fieldName. '-' . $foreign_table. '-' . $foreign_field;
611 * Renames columns or the primary key of a table
613 * @todo You cannot rename a primary key if "auto increment" is set
615 * @param string $table Table name
616 * @param array $columns Columns Syntax for Rename: [ $old1 => [ $new1, $type1 ], $old2 => [ $new2, $type2 ], ... ]
617 * Syntax for Primary Key: [ $col1, $col2, ...]
618 * @param int $type The type of renaming (Default is Column)
620 * @return boolean Was the renaming successful?
623 public static function rename(string $table, array $columns, int $type = self::RENAME_COLUMN): bool
625 if (empty($table) || empty($columns)) {
629 if (!is_array($columns)) {
633 $table = DBA::escape($table);
635 $sql = "ALTER TABLE `" . $table . "`";
637 case self::RENAME_COLUMN:
638 if (!self::existsColumn($table, array_keys($columns))) {
641 $sql .= implode(',', array_map(
642 function ($to, $from) {
643 return " CHANGE `" . $from . "` `" . $to[0] . "` " . $to[1];
649 case self::RENAME_PRIMARY_KEY:
650 if (!self::existsColumn($table, $columns)) {
653 $sql .= " DROP PRIMARY KEY, ADD PRIMARY KEY(`" . implode('`, `', $columns) . "`)";
661 $stmt = DBA::p($sql);
663 if (is_bool($stmt)) {
675 * Check if the columns of the table exists
677 * @param string $table Table name
678 * @param array $columns Columns to check ( Syntax: [ $col1, $col2, .. ] )
680 * @return boolean Does the table exist?
683 public static function existsColumn(string $table, array $columns = []): bool
689 if (is_null($columns) || empty($columns)) {
690 return self::existsTable($table);
693 $table = DBA::escape($table);
695 foreach ($columns as $column) {
696 $sql = "SHOW COLUMNS FROM `" . $table . "` LIKE '" . $column . "';";
698 $stmt = DBA::p($sql);
700 if (is_bool($stmt)) {
703 $retval = (DBA::numRows($stmt) > 0);
717 * Check if a foreign key exists for the given table field
719 * @param string $table Table name
720 * @param string $field Field name
721 * @return boolean Wether a foreign key exists
723 public static function existsForeignKeyForField(string $table, string $field): bool
725 return DBA::exists('INFORMATION_SCHEMA.KEY_COLUMN_USAGE',
726 ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
727 DBA::databaseName(), $table, $field]);
731 * Check if a table exists
733 * @param string $table Single table name (please loop yourself)
734 * @return boolean Does the table exist?
737 public static function existsTable(string $table): bool
743 $condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
745 return DBA::exists('information_schema.tables', $condition);
749 * Returns the columns of a table
751 * @param string $table Table name
753 * @return array An array of the table columns
756 public static function getColumns(string $table): array
758 $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
759 return DBA::toArray($stmtColumns);
763 * Check if initial database values do exist - or create them
765 * @param bool $verbose Whether to output messages
768 public static function checkInitialValues(bool $verbose = false)
770 if (self::existsTable('verb')) {
771 if (!DBA::exists('verb', ['id' => 1])) {
772 foreach (Item::ACTIVITIES as $index => $activity) {
773 DBA::insert('verb', ['id' => $index + 1, 'name' => $activity], Database::INSERT_IGNORE);
776 echo "verb: activities added\n";
778 } elseif ($verbose) {
779 echo "verb: activities already added\n";
782 if (!DBA::exists('verb', ['id' => 0])) {
783 DBA::insert('verb', ['name' => '']);
784 $lastid = DBA::lastInsertId();
786 DBA::update('verb', ['id' => 0], ['id' => $lastid]);
788 echo "Zero verb added\n";
791 } elseif ($verbose) {
792 echo "Zero verb already added\n";
794 } elseif ($verbose) {
795 echo "verb: Table not found\n";
798 if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) {
801 'page-flags' => User::PAGE_FLAGS_SOAPBOX,
802 'account-type' => User::ACCOUNT_TYPE_RELAY,
804 DBA::insert('user', $user);
805 $lastid = DBA::lastInsertId();
807 DBA::update('user', ['uid' => 0], ['uid' => $lastid]);
809 echo "Zero user added\n";
812 } elseif (self::existsTable('user') && $verbose) {
813 echo "Zero user already added\n";
814 } elseif ($verbose) {
815 echo "user: Table not found\n";
818 if (self::existsTable('contact') && !DBA::exists('contact', ['id' => 0])) {
819 DBA::insert('contact', ['nurl' => '']);
820 $lastid = DBA::lastInsertId();
822 DBA::update('contact', ['id' => 0], ['id' => $lastid]);
824 echo "Zero contact added\n";
827 } elseif (self::existsTable('contact') && $verbose) {
828 echo "Zero contact already added\n";
829 } elseif ($verbose) {
830 echo "contact: Table not found\n";
833 if (self::existsTable('tag') && !DBA::exists('tag', ['id' => 0])) {
834 DBA::insert('tag', ['name' => '']);
835 $lastid = DBA::lastInsertId();
837 DBA::update('tag', ['id' => 0], ['id' => $lastid]);
839 echo "Zero tag added\n";
842 } elseif (self::existsTable('tag') && $verbose) {
843 echo "Zero tag already added\n";
844 } elseif ($verbose) {
845 echo "tag: Table not found\n";
848 if (self::existsTable('permissionset')) {
849 if (!DBA::exists('permissionset', ['id' => 0])) {
850 DBA::insert('permissionset', ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']);
851 $lastid = DBA::lastInsertId();
853 DBA::update('permissionset', ['id' => 0], ['id' => $lastid]);
855 echo "Zero permissionset added\n";
858 } elseif ($verbose) {
859 echo "Zero permissionset already added\n";
861 if (self::existsTable('item') && !self::existsForeignKeyForField('item', 'psid')) {
862 $sets = DBA::p("SELECT `psid`, `item`.`uid`, `item`.`private` FROM `item`
863 LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`
864 WHERE `permissionset`.`id` IS NULL AND NOT `psid` IS NULL");
865 while ($set = DBA::fetch($sets)) {
866 if (($set['private'] == Item::PRIVATE) && ($set['uid'] != 0)) {
867 $owner = User::getOwnerDataById($set['uid']);
869 $permission = '<' . $owner['id'] . '>';
876 $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission,
877 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => ''];
878 DBA::insert('permissionset', $fields);
882 } elseif ($verbose) {
883 echo "permissionset: Table not found\n";
886 if (self::existsTable('tokens') && self::existsTable('clients') && !self::existsForeignKeyForField('tokens', 'client_id')) {
887 $tokens = DBA::p("SELECT `tokens`.`id` FROM `tokens`
888 LEFT JOIN `clients` ON `clients`.`client_id` = `tokens`.`client_id`
889 WHERE `clients`.`client_id` IS NULL");
890 while ($token = DBA::fetch($tokens)) {
891 DBA::delete('tokens', ['id' => $token['id']]);
898 * Checks if a database update is currently running
902 private static function isUpdating(): bool
906 $processes = DBA::select('information_schema.processlist', ['info'], [
907 'db' => DBA::databaseName(),
908 'command' => ['Query', 'Execute']
911 while ($process = DBA::fetch($processes)) {
912 $parts = explode(' ', $process['info']);
913 if (in_array(strtolower(array_shift($parts)), ['alter', 'create', 'drop', 'rename'])) {
918 DBA::close($processes);