3 * @copyright Copyright (C) 2020, Friendica
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\Network\HTTPException\InternalServerErrorException;
30 use Friendica\Util\Strings;
38 * Function to check if the Database structure needs an update.
40 * @param string $basePath The base path of this application
41 * @param boolean $via_worker Is the check run via the worker?
42 * @param App\Mode $mode The current app mode
44 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
46 public static function check(string $basePath, bool $via_worker, App\Mode $mode)
48 if (!DBA::connected()) {
52 // Don't check the status if the last update was failed
53 if (DI::config()->get('system', 'update', Update::SUCCESS, true) == Update::FAILED) {
57 $build = DI::config()->get('system', 'build');
60 DI::config()->set('system', 'build', DB_UPDATE_VERSION - 1);
61 $build = DB_UPDATE_VERSION - 1;
64 // We don't support upgrading from very old versions anymore
65 if ($build < NEW_TABLE_STRUCTURE_VERSION) {
66 $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);
67 if (DI::mode()->getExecutor() == Mode::INDEX) {
70 throw new InternalServerErrorException($error);
74 // The postupdate has to completed version 1281 for the new post views to take over
75 $postupdate = DI::config()->get("system", "post_update_version");
76 if ($postupdate < NEW_TABLE_STRUCTURE_VERSION) {
77 $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);
78 if (DI::mode()->getExecutor() == Mode::INDEX) {
81 throw new InternalServerErrorException($error);
85 if ($build < DB_UPDATE_VERSION) {
87 // Calling the database update directly via the worker enables us to perform database changes to the workerqueue table itself.
88 // This is a fallback, since normally the database update will be performed by a worker job.
89 // This worker job doesn't work for changes to the "workerqueue" table itself.
92 Worker::add(PRIORITY_CRITICAL, 'DBUpdate');
98 * Automatic database updates
100 * @param string $basePath The base path of this application
101 * @param bool $force Force the Update-Check even if the database version doesn't match
102 * @param bool $override Overrides any running/stuck updates
103 * @param bool $verbose Run the Update-Check verbose
104 * @param bool $sendMail Sends a Mail to the administrator in case of success/failure
106 * @return string Empty string if the update is successful, error messages otherwise
107 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
109 public static function run(string $basePath, bool $force = false, bool $override = false, bool $verbose = false, bool $sendMail = true)
111 // In force mode, we release the dbupdate lock first
112 // Necessary in case of an stuck update
114 DI::lock()->release('dbupdate', true);
117 $build = DI::config()->get('system', 'build', null, true);
119 if (empty($build) || ($build > DB_UPDATE_VERSION)) {
120 $build = DB_UPDATE_VERSION - 1;
121 DI::config()->set('system', 'build', $build);
124 if ($build != DB_UPDATE_VERSION || $force) {
125 require_once 'update.php';
127 $stored = intval($build);
128 $current = intval(DB_UPDATE_VERSION);
129 if ($stored < $current || $force) {
130 DI::config()->load('database');
132 // Compare the current structure with the defined structure
133 // If the Lock is acquired, never release it automatically to avoid double updates
134 if (DI::lock()->acquire('dbupdate', 0, Cache\Duration::INFINITE)) {
136 Logger::notice('Update starting.', ['from' => $stored, 'to' => $current]);
138 // Checks if the build changed during Lock acquiring (so no double update occurs)
139 $retryBuild = DI::config()->get('system', 'build', null, true);
140 if ($retryBuild !== $build) {
141 Logger::notice('Update already done.', ['from' => $stored, 'to' => $current]);
142 DI::lock()->release('dbupdate');
146 // run the pre_update_nnnn functions in update.php
147 for ($version = $stored + 1; $version <= $current; $version++) {
148 Logger::notice('Execute pre update.', ['version' => $version]);
149 $r = self::runUpdateFunction($version, 'pre_update', $sendMail);
151 Logger::warning('Pre update failed', ['version' => $version]);
152 DI::config()->set('system', 'update', Update::FAILED);
153 DI::lock()->release('dbupdate');
156 Logger::notice('Pre update executed.', ['version' => $version]);
160 // update the structure in one call
161 Logger::notice('Execute structure update');
162 $retval = DBStructure::update($basePath, $verbose, true);
163 if (!empty($retval)) {
170 Logger::error('Update ERROR.', ['from' => $stored, 'to' => $current, 'retval' => $retval]);
171 DI::config()->set('system', 'update', Update::FAILED);
172 DI::lock()->release('dbupdate');
175 Logger::notice('Database structure update finished.', ['from' => $stored, 'to' => $current]);
178 // run the update_nnnn functions in update.php
179 for ($version = $stored + 1; $version <= $current; $version++) {
180 Logger::notice('Execute post update.', ['version' => $version]);
181 $r = self::runUpdateFunction($version, 'update', $sendMail);
183 Logger::warning('Post update failed', ['version' => $version]);
184 DI::config()->set('system', 'update', Update::FAILED);
185 DI::lock()->release('dbupdate');
188 DI::config()->set('system', 'build', $version);
189 Logger::notice('Post update executed.', ['version' => $version]);
193 DI::config()->set('system', 'build', $current);
194 DI::config()->set('system', 'update', Update::SUCCESS);
195 DI::lock()->release('dbupdate');
197 Logger::notice('Update success.', ['from' => $stored, 'to' => $current]);
199 self::updateSuccessful($stored, $current);
209 * Executes a specific update function
211 * @param int $version the DB version number of the function
212 * @param string $prefix the prefix of the function (update, pre_update)
213 * @param bool $sendMail whether to send emails on success/failure
215 * @return bool true, if the update function worked
216 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
218 public static function runUpdateFunction(int $version, string $prefix, bool $sendMail = true)
220 $funcname = $prefix . '_' . $version;
222 Logger::notice('Update function start.', ['function' => $funcname]);
224 if (function_exists($funcname)) {
225 // There could be a lot of processes running or about to run.
226 // We want exactly one process to run the update command.
227 // So store the fact that we're taking responsibility
228 // after first checking to see if somebody else already has.
229 // If the update fails or times-out completely you may need to
230 // delete the config entry to try again.
232 if (DI::lock()->acquire('dbupdate_function', 120, Cache\Duration::INFINITE)) {
234 // call the specific update
235 Logger::notice('Pre update function start.', ['function' => $funcname]);
236 $retval = $funcname();
237 Logger::notice('Update function done.', ['function' => $funcname]);
241 //send the administrator an e-mail
244 DI::l10n()->t('Update %s failed. See error logs.', $version)
247 Logger::error('Update function ERROR.', ['function' => $funcname, 'retval' => $retval]);
248 DI::lock()->release('dbupdate_function');
251 DI::lock()->release('dbupdate_function');
252 Logger::notice('Update function finished.', ['function' => $funcname]);
256 Logger::error('Locking failed.', ['function' => $funcname]);
260 Logger::notice('Update function skipped.', ['function' => $funcname]);
266 * send the email and do what is needed to do on update fails
268 * @param int $update_id number of failed update
269 * @param string $error_message error message
270 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
272 private static function updateFailed(int $update_id, string $error_message) {
273 //send the administrators an e-mail
274 $condition = ['email' => explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email'))), 'parent-uid' => 0];
275 $adminlist = DBA::select('user', ['uid', 'language', 'email'], $condition, ['order' => ['uid']]);
278 if (!DBA::isResult($adminlist)) {
279 Logger::warning('Cannot notify administrators .', ['update' => $update_id, 'message' => $error_message]);
287 // every admin could had different language
288 while ($admin = DBA::fetch($adminlist)) {
289 if (in_array($admin['email'], $sent)) {
292 $sent[] = $admin['email'];
294 $lang = $admin['language'] ?? 'en';
295 $l10n = DI::l10n()->withLang($lang);
297 $preamble = Strings::deindent($l10n->t("
298 The friendica developers released update %s recently,
299 but when I tried to install it, something went terribly wrong.
300 This needs to be fixed soon and I can't do it alone. Please contact a
301 friendica developer if you can not help me on your own. My database might be invalid.",
303 $body = $l10n->t('The error message is\n[pre]%s[/pre]', $error_message);
305 $email = DI::emailer()
307 ->withMessage($l10n->t('[Friendica Notify] Database update'), $preamble, $body)
309 ->withRecipient($admin['email'])
311 DI::emailer()->send($email);
314 Logger::alert('Database structure update failed.', ['error' => $error_message]);
318 * Send a mail to the administrator about the successful update
320 * @param integer $from_build
321 * @param integer $to_build
324 private static function updateSuccessful(int $from_build, int $to_build)
326 //send the administrators an e-mail
327 $condition = ['email' => explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email'))), 'parent-uid' => 0];
328 $adminlist = DBA::select('user', ['uid', 'language', 'email'], $condition, ['order' => ['uid']]);
330 if (DBA::isResult($adminlist)) {
333 // every admin could had different language
334 while ($admin = DBA::fetch($adminlist)) {
335 if (in_array($admin['email'], $sent)) {
338 $sent[] = $admin['email'];
340 $lang = (($admin['language']) ? $admin['language'] : 'en');
341 $l10n = DI::l10n()->withLang($lang);
343 $preamble = Strings::deindent($l10n->t('
344 The friendica database was successfully updated from %s to %s.',
345 $from_build, $to_build));
347 $email = DI::emailer()
349 ->withMessage($l10n->t('[Friendica Notify] Database update'), $preamble)
351 ->withRecipient($admin['email'])
353 DI::emailer()->send($email);
357 Logger::debug('Database structure update successful.');