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::notice('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::notice('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', $sendMail);
132 Logger::warning('Pre update failed', ['version' => $x]);
133 DI::config()->set('system', 'update', Update::FAILED);
134 DI::lock()->release('dbupdate');
139 // update the structure in one call
140 $retval = DBStructure::update($basePath, $verbose, true);
141 if (!empty($retval)) {
148 Logger::error('Update ERROR.', ['from' => $stored, 'to' => $current, 'retval' => $retval]);
149 DI::config()->set('system', 'update', Update::FAILED);
150 DI::lock()->release('dbupdate');
153 DI::config()->set('database', 'last_successful_update', $current);
154 DI::config()->set('database', 'last_successful_update_time', time());
155 Logger::info('Update finished.', ['from' => $stored, 'to' => $current]);
158 // run the update_nnnn functions in update.php
159 for ($x = $stored + 1; $x <= $current; $x++) {
160 $r = self::runUpdateFunction($x, 'update', $sendMail);
162 Logger::warning('Post update failed', ['version' => $x]);
163 DI::config()->set('system', 'update', Update::FAILED);
164 DI::lock()->release('dbupdate');
169 Logger::notice('Update success.', ['from' => $stored, 'to' => $current]);
171 self::updateSuccessfull($stored, $current);
174 DI::config()->set('system', 'update', Update::SUCCESS);
175 DI::lock()->release('dbupdate');
184 * Executes a specific update function
186 * @param int $x the DB version number of the function
187 * @param string $prefix the prefix of the function (update, pre_update)
188 * @param bool $sendMail whether to send emails on success/failure
190 * @return bool true, if the update function worked
191 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
193 public static function runUpdateFunction($x, $prefix, bool $sendMail = true)
195 $funcname = $prefix . '_' . $x;
197 Logger::info('Update function start.', ['function' => $funcname]);
199 if (function_exists($funcname)) {
200 // There could be a lot of processes running or about to run.
201 // We want exactly one process to run the update command.
202 // So store the fact that we're taking responsibility
203 // after first checking to see if somebody else already has.
204 // If the update fails or times-out completely you may need to
205 // delete the config entry to try again.
207 if (DI::lock()->acquire('dbupdate_function', 120, Cache\Duration::INFINITE)) {
209 // call the specific update
210 Logger::info('Pre update function start.', ['function' => $funcname]);
211 $retval = $funcname();
212 Logger::info('Update function done.', ['function' => $funcname]);
216 //send the administrator an e-mail
219 DI::l10n()->t('Update %s failed. See error logs.', $x)
222 Logger::error('Update function ERROR.', ['function' => $funcname, 'retval' => $retval]);
223 DI::lock()->release('dbupdate_function');
226 DI::config()->set('database', 'last_successful_update_function', $funcname);
227 DI::config()->set('database', 'last_successful_update_function_time', time());
229 if ($prefix == 'update') {
230 DI::config()->set('system', 'build', $x);
233 DI::lock()->release('dbupdate_function');
234 Logger::info('Update function finished.', ['function' => $funcname]);
238 Logger::error('Locking failed.', ['function' => $funcname]);
241 Logger::info('Update function skipped.', ['function' => $funcname]);
243 DI::config()->set('database', 'last_successful_update_function', $funcname);
244 DI::config()->set('database', 'last_successful_update_function_time', time());
246 if ($prefix == 'update') {
247 DI::config()->set('system', 'build', $x);
255 * send the email and do what is needed to do on update fails
257 * @param int $update_id number of failed update
258 * @param string $error_message error message
259 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
261 private static function updateFailed($update_id, $error_message) {
262 //send the administrators an e-mail
263 $condition = ['email' => explode(",", str_replace(" ", "", DI::config()->get('config', 'admin_email'))), 'parent-uid' => 0];
264 $adminlist = DBA::select('user', ['uid', 'language', 'email'], $condition, ['order' => ['uid']]);
267 if (!DBA::isResult($adminlist)) {
268 Logger::warning('Cannot notify administrators .', ['update' => $update_id, 'message' => $error_message]);
276 // every admin could had different language
277 while ($admin = DBA::fetch($adminlist)) {
278 if (in_array($admin['email'], $sent)) {
281 $sent[] = $admin['email'];
283 $lang = $admin['language'] ?? 'en';
284 $l10n = DI::l10n()->withLang($lang);
286 $preamble = Strings::deindent($l10n->t("
287 The friendica developers released update %s recently,
288 but when I tried to install it, something went terribly wrong.
289 This needs to be fixed soon and I can't do it alone. Please contact a
290 friendica developer if you can not help me on your own. My database might be invalid.",
292 $body = $l10n->t("The error message is\n[pre]%s[/pre]", $error_message);
294 $email = DI::emailer()
296 ->withMessage($l10n->t('[Friendica Notify] Database update'), $preamble, $body)
298 ->withRecipient($admin['email'])
300 DI::emailer()->send($email);
304 Logger::alert('Database structure update FAILED.', ['error' => $error_message]);
307 private static function updateSuccessfull($from_build, $to_build)
309 //send the administrators an e-mail
310 $condition = ['email' => explode(",", str_replace(" ", "", DI::config()->get('config', 'admin_email'))), 'parent-uid' => 0];
311 $adminlist = DBA::select('user', ['uid', 'language', 'email'], $condition, ['order' => ['uid']]);
313 if (DBA::isResult($adminlist)) {
316 // every admin could had different language
317 while ($admin = DBA::fetch($adminlist)) {
318 if (in_array($admin['email'], $sent)) {
321 $sent[] = $admin['email'];
323 $lang = (($admin['language']) ? $admin['language'] : 'en');
324 $l10n = DI::l10n()->withLang($lang);
326 $preamble = Strings::deindent($l10n->t("
327 The friendica database was successfully updated from %s to %s.",
328 $from_build, $to_build));
330 $email = DI::emailer()
332 ->withMessage($l10n->t('[Friendica Notify] Database update'), $preamble)
334 ->withRecipient($admin['email'])
336 DI::emailer()->send($email);
341 Logger::debug('Database structure update successful.');