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\Database\DBA;
26 use Friendica\Database\DBStructure;
28 use Friendica\Util\Strings;
36 * Function to check if the Database structure needs an update.
38 * @param string $basePath The base path of this application
39 * @param boolean $via_worker Is the check run via the worker?
40 * @param App\Mode $mode The current app mode
42 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
44 public static function check($basePath, $via_worker, App\Mode $mode)
46 if (!DBA::connected()) {
50 // Don't check the status if the last update was failed
51 if (DI::config()->get('system', 'update', Update::SUCCESS, true) == Update::FAILED) {
55 $build = DI::config()->get('system', 'build');
58 DI::config()->set('system', 'build', DB_UPDATE_VERSION - 1);
59 $build = DB_UPDATE_VERSION - 1;
62 // We don't support upgrading from very old versions anymore
63 if ($build < NEW_UPDATE_ROUTINE_VERSION) {
64 die('You try to update from a version prior to database version 1170. The direct upgrade path is not supported. Please update to version 3.5.4 before updating to this version.');
67 if ($build < DB_UPDATE_VERSION) {
69 // Calling the database update directly via the worker enables us to perform database changes to the workerqueue table itself.
70 // This is a fallback, since normally the database update will be performed by a worker job.
71 // This worker job doesn't work for changes to the "workerqueue" table itself.
74 Worker::add(PRIORITY_CRITICAL, 'DBUpdate');
80 * Automatic database updates
82 * @param string $basePath The base path of this application
83 * @param bool $force Force the Update-Check even if the database version doesn't match
84 * @param bool $override Overrides any running/stuck updates
85 * @param bool $verbose Run the Update-Check verbose
86 * @param bool $sendMail Sends a Mail to the administrator in case of success/failure
88 * @return string Empty string if the update is successful, error messages otherwise
89 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
91 public static function run($basePath, $force = false, $override = false, $verbose = false, $sendMail = true)
93 // In force mode, we release the dbupdate lock first
94 // Necessary in case of an stuck update
96 DI::lock()->release('dbupdate', true);
99 $build = DI::config()->get('system', 'build', null, true);
101 if (empty($build) || ($build > DB_UPDATE_VERSION)) {
102 $build = DB_UPDATE_VERSION - 1;
103 DI::config()->set('system', 'build', $build);
106 if ($build != DB_UPDATE_VERSION || $force) {
107 require_once 'update.php';
109 $stored = intval($build);
110 $current = intval(DB_UPDATE_VERSION);
111 if ($stored < $current || $force) {
112 DI::config()->load('database');
114 Logger::info('Update starting.', ['from' => $stored, 'to' => $current]);
116 // Compare the current structure with the defined structure
117 // If the Lock is acquired, never release it automatically to avoid double updates
118 if (DI::lock()->acquire('dbupdate', 120, Cache\Duration::INFINITE)) {
120 // Checks if the build changed during Lock acquiring (so no double update occurs)
121 $retryBuild = DI::config()->get('system', 'build', null, true);
122 if ($retryBuild !== $build) {
123 Logger::info('Update already done.', ['from' => $stored, 'to' => $current]);
124 DI::lock()->release('dbupdate');
128 // run the pre_update_nnnn functions in update.php
129 for ($x = $stored + 1; $x <= $current; $x++) {
130 $r = self::runUpdateFunction($x, 'pre_update');
132 DI::config()->set('system', 'update', Update::FAILED);
133 DI::lock()->release('dbupdate');
138 // update the structure in one call
139 $retval = DBStructure::update($basePath, $verbose, true);
140 if (!empty($retval)) {
147 Logger::error('Update ERROR.', ['from' => $stored, 'to' => $current, 'retval' => $retval]);
148 DI::config()->set('system', 'update', Update::FAILED);
149 DI::lock()->release('dbupdate');
152 DI::config()->set('database', 'last_successful_update', $current);
153 DI::config()->set('database', 'last_successful_update_time', time());
154 Logger::info('Update finished.', ['from' => $stored, 'to' => $current]);
157 // run the update_nnnn functions in update.php
158 for ($x = $stored + 1; $x <= $current; $x++) {
159 $r = self::runUpdateFunction($x, 'update');
161 DI::config()->set('system', 'update', Update::FAILED);
162 DI::lock()->release('dbupdate');
167 Logger::notice('Update success.', ['from' => $stored, 'to' => $current]);
169 self::updateSuccessfull($stored, $current);
172 DI::config()->set('system', 'update', Update::SUCCESS);
173 DI::lock()->release('dbupdate');
182 * Executes a specific update function
184 * @param int $x the DB version number of the function
185 * @param string $prefix the prefix of the function (update, pre_update)
187 * @return bool true, if the update function worked
188 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
190 public static function runUpdateFunction($x, $prefix)
192 $funcname = $prefix . '_' . $x;
194 Logger::info('Update function start.', ['function' => $funcname]);
196 if (function_exists($funcname)) {
197 // There could be a lot of processes running or about to run.
198 // We want exactly one process to run the update command.
199 // So store the fact that we're taking responsibility
200 // after first checking to see if somebody else already has.
201 // If the update fails or times-out completely you may need to
202 // delete the config entry to try again.
204 if (DI::lock()->acquire('dbupdate_function', 120, Cache\Duration::INFINITE)) {
206 // call the specific update
207 $retval = $funcname();
210 //send the administrator an e-mail
213 DI::l10n()->t('Update %s failed. See error logs.', $x)
215 Logger::error('Update function ERROR.', ['function' => $funcname, 'retval' => $retval]);
216 DI::lock()->release('dbupdate_function');
219 DI::config()->set('database', 'last_successful_update_function', $funcname);
220 DI::config()->set('database', 'last_successful_update_function_time', time());
222 if ($prefix == 'update') {
223 DI::config()->set('system', 'build', $x);
226 DI::lock()->release('dbupdate_function');
227 Logger::info('Update function finished.', ['function' => $funcname]);
232 Logger::info('Update function skipped.', ['function' => $funcname]);
234 DI::config()->set('database', 'last_successful_update_function', $funcname);
235 DI::config()->set('database', 'last_successful_update_function_time', time());
237 if ($prefix == 'update') {
238 DI::config()->set('system', 'build', $x);
246 * send the email and do what is needed to do on update fails
248 * @param int $update_id number of failed update
249 * @param string $error_message error message
250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
252 private static function updateFailed($update_id, $error_message) {
253 //send the administrators an e-mail
254 $condition = ['email' => explode(",", str_replace(" ", "", DI::config()->get('config', 'admin_email'))), 'parent-uid' => 0];
255 $adminlist = DBA::select('user', ['uid', 'language', 'email'], $condition, ['order' => ['uid']]);
258 if (!DBA::isResult($adminlist)) {
259 Logger::warning('Cannot notify administrators .', ['update' => $update_id, 'message' => $error_message]);
267 // every admin could had different language
268 while ($admin = DBA::fetch($adminlist)) {
269 if (in_array($admin['email'], $sent)) {
272 $sent[] = $admin['email'];
274 $lang = $admin['language'] ?? 'en';
275 $l10n = DI::l10n()->withLang($lang);
277 $preamble = Strings::deindent($l10n->t("
278 The friendica developers released update %s recently,
279 but when I tried to install it, something went terribly wrong.
280 This needs to be fixed soon and I can't do it alone. Please contact a
281 friendica developer if you can not help me on your own. My database might be invalid.",
283 $body = $l10n->t("The error message is\n[pre]%s[/pre]", $error_message);
285 $email = DI::emailer()
287 ->withMessage($l10n->t('[Friendica Notify] Database update'), $preamble, $body)
289 ->withRecipient($admin['email'])
291 DI::emailer()->send($email);
295 Logger::alert('Database structure update FAILED.', ['error' => $error_message]);
298 private static function updateSuccessfull($from_build, $to_build)
300 //send the administrators an e-mail
301 $condition = ['email' => explode(",", str_replace(" ", "", DI::config()->get('config', 'admin_email'))), 'parent-uid' => 0];
302 $adminlist = DBA::select('user', ['uid', 'language', 'email'], $condition, ['order' => ['uid']]);
304 if (DBA::isResult($adminlist)) {
307 // every admin could had different language
308 while ($admin = DBA::fetch($adminlist)) {
309 if (in_array($admin['email'], $sent)) {
312 $sent[] = $admin['email'];
314 $lang = (($admin['language']) ? $admin['language'] : 'en');
315 $l10n = DI::l10n()->withLang($lang);
317 $preamble = Strings::deindent($l10n->t("
318 The friendica database was successfully updated from %s to %s.",
319 $from_build, $to_build));
321 $email = DI::emailer()
323 ->withMessage($l10n->t('[Friendica Notify] Database update'), $preamble)
325 ->withRecipient($admin['email'])
327 DI::emailer()->send($email);
332 Logger::debug('Database structure update successful.');