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