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