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