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