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