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