]> git.mxchange.org Git - friendica.git/blob - src/Core/Update.php
Remove confirm template obsolete uses (except for contacts)
[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($basePath, $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($basePath, $force = false, $override = false, $verbose = false, $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                                 Logger::notice('Update starting.', ['from' => $stored, 'to' => $current]);
115
116                                 // Compare the current structure with the defined structure
117                                 // If the Lock is acquired, never release it automatically to avoid double updates
118                                 if (DI::lock()->acquire('dbupdate', 120, Cache\Duration::INFINITE)) {
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 ($x = $stored + 1; $x <= $current; $x++) {
130                                                 $r = self::runUpdateFunction($x, 'pre_update', $sendMail);
131                                                 if (!$r) {
132                                                         Logger::warning('Pre update failed', ['version' => $x]);
133                                                         DI::config()->set('system', 'update', Update::FAILED);
134                                                         DI::lock()->release('dbupdate');
135                                                         return $r;
136                                                 }
137                                         }
138
139                                         // update the structure in one call
140                                         $retval = DBStructure::update($basePath, $verbose, true);
141                                         if (!empty($retval)) {
142                                                 if ($sendMail) {
143                                                         self::updateFailed(
144                                                                 DB_UPDATE_VERSION,
145                                                                 $retval
146                                                         );
147                                                 }
148                                                 Logger::error('Update ERROR.', ['from' => $stored, 'to' => $current, 'retval' => $retval]);
149                                                 DI::config()->set('system', 'update', Update::FAILED);
150                                                 DI::lock()->release('dbupdate');
151                                                 return $retval;
152                                         } else {
153                                                 DI::config()->set('database', 'last_successful_update', $current);
154                                                 DI::config()->set('database', 'last_successful_update_time', time());
155                                                 Logger::info('Update finished.', ['from' => $stored, 'to' => $current]);
156                                         }
157
158                                         // run the update_nnnn functions in update.php
159                                         for ($x = $stored + 1; $x <= $current; $x++) {
160                                                 $r = self::runUpdateFunction($x, 'update', $sendMail);
161                                                 if (!$r) {
162                                                         Logger::warning('Post update failed', ['version' => $x]);
163                                                         DI::config()->set('system', 'update', Update::FAILED);
164                                                         DI::lock()->release('dbupdate');
165                                                         return $r;
166                                                 }
167                                         }
168
169                                         Logger::notice('Update success.', ['from' => $stored, 'to' => $current]);
170                                         if ($sendMail) {
171                                                 self::updateSuccessfull($stored, $current);
172                                         }
173
174                                         DI::config()->set('system', 'update', Update::SUCCESS);
175                                         DI::lock()->release('dbupdate');
176                                 }
177                         }
178                 }
179
180                 return '';
181         }
182
183         /**
184          * Executes a specific update function
185          *
186          * @param int    $x        the DB version number of the function
187          * @param string $prefix   the prefix of the function (update, pre_update)
188          * @param bool   $sendMail whether to send emails on success/failure
189
190          * @return bool true, if the update function worked
191          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
192          */
193         public static function runUpdateFunction($x, $prefix, bool $sendMail = true)
194         {
195                 $funcname = $prefix . '_' . $x;
196
197                 Logger::info('Update function start.', ['function' => $funcname]);
198
199                 if (function_exists($funcname)) {
200                         // There could be a lot of processes running or about to run.
201                         // We want exactly one process to run the update command.
202                         // So store the fact that we're taking responsibility
203                         // after first checking to see if somebody else already has.
204                         // If the update fails or times-out completely you may need to
205                         // delete the config entry to try again.
206
207                         if (DI::lock()->acquire('dbupdate_function', 120, Cache\Duration::INFINITE)) {
208
209                                 // call the specific update
210                                 Logger::info('Pre update function start.', ['function' => $funcname]);
211                                 $retval = $funcname();
212                                 Logger::info('Update function done.', ['function' => $funcname]);
213
214                                 if ($retval) {
215                                         if ($sendMail) {
216                                                 //send the administrator an e-mail
217                                                 self::updateFailed(
218                                                         $x,
219                                                         DI::l10n()->t('Update %s failed. See error logs.', $x)
220                                                 );
221                                         }
222                                         Logger::error('Update function ERROR.', ['function' => $funcname, 'retval' => $retval]);
223                                         DI::lock()->release('dbupdate_function');
224                                         return false;
225                                 } else {
226                                         DI::config()->set('database', 'last_successful_update_function', $funcname);
227                                         DI::config()->set('database', 'last_successful_update_function_time', time());
228
229                                         if ($prefix == 'update') {
230                                                 DI::config()->set('system', 'build', $x);
231                                         }
232
233                                         DI::lock()->release('dbupdate_function');
234                                         Logger::info('Update function finished.', ['function' => $funcname]);
235                                         return true;
236                                 }
237                         } else {
238                                 Logger::error('Locking failed.', ['function' => $funcname]);
239                         }
240                 } else {
241                         Logger::info('Update function skipped.', ['function' => $funcname]);
242
243                         DI::config()->set('database', 'last_successful_update_function', $funcname);
244                         DI::config()->set('database', 'last_successful_update_function_time', time());
245
246                         if ($prefix == 'update') {
247                                 DI::config()->set('system', 'build', $x);
248                         }
249
250                         return true;
251                 }
252         }
253
254         /**
255          * send the email and do what is needed to do on update fails
256          *
257          * @param int    $update_id     number of failed update
258          * @param string $error_message error message
259          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
260          */
261         private static function updateFailed($update_id, $error_message) {
262                 //send the administrators an e-mail
263                 $condition = ['email' => explode(",", str_replace(" ", "", DI::config()->get('config', 'admin_email'))), 'parent-uid' => 0];
264                 $adminlist = DBA::select('user', ['uid', 'language', 'email'], $condition, ['order' => ['uid']]);
265
266                 // No valid result?
267                 if (!DBA::isResult($adminlist)) {
268                         Logger::warning('Cannot notify administrators .', ['update' => $update_id, 'message' => $error_message]);
269
270                         // Don't continue
271                         return;
272                 }
273
274                 $sent = [];
275
276                 // every admin could had different language
277                 while ($admin = DBA::fetch($adminlist)) {
278                         if (in_array($admin['email'], $sent)) {
279                                 continue;
280                         }
281                         $sent[] = $admin['email'];
282
283                         $lang = $admin['language'] ?? 'en';
284                         $l10n = DI::l10n()->withLang($lang);
285
286                         $preamble = Strings::deindent($l10n->t("
287                                 The friendica developers released update %s recently,
288                                 but when I tried to install it, something went terribly wrong.
289                                 This needs to be fixed soon and I can't do it alone. Please contact a
290                                 friendica developer if you can not help me on your own. My database might be invalid.",
291                                 $update_id));
292                         $body     = $l10n->t("The error message is\n[pre]%s[/pre]", $error_message);
293
294                         $email = DI::emailer()
295                                 ->newSystemMail()
296                                 ->withMessage($l10n->t('[Friendica Notify] Database update'), $preamble, $body)
297                                 ->forUser($admin)
298                                 ->withRecipient($admin['email'])
299                                 ->build();
300                         DI::emailer()->send($email);
301                 }
302
303                 //try the logger
304                 Logger::alert('Database structure update FAILED.', ['error' => $error_message]);
305         }
306
307         private static function updateSuccessfull($from_build, $to_build)
308         {
309                 //send the administrators an e-mail
310                 $condition = ['email' => explode(",", str_replace(" ", "", DI::config()->get('config', 'admin_email'))), 'parent-uid' => 0];
311                 $adminlist = DBA::select('user', ['uid', 'language', 'email'], $condition, ['order' => ['uid']]);
312
313                 if (DBA::isResult($adminlist)) {
314                         $sent = [];
315
316                         // every admin could had different language
317                         while ($admin = DBA::fetch($adminlist)) {
318                                 if (in_array($admin['email'], $sent)) {
319                                         continue;
320                                 }
321                                 $sent[] = $admin['email'];
322
323                                 $lang = (($admin['language']) ? $admin['language'] : 'en');
324                                 $l10n = DI::l10n()->withLang($lang);
325
326                                 $preamble = Strings::deindent($l10n->t("
327                                         The friendica database was successfully updated from %s to %s.",
328                                         $from_build, $to_build));
329
330                                 $email = DI::emailer()
331                                         ->newSystemMail()
332                                         ->withMessage($l10n->t('[Friendica Notify] Database update'), $preamble)
333                                         ->forUser($admin)
334                                         ->withRecipient($admin['email'])
335                                         ->build();
336                                 DI::emailer()->send($email);
337                         }
338                 }
339
340                 //try the logger
341                 Logger::debug('Database structure update successful.');
342         }
343 }