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