3 * @copyright Copyright (C) 2010-2023, 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\Core;
25 use Friendica\App\Mode;
26 use Friendica\Database\DBA;
27 use Friendica\Database\DBStructure;
29 use Friendica\Model\User;
30 use Friendica\Network\HTTPException\InternalServerErrorException;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Strings;
39 const NEW_TABLE_STRUCTURE_VERSION = 1288;
42 * Function to check if the Database structure needs an update.
44 * @param string $basePath The base path of this application
45 * @param boolean $via_worker Is the check run via the worker?
46 * @param App\Mode $mode The current app mode
48 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
50 public static function check(string $basePath, bool $via_worker)
52 if (!DBA::connected()) {
56 // Don't check the status if the last update was failed
57 if (DI::config()->get('system', 'update', Update::SUCCESS) == Update::FAILED) {
61 $build = DI::config()->get('system', 'build');
64 // legacy option - check if there's something in the Config table
65 if (DBStructure::existsTable('config')) {
66 $dbConfig = DBA::selectFirst('config', ['v'], ['cat' => 'system', 'k' => 'build']);
67 if (!empty($dbConfig)) {
68 $build = $dbConfig['v'];
73 DI::config()->set('system', 'build', DB_UPDATE_VERSION - 1);
74 $build = DB_UPDATE_VERSION - 1;
78 // We don't support upgrading from very old versions anymore
79 if ($build < self::NEW_TABLE_STRUCTURE_VERSION) {
80 $error = DI::l10n()->t('Updates from version %s are not supported. Please update at least to version 2021.01 and wait until the postupdate finished version 1383.', $build);
81 if (DI::mode()->getExecutor() == Mode::INDEX) {
84 throw new InternalServerErrorException($error);
88 // The postupdate has to completed version 1288 for the new post views to take over
89 $postupdate = DI::keyValue()->get('post_update_version') ?? self::NEW_TABLE_STRUCTURE_VERSION;
90 if ($postupdate < self::NEW_TABLE_STRUCTURE_VERSION) {
91 $error = DI::l10n()->t('Updates from postupdate version %s are not supported. Please update at least to version 2021.01 and wait until the postupdate finished version 1383.', $postupdate);
92 if (DI::mode()->getExecutor() == Mode::INDEX) {
95 throw new InternalServerErrorException($error);
99 if ($build < DB_UPDATE_VERSION) {
102 * Calling the database update directly via the worker enables us to perform database changes to the workerqueue table itself.
103 * This is a fallback, since normally the database update will be performed by a worker job.
104 * This worker job doesn't work for changes to the "workerqueue" table itself.
106 self::run($basePath);
108 Worker::add(Worker::PRIORITY_CRITICAL, 'DBUpdate');
114 * Automatic database updates
116 * @param string $basePath The base path of this application
117 * @param bool $force Force the Update-Check even if the database version doesn't match
118 * @param bool $override Overrides any running/stuck updates
119 * @param bool $verbose Run the Update-Check verbose
120 * @param bool $sendMail Sends a Mail to the administrator in case of success/failure
121 * @return string Empty string if the update is successful, error messages otherwise
122 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
124 public static function run(string $basePath, bool $force = false, bool $override = false, bool $verbose = false, bool $sendMail = true): string
126 // In force mode, we release the dbupdate lock first
127 // Necessary in case of an stuck update
129 DI::lock()->release('dbupdate', true);
132 $build = DI::config()->get('system', 'build');
135 // legacy option - check if there's something in the Config table
136 if (DBStructure::existsTable('config')) {
137 $dbConfig = DBA::selectFirst('config', ['v'], ['cat' => 'system', 'k' => 'build']);
138 if (!empty($dbConfig)) {
139 $build = $dbConfig['v'];
143 if (empty($build) || ($build > DB_UPDATE_VERSION)) {
144 DI::config()->set('system', 'build', DB_UPDATE_VERSION - 1);
145 $build = DB_UPDATE_VERSION - 1;
149 if ($build != DB_UPDATE_VERSION || $force) {
150 require_once 'update.php';
152 $stored = intval($build);
153 $current = intval(DB_UPDATE_VERSION);
154 if ($stored < $current || $force) {
155 DI::config()->reload();
157 // Compare the current structure with the defined structure
158 // If the Lock is acquired, never release it automatically to avoid double updates
159 if (DI::lock()->acquire('dbupdate', 0, Cache\Enum\Duration::INFINITE)) {
161 Logger::notice('Update starting.', ['from' => $stored, 'to' => $current]);
163 // Checks if the build changed during Lock acquiring (so no double update occurs)
164 $retryBuild = DI::config()->get('system', 'build');
165 if ($retryBuild !== $build) {
166 Logger::notice('Update already done.', ['from' => $stored, 'to' => $current]);
167 DI::lock()->release('dbupdate');
171 DI::config()->set('system', 'maintenance', 1);
173 // run the pre_update_nnnn functions in update.php
174 for ($version = $stored + 1; $version <= $current; $version++) {
175 Logger::notice('Execute pre update.', ['version' => $version]);
176 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: executing pre update %d',
177 DateTimeFormat::utcNow() . ' ' . date('e'), $version));
178 $r = self::runUpdateFunction($version, 'pre_update', $sendMail);
180 Logger::warning('Pre update failed', ['version' => $version]);
181 DI::config()->set('system', 'update', Update::FAILED);
182 DI::lock()->release('dbupdate');
183 DI::config()->beginTransaction()
184 ->set('system', 'maintenance', false)
185 ->delete('system', 'maintenance_reason')
189 Logger::notice('Pre update executed.', ['version' => $version]);
193 // update the structure in one call
194 Logger::notice('Execute structure update');
195 $retval = DBStructure::performUpdate(false, $verbose);
196 if (!empty($retval)) {
203 Logger::error('Update ERROR.', ['from' => $stored, 'to' => $current, 'retval' => $retval]);
204 DI::config()->set('system', 'update', Update::FAILED);
205 DI::lock()->release('dbupdate');
206 DI::config()->beginTransaction()
207 ->set('system', 'maintenance', false)
208 ->delete('system', 'maintenance_reason')
212 Logger::notice('Database structure update finished.', ['from' => $stored, 'to' => $current]);
215 // run the update_nnnn functions in update.php
216 for ($version = $stored + 1; $version <= $current; $version++) {
217 Logger::notice('Execute post update.', ['version' => $version]);
218 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: executing post update %d',
219 DateTimeFormat::utcNow() . ' ' . date('e'), $version));
220 $r = self::runUpdateFunction($version, 'update', $sendMail);
222 Logger::warning('Post update failed', ['version' => $version]);
223 DI::config()->set('system', 'update', Update::FAILED);
224 DI::lock()->release('dbupdate');
225 DI::config()->beginTransaction()
226 ->set('system', 'maintenance', false)
227 ->delete('system', 'maintenance_reason')
231 DI::config()->set('system', 'build', $version);
232 Logger::notice('Post update executed.', ['version' => $version]);
236 DI::config()->set('system', 'build', $current);
237 DI::config()->set('system', 'update', Update::SUCCESS);
238 DI::lock()->release('dbupdate');
239 DI::config()->beginTransaction()
240 ->set('system', 'maintenance', false)
241 ->delete('system', 'maintenance_reason')
244 Logger::notice('Update success.', ['from' => $stored, 'to' => $current]);
246 self::updateSuccessful($stored, $current);
249 Logger::warning('Update lock could not be acquired');
258 * Executes a specific update function
260 * @param int $version the DB version number of the function
261 * @param string $prefix the prefix of the function (update, pre_update)
262 * @param bool $sendMail whether to send emails on success/failure
263 * @return bool true, if the update function worked
264 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
266 public static function runUpdateFunction(int $version, string $prefix, bool $sendMail = true): bool
268 $funcname = $prefix . '_' . $version;
270 Logger::notice('Update function start.', ['function' => $funcname]);
272 if (function_exists($funcname)) {
273 // There could be a lot of processes running or about to run.
274 // We want exactly one process to run the update command.
275 // So store the fact that we're taking responsibility
276 // after first checking to see if somebody else already has.
277 // If the update fails or times-out completely you may need to
278 // delete the config entry to try again.
280 if (DI::lock()->acquire('dbupdate_function', 120, Cache\Enum\Duration::INFINITE)) {
282 // call the specific update
283 Logger::notice('Pre update function start.', ['function' => $funcname]);
284 $retval = $funcname();
285 Logger::notice('Update function done.', ['function' => $funcname]);
289 //send the administrator an e-mail
292 DI::l10n()->t('Update %s failed. See error logs.', $version)
295 Logger::error('Update function ERROR.', ['function' => $funcname, 'retval' => $retval]);
296 DI::lock()->release('dbupdate_function');
299 DI::lock()->release('dbupdate_function');
300 Logger::notice('Update function finished.', ['function' => $funcname]);
304 Logger::error('Locking failed.', ['function' => $funcname]);
308 Logger::notice('Update function skipped.', ['function' => $funcname]);
314 * send the email and do what is needed to do on update fails
316 * @param int $update_id number of failed update
317 * @param string $error_message error message
319 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
321 private static function updateFailed(int $update_id, string $error_message)
323 $adminEmails = User::getAdminListForEmailing(['uid', 'language', 'email']);
325 Logger::warning('Cannot notify administrators .', ['update' => $update_id, 'message' => $error_message]);
329 foreach($adminEmails as $admin) {
330 $l10n = DI::l10n()->withLang($admin['language'] ?: 'en');
332 $preamble = Strings::deindent($l10n->t("
333 The friendica developers released update %s recently,
334 but when I tried to install it, something went terribly wrong.
335 This needs to be fixed soon and I can't do it alone. Please contact a
336 friendica developer if you can not help me on your own. My database might be invalid.",
338 $body = $l10n->t('The error message is\n[pre]%s[/pre]', $error_message);
340 $email = DI::emailer()
342 ->withMessage($l10n->t('[Friendica Notify] Database update'), $preamble, $body)
344 ->withRecipient($admin['email'])
346 DI::emailer()->send($email);
349 Logger::alert('Database structure update failed.', ['error' => $error_message]);
353 * Send a mail to the administrator about the successful update
355 * @param integer $from_build
356 * @param integer $to_build
359 private static function updateSuccessful(int $from_build, int $to_build)
361 foreach(User::getAdminListForEmailing(['uid', 'language', 'email']) as $admin) {
362 $l10n = DI::l10n()->withLang($admin['language'] ?: 'en');
364 $preamble = Strings::deindent($l10n->t('
365 The friendica database was successfully updated from %s to %s.',
366 $from_build, $to_build));
368 $email = DI::emailer()
370 ->withMessage($l10n->t('[Friendica Notify] Database update'), $preamble)
372 ->withRecipient($admin['email'])
374 DI::emailer()->send($email);
377 Logger::debug('Database structure update successful.');