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