]> git.mxchange.org Git - friendica.git/blob - src/Core/Update.php
Add common relationship methods to Model\ContactRelation
[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', $sendMail);
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', $sendMail);
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          * @param bool   $sendMail whether to send emails on success/failure
187
188          * @return bool true, if the update function worked
189          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
190          */
191         public static function runUpdateFunction($x, $prefix, bool $sendMail = true)
192         {
193                 $funcname = $prefix . '_' . $x;
194
195                 Logger::info('Update function start.', ['function' => $funcname]);
196
197                 if (function_exists($funcname)) {
198                         // There could be a lot of processes running or about to run.
199                         // We want exactly one process to run the update command.
200                         // So store the fact that we're taking responsibility
201                         // after first checking to see if somebody else already has.
202                         // If the update fails or times-out completely you may need to
203                         // delete the config entry to try again.
204
205                         if (DI::lock()->acquire('dbupdate_function', 120, Cache\Duration::INFINITE)) {
206
207                                 // call the specific update
208                                 $retval = $funcname();
209
210                                 if ($retval) {
211                                         if ($sendMail) {
212                                                 //send the administrator an e-mail
213                                                 self::updateFailed(
214                                                         $x,
215                                                         DI::l10n()->t('Update %s failed. See error logs.', $x)
216                                                 );
217                                         }
218                                         Logger::error('Update function ERROR.', ['function' => $funcname, 'retval' => $retval]);
219                                         DI::lock()->release('dbupdate_function');
220                                         return false;
221                                 } else {
222                                         DI::config()->set('database', 'last_successful_update_function', $funcname);
223                                         DI::config()->set('database', 'last_successful_update_function_time', time());
224
225                                         if ($prefix == 'update') {
226                                                 DI::config()->set('system', 'build', $x);
227                                         }
228
229                                         DI::lock()->release('dbupdate_function');
230                                         Logger::info('Update function finished.', ['function' => $funcname]);
231                                         return true;
232                                 }
233                         }
234                 } else {
235                         Logger::info('Update function skipped.', ['function' => $funcname]);
236
237                         DI::config()->set('database', 'last_successful_update_function', $funcname);
238                         DI::config()->set('database', 'last_successful_update_function_time', time());
239
240                         if ($prefix == 'update') {
241                                 DI::config()->set('system', 'build', $x);
242                         }
243
244                         return true;
245                 }
246         }
247
248         /**
249          * send the email and do what is needed to do on update fails
250          *
251          * @param int    $update_id     number of failed update
252          * @param string $error_message error message
253          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
254          */
255         private static function updateFailed($update_id, $error_message) {
256                 //send the administrators an e-mail
257                 $condition = ['email' => explode(",", str_replace(" ", "", DI::config()->get('config', 'admin_email'))), 'parent-uid' => 0];
258                 $adminlist = DBA::select('user', ['uid', 'language', 'email'], $condition, ['order' => ['uid']]);
259
260                 // No valid result?
261                 if (!DBA::isResult($adminlist)) {
262                         Logger::warning('Cannot notify administrators .', ['update' => $update_id, 'message' => $error_message]);
263
264                         // Don't continue
265                         return;
266                 }
267
268                 $sent = [];
269
270                 // every admin could had different language
271                 while ($admin = DBA::fetch($adminlist)) {
272                         if (in_array($admin['email'], $sent)) {
273                                 continue;
274                         }
275                         $sent[] = $admin['email'];
276
277                         $lang = $admin['language'] ?? 'en';
278                         $l10n = DI::l10n()->withLang($lang);
279
280                         $preamble = Strings::deindent($l10n->t("
281                                 The friendica developers released update %s recently,
282                                 but when I tried to install it, something went terribly wrong.
283                                 This needs to be fixed soon and I can't do it alone. Please contact a
284                                 friendica developer if you can not help me on your own. My database might be invalid.",
285                                 $update_id));
286                         $body     = $l10n->t("The error message is\n[pre]%s[/pre]", $error_message);
287
288                         $email = DI::emailer()
289                                 ->newSystemMail()
290                                 ->withMessage($l10n->t('[Friendica Notify] Database update'), $preamble, $body)
291                                 ->forUser($admin)
292                                 ->withRecipient($admin['email'])
293                                 ->build();
294                         DI::emailer()->send($email);
295                 }
296
297                 //try the logger
298                 Logger::alert('Database structure update FAILED.', ['error' => $error_message]);
299         }
300
301         private static function updateSuccessfull($from_build, $to_build)
302         {
303                 //send the administrators an e-mail
304                 $condition = ['email' => explode(",", str_replace(" ", "", DI::config()->get('config', 'admin_email'))), 'parent-uid' => 0];
305                 $adminlist = DBA::select('user', ['uid', 'language', 'email'], $condition, ['order' => ['uid']]);
306
307                 if (DBA::isResult($adminlist)) {
308                         $sent = [];
309
310                         // every admin could had different language
311                         while ($admin = DBA::fetch($adminlist)) {
312                                 if (in_array($admin['email'], $sent)) {
313                                         continue;
314                                 }
315                                 $sent[] = $admin['email'];
316
317                                 $lang = (($admin['language']) ? $admin['language'] : 'en');
318                                 $l10n = DI::l10n()->withLang($lang);
319
320                                 $preamble = Strings::deindent($l10n->t("
321                                         The friendica database was successfully updated from %s to %s.",
322                                         $from_build, $to_build));
323
324                                 $email = DI::emailer()
325                                         ->newSystemMail()
326                                         ->withMessage($l10n->t('[Friendica Notify] Database update'), $preamble)
327                                         ->forUser($admin)
328                                         ->withRecipient($admin['email'])
329                                         ->build();
330                                 DI::emailer()->send($email);
331                         }
332                 }
333
334                 //try the logger
335                 Logger::debug('Database structure update successful.');
336         }
337 }