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