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