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