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