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