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