3 namespace Friendica\Core;
6 use Friendica\Database\DBA;
7 use Friendica\Database\DBStructure;
8 use Friendica\Util\Strings;
16 * @brief Function to check if the Database structure needs an update.
18 * @param string $basePath The base path of this application
19 * @param boolean $via_worker Is the check run via the worker?
20 * @param App\Mode $mode The current app mode
22 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
24 public static function check($basePath, $via_worker, App\Mode $mode)
26 if (!DBA::connected()) {
30 // Don't check the status if the last update was failed
31 if (Config::get('system', 'update', Update::SUCCESS, true) == Update::FAILED) {
35 $build = Config::get('system', 'build');
38 Config::set('system', 'build', DB_UPDATE_VERSION - 1);
39 $build = DB_UPDATE_VERSION - 1;
42 // We don't support upgrading from very old versions anymore
43 if ($build < NEW_UPDATE_ROUTINE_VERSION) {
44 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.');
47 if ($build < DB_UPDATE_VERSION) {
49 // Calling the database update directly via the worker enables us to perform database changes to the workerqueue table itself.
50 // This is a fallback, since normally the database update will be performed by a worker job.
51 // This worker job doesn't work for changes to the "workerqueue" table itself.
54 Worker::add(PRIORITY_CRITICAL, 'DBUpdate');
60 * Automatic database updates
62 * @param string $basePath The base path of this application
63 * @param bool $force Force the Update-Check even if the database version doesn't match
64 * @param bool $override Overrides any running/stuck updates
65 * @param bool $verbose Run the Update-Check verbose
66 * @param bool $sendMail Sends a Mail to the administrator in case of success/failure
68 * @return string Empty string if the update is successful, error messages otherwise
69 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
71 public static function run($basePath, $force = false, $override = false, $verbose = false, $sendMail = true)
73 // In force mode, we release the dbupdate lock first
74 // Necessary in case of an stuck update
76 Lock::release('dbupdate', true);
79 $build = Config::get('system', 'build', null, true);
81 if (empty($build) || ($build > DB_UPDATE_VERSION)) {
82 $build = DB_UPDATE_VERSION - 1;
83 Config::set('system', 'build', $build);
86 if ($build != DB_UPDATE_VERSION || $force) {
87 require_once 'update.php';
89 $stored = intval($build);
90 $current = intval(DB_UPDATE_VERSION);
91 if ($stored < $current || $force) {
92 Config::load('database');
94 Logger::info('Update starting.', ['from' => $stored, 'to' => $current]);
96 // Compare the current structure with the defined structure
97 // If the Lock is acquired, never release it automatically to avoid double updates
98 if (Lock::acquire('dbupdate', 120, Cache::INFINITE)) {
100 // Checks if the build changed during Lock acquiring (so no double update occurs)
101 $retryBuild = Config::get('system', 'build', null, true);
102 if ($retryBuild !== $build) {
103 Logger::info('Update already done.', ['from' => $stored, 'to' => $current]);
104 Lock::release('dbupdate');
108 // run the pre_update_nnnn functions in update.php
109 for ($x = $stored + 1; $x <= $current; $x++) {
110 $r = self::runUpdateFunction($x, 'pre_update');
112 Config::set('system', 'update', Update::FAILED);
113 Lock::release('dbupdate');
118 // update the structure in one call
119 $retval = DBStructure::update($basePath, $verbose, true);
120 if (!empty($retval)) {
127 Logger::error('Update ERROR.', ['from' => $stored, 'to' => $current, 'retval' => $retval]);
128 Config::set('system', 'update', Update::FAILED);
129 Lock::release('dbupdate');
132 Config::set('database', 'last_successful_update', $current);
133 Config::set('database', 'last_successful_update_time', time());
134 Logger::info('Update finished.', ['from' => $stored, 'to' => $current]);
137 // run the update_nnnn functions in update.php
138 for ($x = $stored + 1; $x <= $current; $x++) {
139 $r = self::runUpdateFunction($x, 'update');
141 Config::set('system', 'update', Update::FAILED);
142 Lock::release('dbupdate');
147 Logger::notice('Update success.', ['from' => $stored, 'to' => $current]);
149 self::updateSuccessfull($stored, $current);
152 Config::set('system', 'update', Update::SUCCESS);
153 Lock::release('dbupdate');
162 * Executes a specific update function
164 * @param int $x the DB version number of the function
165 * @param string $prefix the prefix of the function (update, pre_update)
167 * @return bool true, if the update function worked
168 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
170 public static function runUpdateFunction($x, $prefix)
172 $funcname = $prefix . '_' . $x;
174 Logger::info('Update function start.', ['function' => $funcname]);
176 if (function_exists($funcname)) {
177 // There could be a lot of processes running or about to run.
178 // We want exactly one process to run the update command.
179 // So store the fact that we're taking responsibility
180 // after first checking to see if somebody else already has.
181 // If the update fails or times-out completely you may need to
182 // delete the config entry to try again.
184 if (Lock::acquire('dbupdate_function', 120,Cache::INFINITE)) {
186 // call the specific update
187 $retval = $funcname();
190 //send the administrator an e-mail
193 L10n::t('Update %s failed. See error logs.', $x)
195 Logger::error('Update function ERROR.', ['function' => $funcname, 'retval' => $retval]);
196 Lock::release('dbupdate_function');
199 Config::set('database', 'last_successful_update_function', $funcname);
200 Config::set('database', 'last_successful_update_function_time', time());
202 if ($prefix == 'update') {
203 Config::set('system', 'build', $x);
206 Lock::release('dbupdate_function');
207 Logger::info('Update function finished.', ['function' => $funcname]);
212 Logger::info('Update function skipped.', ['function' => $funcname]);
214 Config::set('database', 'last_successful_update_function', $funcname);
215 Config::set('database', 'last_successful_update_function_time', time());
217 if ($prefix == 'update') {
218 Config::set('system', 'build', $x);
226 * send the email and do what is needed to do on update fails
228 * @param int $update_id number of failed update
229 * @param string $error_message error message
230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
232 private static function updateFailed($update_id, $error_message) {
233 //send the administrators an e-mail
234 $condition = ['email' => explode(",", str_replace(" ", "", Config::get('config', 'admin_email'))), 'parent-uid' => 0];
235 $adminlist = DBA::select('user', ['uid', 'language', 'email'], $condition, ['order' => ['uid']]);
238 if (!DBA::isResult($adminlist)) {
239 Logger::warning('Cannot notify administrators .', ['update' => $update_id, 'message' => $error_message]);
247 // every admin could had different language
248 while ($admin = DBA::fetch($adminlist)) {
249 if (in_array($admin['email'], $sent)) {
252 $sent[] = $admin['email'];
254 $lang = (($admin['language'])?$admin['language']:'en');
255 L10n::pushLang($lang);
257 $preamble = Strings::deindent(L10n::t("
258 The friendica developers released update %s recently,
259 but when I tried to install it, something went terribly wrong.
260 This needs to be fixed soon and I can't do it alone. Please contact a
261 friendica developer if you can not help me on your own. My database might be invalid.",
263 $body = L10n::t("The error message is\n[pre]%s[/pre]", $error_message);
266 'uid' => $admin['uid'],
267 'type' => SYSTEM_EMAIL,
268 'to_email' => $admin['email'],
269 'subject' => l10n::t('[Friendica Notify] Database update'),
270 'preamble' => $preamble,
278 Logger::alert('Database structure update FAILED.', ['error' => $error_message]);
281 private static function updateSuccessfull($from_build, $to_build)
283 //send the administrators an e-mail
284 $condition = ['email' => explode(",", str_replace(" ", "", Config::get('config', 'admin_email'))), 'parent-uid' => 0];
285 $adminlist = DBA::select('user', ['uid', 'language', 'email'], $condition, ['order' => ['uid']]);
287 if (DBA::isResult($adminlist)) {
290 // every admin could had different language
291 while ($admin = DBA::fetch($adminlist)) {
292 if (in_array($admin['email'], $sent)) {
295 $sent[] = $admin['email'];
297 $lang = (($admin['language']) ? $admin['language'] : 'en');
298 L10n::pushLang($lang);
300 $preamble = Strings::deindent(L10n::t("
301 The friendica database was successfully updated from %s to %s.",
302 $from_build, $to_build));
305 'uid' => $admin['uid'],
306 'type' => SYSTEM_EMAIL,
307 'to_email' => $admin['email'],
308 'subject' => l10n::t('[Friendica Notify] Database update'),
309 'preamble' => $preamble,
318 Logger::debug('Database structure update successful.');