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