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