3 namespace Friendica\Core;
5 use Friendica\Database\DBA;
6 use Friendica\Database\DBStructure;
7 use Friendica\Util\Strings;
15 * @brief Function to check if the Database structure needs an update.
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
21 public static function check($basePath, $via_worker)
23 if (!DBA::connected()) {
27 $build = self::getBuild();
28 $current = intval(DB_UPDATE_VERSION);
30 // We don't support upgrading from very old versions anymore
31 if ($build < NEW_UPDATE_ROUTINE_VERSION) {
32 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 if ($build < $current ) {
37 // Calling the database update directly via the worker enables us to perform database changes to the workerqueue table itself.
38 // This is a fallback, since normally the database update will be performed by a worker job.
39 // This worker job doesn't work for changes to the "workerqueue" table itself.
42 Worker::add(PRIORITY_CRITICAL, 'DBUpdate');
48 * Automatic database updates
50 * @param string $basePath The base path of this application
51 * @param bool $force Force the Update-Check even if the database version doesn't match
52 * @param bool $override Overrides any running/stuck updates
53 * @param bool $verbose Run the Update-Check verbose
54 * @param bool $sendMail Sends a Mail to the administrator in case of success/failure
56 * @return string Empty string if the update is successful, error messages otherwise
57 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
59 public static function run($basePath, $force = false, $override = false, $verbose = false, $sendMail = true)
61 // In force mode, we release the dbupdate lock first
62 // Necessary in case of an stuck update
64 Lock::release('dbupdate', true);
67 $current = intval(DB_UPDATE_VERSION);
68 $stored = self::getBuild();
70 if ($stored < $current || $force) {
71 require_once 'update.php';
73 Config::load('database');
75 Logger::log('Update from \'' . $stored . '\' to \'' . $current . '\' - starting', Logger::DEBUG);
77 // Compare the current structure with the defined structure
78 // If the Lock is acquired, never release it automatically to avoid double updates
79 if (Lock::acquire('dbupdate', 0, Cache::INFINITE)) {
81 // recheck again in case we accidentally spawned multiple updates
82 $stored = intval(self::getBuild());
83 if ($stored >= $current) {
84 Lock::release('dbupdate');
88 // run the pre_update_nnnn functions in update.php
89 for ($x = $stored + 1; $x <= $current; $x++) {
90 $r = self::runUpdateFunction($x, 'pre_update');
96 // update the structure in one call
97 $retval = DBStructure::update($basePath, $verbose, true);
98 if (!empty($retval)) {
105 Logger::log('ERROR: Update from \'' . $stored . '\' to \'' . $current . '\' - failed: ' - $retval, Logger::ALL);
106 Lock::release('dbupdate');
109 Config::set('database', 'last_successful_update', $current);
110 Config::set('database', 'last_successful_update_time', time());
111 Logger::log('Update from \'' . $stored . '\' to \'' . $current . '\' - finished', Logger::DEBUG);
114 // run the update_nnnn functions in update.php
115 for ($x = $stored + 1; $x <= $current; $x++) {
116 $r = self::runUpdateFunction($x, 'update');
122 Logger::log('Update from \'' . $stored . '\' to \'' . $current . '\' - successful', Logger::DEBUG);
124 self::updateSuccessfull($stored, $current);
127 Lock::release('dbupdate');
135 * Executes a specific update function
137 * @param int $x the DB version number of the function
138 * @param string $prefix the prefix of the function (update, pre_update)
140 * @return bool true, if the update function worked
141 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
143 public static function runUpdateFunction($x, $prefix)
145 $funcname = $prefix . '_' . $x;
147 Logger::log('Update function \'' . $funcname . '\' - start', Logger::DEBUG);
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.
157 if (Lock::acquire('dbupdate_function', 120,Cache::INFINITE)) {
159 // call the specific update
160 $retval = $funcname();
163 //send the administrator an e-mail
166 L10n::t('Update %s failed. See error logs.', $x)
168 Logger::log('ERROR: Update function \'' . $funcname . '\' - failed: ' . $retval, Logger::ALL);
169 Lock::release('dbupdate_function');
172 Config::set('database', 'last_successful_update_function', $funcname);
173 Config::set('database', 'last_successful_update_function_time', time());
175 if ($prefix == 'update') {
176 Config::set('system', 'build', $x);
179 Lock::release('dbupdate_function');
180 Logger::log('Update function \'' . $funcname . '\' - finished', Logger::DEBUG);
185 Logger::log('Skipping \'' . $funcname . '\' without executing', Logger::DEBUG);
187 Config::set('database', 'last_successful_update_function', $funcname);
188 Config::set('database', 'last_successful_update_function_time', time());
190 if ($prefix == 'update') {
191 Config::set('system', 'build', $x);
199 * send the email and do what is needed to do on update fails
201 * @param int $update_id number of failed update
202 * @param string $error_message error message
203 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
205 private static function updateFailed($update_id, $error_message) {
206 //send the administrators an e-mail
207 $condition = ['email' => explode(",", str_replace(" ", "", Config::get('config', 'admin_email'))), 'parent-uid' => 0];
208 $adminlist = DBA::select('user', ['uid', 'language', 'email'], $condition, ['order' => ['uid']]);
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);
220 // every admin could had different language
221 while ($admin = DBA::fetch($adminlist)) {
222 if (in_array($admin['email'], $sent)) {
225 $sent[] = $admin['email'];
227 $lang = (($admin['language'])?$admin['language']:'en');
228 L10n::pushLang($lang);
230 $preamble = Strings::deindent(L10n::t("
231 The friendica developers released update %s recently,
232 but when I tried to install it, something went terribly wrong.
233 This needs to be fixed soon and I can't do it alone. Please contact a
234 friendica developer if you can not help me on your own. My database might be invalid.",
236 $body = L10n::t("The error message is\n[pre]%s[/pre]", $error_message);
239 'uid' => $admin['uid'],
240 'type' => SYSTEM_EMAIL,
241 'to_email' => $admin['email'],
242 'preamble' => $preamble,
250 Logger::log("CRITICAL: Database structure update failed: " . $error_message);
253 private static function updateSuccessfull($from_build, $to_build)
255 //send the administrators an e-mail
256 $condition = ['email' => explode(",", str_replace(" ", "", Config::get('config', 'admin_email'))), 'parent-uid' => 0];
257 $adminlist = DBA::select('user', ['uid', 'language', 'email'], $condition, ['order' => ['uid']]);
259 if (DBA::isResult($adminlist)) {
262 // every admin could had different language
263 while ($admin = DBA::fetch($adminlist)) {
264 if (in_array($admin['email'], $sent)) {
267 $sent[] = $admin['email'];
269 $lang = (($admin['language']) ? $admin['language'] : 'en');
270 L10n::pushLang($lang);
272 $preamble = Strings::deindent(L10n::t("
273 The friendica database was successfully updated from %s to %s.",
274 $from_build, $to_build));
277 'uid' => $admin['uid'],
278 'type' => SYSTEM_EMAIL,
279 'to_email' => $admin['email'],
280 'preamble' => $preamble,
289 Logger::log("Database structure update successful.", Logger::TRACE);
293 * Returns the current build number of the instance
295 * @return int the build number
297 private static function getBuild()
299 $build = Config::get('system', 'build');
301 if (empty($build) || ($build > DB_UPDATE_VERSION)) {
302 $build = DB_UPDATE_VERSION - 1;
303 Config::set('system', 'build', $build);
306 return (is_int($build) ? intval($build) : DB_UPDATE_VERSION - 1);