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