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