]> git.mxchange.org Git - friendica.git/blob - src/Core/Update.php
Renamed Cache flag
[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                                 // Compare the current structure with the defined structure
73                                 // If the Lock is acquired, never release it automatically to avoid double updates
74                                 if (Lock::acquire('dbupdate', 120, Cache::INFINITE)) {
75
76                                         // run the pre_update_nnnn functions in update.php
77                                         for ($x = $stored + 1; $x <= $current; $x++) {
78                                                 $r = self::runUpdateFunction($x, 'pre_update');
79                                                 if (!$r) {
80                                                         break;
81                                                 }
82                                         }
83
84                                         // update the structure in one call
85                                         $retval = DBStructure::update($verbose, true);
86                                         if ($retval) {
87                                                 if ($sendMail) {
88                                                         self::updateFailed(
89                                                                 DB_UPDATE_VERSION,
90                                                                 $retval
91                                                         );
92                                                 }
93                                                 Lock::release('dbupdate');
94                                                 return $retval;
95                                         } else {
96                                                 Config::set('database', 'last_successful_update', $current);
97                                                 Config::set('database', 'last_successful_update_time', time());
98                                         }
99
100                                         // run the update_nnnn functions in update.php
101                                         for ($x = $stored + 1; $x <= $current; $x++) {
102                                                 $r = self::runUpdateFunction($x, 'update');
103                                                 if (!$r) {
104                                                         break;
105                                                 }
106                                         }
107
108                                         if ($sendMail) {
109                                                 self::updateSuccessfull($stored, $current);
110                                         }
111
112                                         Lock::release('dbupdate');
113                                 }
114                         }
115                 }
116
117                 return '';
118         }
119
120         /**
121          * Executes a specific update function
122          *
123          * @param int $x the DB version number of the function
124          * @param string $prefix the prefix of the function (update, pre_update)
125          *
126          * @return bool true, if the update function worked
127          */
128         public static function runUpdateFunction($x, $prefix)
129         {
130                 $funcname = $prefix . '_' . $x;
131
132                 if (function_exists($funcname)) {
133                         // There could be a lot of processes running or about to run.
134                         // We want exactly one process to run the update command.
135                         // So store the fact that we're taking responsibility
136                         // after first checking to see if somebody else already has.
137                         // If the update fails or times-out completely you may need to
138                         // delete the config entry to try again.
139
140                         if (Lock::acquire('dbupdate_function', 120,Cache::INFINITE)) {
141
142                                 // call the specific update
143                                 $retval = $funcname();
144
145                                 if ($retval) {
146                                         //send the administrator an e-mail
147                                         self::updateFailed(
148                                                 $x,
149                                                 L10n::t('Update %s failed. See error logs.', $x)
150                                         );
151                                         Lock::release('dbupdate_function');
152                                         return false;
153                                 } else {
154                                         Config::set('database', 'last_successful_update_function', $funcname);
155                                         Config::set('database', 'last_successful_update_function_time', time());
156
157                                         if ($prefix == 'update') {
158                                                 Config::set('system', 'build', $x);
159                                         }
160
161                                         Lock::release('dbupdate_function');
162                                         return true;
163                                 }
164                         }
165                 } else {
166                         logger('Skipping \'' . $funcname . '\' without executing', LOGGER_DEBUG);
167
168                         Config::set('database', 'last_successful_update_function', $funcname);
169                         Config::set('database', 'last_successful_update_function_time', time());
170
171                         if ($prefix == 'update') {
172                                 Config::set('system', 'build', $x);
173                         }
174
175                         return true;
176                 }
177         }
178
179         /**
180          * send the email and do what is needed to do on update fails
181          *
182          * @param int $update_id                number of failed update
183          * @param string $error_message error message
184          */
185         private static function updateFailed($update_id, $error_message) {
186                 //send the administrators an e-mail
187                 $admin_mail_list = "'".implode("','", array_map(['Friendica\Database\DBA', 'escape'], explode(",", str_replace(" ", "", Config::get('config', 'admin_email')))))."'";
188                 $adminlist = q("SELECT uid, language, email FROM user WHERE email IN (%s)",
189                         $admin_mail_list
190                 );
191
192                 // No valid result?
193                 if (!DBA::isResult($adminlist)) {
194                         logger(sprintf('Cannot notify administrators about update_id=%d, error_message=%s', $update_id, $error_message), LOGGER_INFO);
195
196                         // Don't continue
197                         return;
198                 }
199
200                 // every admin could had different language
201                 foreach ($adminlist as $admin) {
202                         $lang = (($admin['language'])?$admin['language']:'en');
203                         L10n::pushLang($lang);
204
205                         $preamble = deindent(L10n::t("
206                                 The friendica developers released update %s recently,
207                                 but when I tried to install it, something went terribly wrong.
208                                 This needs to be fixed soon and I can't do it alone. Please contact a
209                                 friendica developer if you can not help me on your own. My database might be invalid.",
210                                 $update_id));
211                         $body = L10n::t("The error message is\n[pre]%s[/pre]", $error_message);
212
213                         notification([
214                                         'uid'      => $admin['uid'],
215                                         'type'     => SYSTEM_EMAIL,
216                                         'to_email' => $admin['email'],
217                                         'preamble' => $preamble,
218                                         'body'     => $body,
219                                         'language' => $lang]
220                         );
221                         L10n::popLang();
222                 }
223
224                 //try the logger
225                 logger("CRITICAL: Database structure update failed: ".$error_message);
226         }
227
228         private static function updateSuccessfull($from_build, $to_build)
229         {
230                 //send the administrators an e-mail
231                 $admin_mail_list = "'".implode("','", array_map(['Friendica\Database\DBA', 'escape'], explode(",", str_replace(" ", "", Config::get('config', 'admin_email')))))."'";
232                 $adminlist = q("SELECT uid, language, email FROM user WHERE email IN (%s)",
233                         $admin_mail_list
234                 );
235
236                 if (DBA::isResult($adminlist)) {
237                         // every admin could had different language
238                         foreach ($adminlist as $admin) {
239                                 $lang = (($admin['language']) ? $admin['language'] : 'en');
240                                 L10n::pushLang($lang);
241
242                                 $preamble = deindent(L10n::t("
243                                         The friendica database was successfully updated from %s to %s.",
244                                         $from_build, $to_build));
245
246                                 notification([
247                                                 'uid' => $admin['uid'],
248                                                 'type' => SYSTEM_EMAIL,
249                                                 'to_email' => $admin['email'],
250                                                 'preamble' => $preamble,
251                                                 'body' => $preamble,
252                                                 'language' => $lang]
253                                 );
254                                 L10n::popLang();
255                         }
256                 }
257
258                 //try the logger
259                 logger("CRITICAL: Database structure update successful.", LOGGER_TRACE);
260         }
261 }