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