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