]> git.mxchange.org Git - friendica.git/blob - src/Core/Update.php
Funkwhale context file moved
[friendica.git] / src / Core / Update.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Core;
23
24 use Friendica\App;
25 use Friendica\App\Mode;
26 use Friendica\Database\DBA;
27 use Friendica\Database\DBStructure;
28 use Friendica\DI;
29 use Friendica\Network\HTTPException\InternalServerErrorException;
30 use Friendica\Util\DateTimeFormat;
31 use Friendica\Util\Strings;
32
33 class Update
34 {
35         const SUCCESS = 0;
36         const FAILED  = 1;
37
38         /**
39          * Function to check if the Database structure needs an update.
40          *
41          * @param string   $basePath   The base path of this application
42          * @param boolean  $via_worker Is the check run via the worker?
43          * @param App\Mode $mode       The current app mode
44          * @return void
45          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
46          */
47         public static function check(string $basePath, bool $via_worker, App\Mode $mode)
48         {
49                 if (!DBA::connected()) {
50                         return;
51                 }
52
53                 // Don't check the status if the last update was failed
54                 if (DI::config()->get('system', 'update', Update::SUCCESS, true) == Update::FAILED) {
55                         return;
56                 }
57
58                 $build = DI::config()->get('system', 'build');
59
60                 if (empty($build)) {
61                         DI::config()->set('system', 'build', DB_UPDATE_VERSION - 1);
62                         $build = DB_UPDATE_VERSION - 1;
63                 }
64
65                 // We don't support upgrading from very old versions anymore
66                 if ($build < NEW_TABLE_STRUCTURE_VERSION) {
67                         $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);
68                         if (DI::mode()->getExecutor() == Mode::INDEX) {
69                                 die($error);
70                         } else {
71                                 throw new InternalServerErrorException($error);
72                         }
73                 }
74
75                 // The postupdate has to completed version 1288 for the new post views to take over
76                 $postupdate = DI::config()->get('system', 'post_update_version', NEW_TABLE_STRUCTURE_VERSION);
77                 if ($postupdate < NEW_TABLE_STRUCTURE_VERSION) {
78                         $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);
79                         if (DI::mode()->getExecutor() == Mode::INDEX) {
80                                 die($error);
81                         } else {
82                                 throw new InternalServerErrorException($error);
83                         }
84                 }
85
86                 if ($build < DB_UPDATE_VERSION) {
87                         if ($via_worker) {
88                                 /*
89                                  * Calling the database update directly via the worker enables us to perform database changes to the workerqueue table itself.
90                                  * This is a fallback, since normally the database update will be performed by a worker job.
91                                  * This worker job doesn't work for changes to the "workerqueue" table itself.
92                                  */
93                                 self::run($basePath);
94                         } else {
95                                 Worker::add(PRIORITY_CRITICAL, 'DBUpdate');
96                         }
97                 }
98         }
99
100         /**
101          * Automatic database updates
102          *
103          * @param string $basePath The base path of this application
104          * @param bool   $force    Force the Update-Check even if the database version doesn't match
105          * @param bool   $override Overrides any running/stuck updates
106          * @param bool   $verbose  Run the Update-Check verbose
107          * @param bool   $sendMail Sends a Mail to the administrator in case of success/failure
108          * @return string Empty string if the update is successful, error messages otherwise
109          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
110          */
111         public static function run(string $basePath, bool $force = false, bool $override = false, bool $verbose = false, bool $sendMail = true): string
112         {
113                 // In force mode, we release the dbupdate lock first
114                 // Necessary in case of an stuck update
115                 if ($override) {
116                         DI::lock()->release('dbupdate', true);
117                 }
118
119                 $build = DI::config()->get('system', 'build', null, true);
120
121                 if (empty($build) || ($build > DB_UPDATE_VERSION)) {
122                         $build = DB_UPDATE_VERSION - 1;
123                         DI::config()->set('system', 'build', $build);
124                 }
125
126                 if ($build != DB_UPDATE_VERSION || $force) {
127                         require_once 'update.php';
128
129                         $stored = intval($build);
130                         $current = intval(DB_UPDATE_VERSION);
131                         if ($stored < $current || $force) {
132                                 DI::config()->load('database');
133
134                                 // Compare the current structure with the defined structure
135                                 // If the Lock is acquired, never release it automatically to avoid double updates
136                                 if (DI::lock()->acquire('dbupdate', 0, Cache\Enum\Duration::INFINITE)) {
137
138                                         Logger::notice('Update starting.', ['from' => $stored, 'to' => $current]);
139
140                                         // Checks if the build changed during Lock acquiring (so no double update occurs)
141                                         $retryBuild = DI::config()->get('system', 'build', null, true);
142                                         if ($retryBuild !== $build) {
143                                                 Logger::notice('Update already done.', ['from' => $stored, 'to' => $current]);
144                                                 DI::lock()->release('dbupdate');
145                                                 return '';
146                                         }
147
148                                         DI::config()->set('system', 'maintenance', 1);
149                 
150                                         // run the pre_update_nnnn functions in update.php
151                                         for ($version = $stored + 1; $version <= $current; $version++) {
152                                                 Logger::notice('Execute pre update.', ['version' => $version]);
153                                                 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: executing pre update %d',
154                                                         DateTimeFormat::utcNow() . ' ' . date('e'), $version));
155                                                 $r = self::runUpdateFunction($version, 'pre_update', $sendMail);
156                                                 if (!$r) {
157                                                         Logger::warning('Pre update failed', ['version' => $version]);
158                                                         DI::config()->set('system', 'update', Update::FAILED);
159                                                         DI::lock()->release('dbupdate');
160                                                         DI::config()->set('system', 'maintenance', 0);
161                                                         DI::config()->set('system', 'maintenance_reason', '');
162                                                         return $r;
163                                                 } else {
164                                                         Logger::notice('Pre update executed.', ['version' => $version]);
165                                                 }
166                                         }
167
168                                         // update the structure in one call
169                                         Logger::notice('Execute structure update');
170                                         $retval = DBStructure::performUpdate(false, $verbose);
171                                         if (!empty($retval)) {
172                                                 if ($sendMail) {
173                                                         self::updateFailed(
174                                                                 DB_UPDATE_VERSION,
175                                                                 $retval
176                                                         );
177                                                 }
178                                                 Logger::error('Update ERROR.', ['from' => $stored, 'to' => $current, 'retval' => $retval]);
179                                                 DI::config()->set('system', 'update', Update::FAILED);
180                                                 DI::lock()->release('dbupdate');
181                                                 DI::config()->set('system', 'maintenance', 0);
182                                                 DI::config()->set('system', 'maintenance_reason', '');
183                                                 return $retval;
184                                         } else {
185                                                 Logger::notice('Database structure update finished.', ['from' => $stored, 'to' => $current]);
186                                         }
187
188                                         // run the update_nnnn functions in update.php
189                                         for ($version = $stored + 1; $version <= $current; $version++) {
190                                                 Logger::notice('Execute post update.', ['version' => $version]);
191                                                 DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: executing post update %d',
192                                                         DateTimeFormat::utcNow() . ' ' . date('e'), $version));
193                                                 $r = self::runUpdateFunction($version, 'update', $sendMail);
194                                                 if (!$r) {
195                                                         Logger::warning('Post update failed', ['version' => $version]);
196                                                         DI::config()->set('system', 'update', Update::FAILED);
197                                                         DI::lock()->release('dbupdate');
198                                                         DI::config()->set('system', 'maintenance', 0);
199                                                         DI::config()->set('system', 'maintenance_reason', '');
200                                                         return $r;
201                                                 } else {
202                                                         DI::config()->set('system', 'build', $version);
203                                                         Logger::notice('Post update executed.', ['version' => $version]);
204                                                 }
205                                         }
206
207                                         DI::config()->set('system', 'build', $current);
208                                         DI::config()->set('system', 'update', Update::SUCCESS);
209                                         DI::lock()->release('dbupdate');
210                                         DI::config()->set('system', 'maintenance', 0);
211                                         DI::config()->set('system', 'maintenance_reason', '');
212
213                                         Logger::notice('Update success.', ['from' => $stored, 'to' => $current]);
214                                         if ($sendMail) {
215                                                 self::updateSuccessful($stored, $current);
216                                         }
217                                 } else {
218                                         Logger::warning('Update lock could not be acquired');
219                                 }
220                         }
221                 }
222
223                 return '';
224         }
225
226         /**
227          * Executes a specific update function
228          *
229          * @param int    $version  the DB version number of the function
230          * @param string $prefix   the prefix of the function (update, pre_update)
231          * @param bool   $sendMail whether to send emails on success/failure
232          * @return bool true, if the update function worked
233          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
234          */
235         public static function runUpdateFunction(int $version, string $prefix, bool $sendMail = true): bool
236         {
237                 $funcname = $prefix . '_' . $version;
238
239                 Logger::notice('Update function start.', ['function' => $funcname]);
240
241                 if (function_exists($funcname)) {
242                         // There could be a lot of processes running or about to run.
243                         // We want exactly one process to run the update command.
244                         // So store the fact that we're taking responsibility
245                         // after first checking to see if somebody else already has.
246                         // If the update fails or times-out completely you may need to
247                         // delete the config entry to try again.
248
249                         if (DI::lock()->acquire('dbupdate_function', 120, Cache\Enum\Duration::INFINITE)) {
250
251                                 // call the specific update
252                                 Logger::notice('Pre update function start.', ['function' => $funcname]);
253                                 $retval = $funcname();
254                                 Logger::notice('Update function done.', ['function' => $funcname]);
255
256                                 if ($retval) {
257                                         if ($sendMail) {
258                                                 //send the administrator an e-mail
259                                                 self::updateFailed(
260                                                         $version,
261                                                         DI::l10n()->t('Update %s failed. See error logs.', $version)
262                                                 );
263                                         }
264                                         Logger::error('Update function ERROR.', ['function' => $funcname, 'retval' => $retval]);
265                                         DI::lock()->release('dbupdate_function');
266                                         return false;
267                                 } else {
268                                         DI::lock()->release('dbupdate_function');
269                                         Logger::notice('Update function finished.', ['function' => $funcname]);
270                                         return true;
271                                 }
272                         } else {
273                                 Logger::error('Locking failed.', ['function' => $funcname]);
274                                 return false;
275                         }
276                 } else {
277                         Logger::notice('Update function skipped.', ['function' => $funcname]);
278                         return true;
279                 }
280         }
281
282         /**
283          * send the email and do what is needed to do on update fails
284          *
285          * @param int    $update_id     number of failed update
286          * @param string $error_message error message
287          * @return void
288          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
289          */
290         private static function updateFailed(int $update_id, string $error_message) {
291                 //send the administrators an e-mail
292                 $condition = ['email' => explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email'))), 'parent-uid' => 0];
293                 $adminlist = DBA::select('user', ['uid', 'language', 'email'], $condition, ['order' => ['uid']]);
294
295                 // No valid result?
296                 if (!DBA::isResult($adminlist)) {
297                         Logger::warning('Cannot notify administrators .', ['update' => $update_id, 'message' => $error_message]);
298
299                         // Don't continue
300                         return;
301                 }
302
303                 $sent = [];
304
305                 // every admin could had different language
306                 while ($admin = DBA::fetch($adminlist)) {
307                         if (in_array($admin['email'], $sent)) {
308                                 continue;
309                         }
310                         $sent[] = $admin['email'];
311
312                         $lang = $admin['language'] ?? 'en';
313                         $l10n = DI::l10n()->withLang($lang);
314
315                         $preamble = Strings::deindent($l10n->t("
316                                 The friendica developers released update %s recently,
317                                 but when I tried to install it, something went terribly wrong.
318                                 This needs to be fixed soon and I can't do it alone. Please contact a
319                                 friendica developer if you can not help me on your own. My database might be invalid.",
320                                 $update_id));
321                         $body     = $l10n->t('The error message is\n[pre]%s[/pre]', $error_message);
322
323                         $email = DI::emailer()
324                                 ->newSystemMail()
325                                 ->withMessage($l10n->t('[Friendica Notify] Database update'), $preamble, $body)
326                                 ->forUser($admin)
327                                 ->withRecipient($admin['email'])
328                                 ->build();
329                         DI::emailer()->send($email);
330                 }
331
332                 Logger::alert('Database structure update failed.', ['error' => $error_message]);
333         }
334
335         /**
336          * Send a mail to the administrator about the successful update
337          *
338          * @param integer $from_build
339          * @param integer $to_build
340          * @return void
341          */
342         private static function updateSuccessful(int $from_build, int $to_build)
343         {
344                 //send the administrators an e-mail
345                 $condition = ['email' => explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email'))), 'parent-uid' => 0];
346                 $adminlist = DBA::select('user', ['uid', 'language', 'email'], $condition, ['order' => ['uid']]);
347
348                 if (DBA::isResult($adminlist)) {
349                         $sent = [];
350
351                         // every admin could had different language
352                         while ($admin = DBA::fetch($adminlist)) {
353                                 if (in_array($admin['email'], $sent)) {
354                                         continue;
355                                 }
356                                 $sent[] = $admin['email'];
357
358                                 $lang = (($admin['language']) ? $admin['language'] : 'en');
359                                 $l10n = DI::l10n()->withLang($lang);
360
361                                 $preamble = Strings::deindent($l10n->t('
362                                         The friendica database was successfully updated from %s to %s.',
363                                         $from_build, $to_build));
364
365                                 $email = DI::emailer()
366                                         ->newSystemMail()
367                                         ->withMessage($l10n->t('[Friendica Notify] Database update'), $preamble)
368                                         ->forUser($admin)
369                                         ->withRecipient($admin['email'])
370                                         ->build();
371                                 DI::emailer()->send($email);
372                         }
373                 }
374
375                 Logger::debug('Database structure update successful.');
376         }
377 }