/** * Do the job. * Throw exceptions on errors (the job will be retried). */ public function execute() { global $CFG; // Run automated backups if required - these may take a long time to execute. require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php'; require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php'; \backup_cron_automated_helper::run_automated_backup(); }
/** * Gets the state of the automated backup system. * * @global moodle_database $DB * @return int One of self::STATE_* */ public static function get_automated_backup_state($rundirective = self::RUN_ON_SCHEDULE) { global $DB; $config = get_config('backup'); $active = (int) $config->backup_auto_active; $weekdays = (string) $config->backup_auto_weekdays; // In case of automated backup also check that it is scheduled for at least one weekday. if ($active === self::AUTO_BACKUP_DISABLED || $rundirective == self::RUN_ON_SCHEDULE && $active === self::AUTO_BACKUP_MANUAL || $rundirective == self::RUN_ON_SCHEDULE && strpos($weekdays, '1') === false) { return self::STATE_DISABLED; } else { if (!empty($config->backup_auto_running)) { // Detect if the backup_auto_running semaphore is a valid one // by looking for recent activity in the backup_controllers table // for backups of type backup::MODE_AUTOMATED $timetosee = 60 * 90; // Time to consider in order to clean the semaphore $params = array('purpose' => backup::MODE_AUTOMATED, 'timetolook' => time() - $timetosee); if ($DB->record_exists_select('backup_controllers', "operation = 'backup' AND type = 'course' AND purpose = :purpose AND timemodified > :timetolook", $params)) { return self::STATE_RUNNING; // Recent activity found, still running } else { // No recent activity found, let's clean the semaphore mtrace('Automated backups activity not found in last ' . (int) $timetosee / 60 . ' minutes. Cleaning running status'); backup_cron_automated_helper::set_state_running(false); } } } return self::STATE_OK; }
/** * Execute cron tasks */ function cron_run() { global $DB, $CFG, $OUTPUT; if (CLI_MAINTENANCE) { echo "CLI maintenance mode active, cron execution suspended.\n"; exit(1); } if (moodle_needs_upgrading()) { echo "Moodle upgrade pending, cron execution suspended.\n"; exit(1); } require_once $CFG->libdir . '/adminlib.php'; require_once $CFG->libdir . '/gradelib.php'; if (!empty($CFG->showcronsql)) { $DB->set_debug(true); } if (!empty($CFG->showcrondebugging)) { set_debugging(DEBUG_DEVELOPER, true); } set_time_limit(0); $starttime = microtime(); // Increase memory limit raise_memory_limit(MEMORY_EXTRA); // Emulate normal session - we use admin accoutn by default cron_setup_user(); // Start output log $timenow = time(); mtrace("Server Time: " . date('r', $timenow) . "\n\n"); // Run cleanup core cron jobs, but not every time since they aren't too important. // These don't have a timer to reduce load, so we'll use a random number // to randomly choose the percentage of times we should run these jobs. $random100 = rand(0, 100); if ($random100 < 20) { // Approximately 20% of the time. mtrace("Running clean-up tasks..."); cron_trace_time_and_memory(); // Delete users who haven't confirmed within required period if (!empty($CFG->deleteunconfirmed)) { $cuttime = $timenow - $CFG->deleteunconfirmed * 3600; $rs = $DB->get_recordset_sql("SELECT *\n FROM {user}\n WHERE confirmed = 0 AND firstaccess > 0\n AND firstaccess < ?", array($cuttime)); foreach ($rs as $user) { delete_user($user); // we MUST delete user properly first $DB->delete_records('user', array('id' => $user->id)); // this is a bloody hack, but it might work mtrace(" Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})"); } $rs->close(); } // Delete users who haven't completed profile within required period if (!empty($CFG->deleteincompleteusers)) { $cuttime = $timenow - $CFG->deleteincompleteusers * 3600; $rs = $DB->get_recordset_sql("SELECT *\n FROM {user}\n WHERE confirmed = 1 AND lastaccess > 0\n AND lastaccess < ? AND deleted = 0\n AND (lastname = '' OR firstname = '' OR email = '')", array($cuttime)); foreach ($rs as $user) { if (isguestuser($user) or is_siteadmin($user)) { continue; } delete_user($user); mtrace(" Deleted not fully setup user {$user->username} ({$user->id})"); } $rs->close(); } // Delete old logs to save space (this might need a timer to slow it down...) if (!empty($CFG->loglifetime)) { // value in days $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24; $DB->delete_records_select("log", "time < ?", array($loglifetime)); mtrace(" Deleted old log records"); } // Delete old backup_controllers and logs. $loglifetime = get_config('backup', 'loglifetime'); if (!empty($loglifetime)) { // Value in days. $loglifetime = $timenow - $loglifetime * 3600 * 24; // Delete child records from backup_logs. $DB->execute("DELETE FROM {backup_logs}\n WHERE EXISTS (\n SELECT 'x'\n FROM {backup_controllers} bc\n WHERE bc.backupid = {backup_logs}.backupid\n AND bc.timecreated < ?)", array($loglifetime)); // Delete records from backup_controllers. $DB->execute("DELETE FROM {backup_controllers}\n WHERE timecreated < ?", array($loglifetime)); mtrace(" Deleted old backup records"); } // Delete old cached texts if (!empty($CFG->cachetext)) { // Defined in config.php $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites $DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime)); mtrace(" Deleted old cache_text records"); } if (!empty($CFG->usetags)) { require_once $CFG->dirroot . '/tag/lib.php'; tag_cron(); mtrace(' Executed tag cron'); } // Context maintenance stuff context_helper::cleanup_instances(); mtrace(' Cleaned up context instances'); context_helper::build_all_paths(false); // If you suspect that the context paths are somehow corrupt // replace the line below with: context_helper::build_all_paths(true); mtrace(' Built context paths'); // Remove expired cache flags gc_cache_flags(); mtrace(' Cleaned cache flags'); // Cleanup messaging if (!empty($CFG->messagingdeletereadnotificationsdelay)) { $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay; $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime' => $notificationdeletetime)); mtrace(' Cleaned up read notifications'); } mtrace(' Deleting temporary files...'); cron_delete_from_temp(); // Cleanup user password reset records // Delete any reset request records which are expired by more than a day. // (We keep recently expired requests around so we can give a different error msg to users who // are trying to user a recently expired reset attempt). $pwresettime = isset($CFG->pwresettime) ? $CFG->pwresettime : 1800; $earliestvalid = time() - $pwresettime - DAYSECS; $DB->delete_records_select('user_password_resets', "timerequested < ?", array($earliestvalid)); mtrace(' Cleaned up old password reset records'); mtrace("...finished clean-up tasks"); } // End of occasional clean-up tasks // Send login failures notification - brute force protection in moodle is weak, // we should at least send notices early in each cron execution if (notify_login_failures()) { mtrace(' Notified login failures'); } // Make sure all context instances are properly created - they may be required in auth, enrol, etc. context_helper::create_instances(); mtrace(' Created missing context instances'); // Session gc. mtrace("Running session gc tasks..."); \core\session\manager::gc(); mtrace("...finished stale session cleanup"); // Run the auth cron, if any before enrolments // because it might add users that will be needed in enrol plugins $auths = get_enabled_auth_plugins(); mtrace("Running auth crons if required..."); cron_trace_time_and_memory(); foreach ($auths as $auth) { $authplugin = get_auth_plugin($auth); if (method_exists($authplugin, 'cron')) { mtrace("Running cron for auth/{$auth}..."); $authplugin->cron(); if (!empty($authplugin->log)) { mtrace($authplugin->log); } } unset($authplugin); } // Generate new password emails for users - ppl expect these generated asap if ($DB->count_records('user_preferences', array('name' => 'create_password', 'value' => '1'))) { mtrace('Creating passwords for new users...'); $usernamefields = get_all_user_name_fields(true, 'u'); $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email,\n {$usernamefields}, u.username, u.lang,\n p.id as prefid\n FROM {user} u\n JOIN {user_preferences} p ON u.id=p.userid\n WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin' AND u.deleted = 0"); // note: we can not send emails to suspended accounts foreach ($newusers as $newuser) { // Use a low cost factor when generating bcrypt hash otherwise // hashing would be slow when emailing lots of users. Hashes // will be automatically updated to a higher cost factor the first // time the user logs in. if (setnew_password_and_mail($newuser, true)) { unset_user_preference('create_password', $newuser); set_user_preference('auth_forcepasswordchange', 1, $newuser); } else { trigger_error("Could not create and mail new user password!"); } } $newusers->close(); } // It is very important to run enrol early // because other plugins depend on correct enrolment info. mtrace("Running enrol crons if required..."); $enrols = enrol_get_plugins(true); foreach ($enrols as $ename => $enrol) { // do this for all plugins, disabled plugins might want to cleanup stuff such as roles if (!$enrol->is_cron_required()) { continue; } mtrace("Running cron for enrol_{$ename}..."); cron_trace_time_and_memory(); $enrol->cron(); $enrol->set_config('lastcron', time()); } // Run all cron jobs for each module mtrace("Starting activity modules"); get_mailer('buffer'); if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) { foreach ($mods as $mod) { $libfile = "{$CFG->dirroot}/mod/{$mod->name}/lib.php"; if (file_exists($libfile)) { include_once $libfile; $cron_function = $mod->name . "_cron"; if (function_exists($cron_function)) { mtrace("Processing module function {$cron_function} ...", ''); cron_trace_time_and_memory(); $pre_dbqueries = null; $pre_dbqueries = $DB->perf_get_queries(); $pre_time = microtime(1); if ($cron_function()) { $DB->set_field("modules", "lastcron", $timenow, array("id" => $mod->id)); } if (isset($pre_dbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries"); mtrace("... used " . (microtime(1) - $pre_time) . " seconds"); } // Reset possible changes by modules to time_limit. MDL-11597 @set_time_limit(0); mtrace("done."); } } } } get_mailer('close'); mtrace("Finished activity modules"); mtrace("Starting blocks"); if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) { // We will need the base class. require_once $CFG->dirroot . '/blocks/moodleblock.class.php'; foreach ($blocks as $block) { $blockfile = $CFG->dirroot . '/blocks/' . $block->name . '/block_' . $block->name . '.php'; if (file_exists($blockfile)) { require_once $blockfile; $classname = 'block_' . $block->name; $blockobj = new $classname(); if (method_exists($blockobj, 'cron')) { mtrace("Processing cron function for " . $block->name . '....', ''); cron_trace_time_and_memory(); if ($blockobj->cron()) { $DB->set_field('block', 'lastcron', $timenow, array('id' => $block->id)); } // Reset possible changes by blocks to time_limit. MDL-11597 @set_time_limit(0); mtrace('done.'); } } } } mtrace('Finished blocks'); mtrace('Starting admin reports'); cron_execute_plugin_type('report'); mtrace('Finished admin reports'); mtrace('Starting main gradebook job...'); cron_trace_time_and_memory(); grade_cron(); mtrace('done.'); mtrace('Starting processing the event queue...'); cron_trace_time_and_memory(); events_cron(); mtrace('done.'); if ($CFG->enablecompletion) { // Completion cron mtrace('Starting the completion cron...'); cron_trace_time_and_memory(); require_once $CFG->dirroot . '/completion/cron.php'; completion_cron(); mtrace('done'); } if ($CFG->enableportfolios) { // Portfolio cron mtrace('Starting the portfolio cron...'); cron_trace_time_and_memory(); require_once $CFG->libdir . '/portfoliolib.php'; portfolio_cron(); mtrace('done'); } //now do plagiarism checks require_once $CFG->libdir . '/plagiarismlib.php'; plagiarism_cron(); mtrace('Starting course reports'); cron_execute_plugin_type('coursereport'); mtrace('Finished course reports'); // run gradebook import/export/report cron mtrace('Starting gradebook plugins'); cron_execute_plugin_type('gradeimport'); cron_execute_plugin_type('gradeexport'); cron_execute_plugin_type('gradereport'); mtrace('Finished gradebook plugins'); // run calendar cron require_once "{$CFG->dirroot}/calendar/lib.php"; calendar_cron(); // Run external blog cron if needed if (!empty($CFG->enableblogs) && $CFG->useexternalblogs) { require_once $CFG->dirroot . '/blog/lib.php'; mtrace("Fetching external blog entries...", ''); cron_trace_time_and_memory(); $sql = "timefetched < ? OR timefetched = 0"; $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime)); foreach ($externalblogs as $eb) { blog_sync_external_entries($eb); } mtrace('done.'); } // Run blog associations cleanup if (!empty($CFG->enableblogs) && $CFG->useblogassociations) { require_once $CFG->dirroot . '/blog/lib.php'; // delete entries whose contextids no longer exists mtrace("Deleting blog associations linked to non-existent contexts...", ''); cron_trace_time_and_memory(); $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})'); mtrace('done.'); } // Run question bank clean-up. mtrace("Starting the question bank cron...", ''); cron_trace_time_and_memory(); require_once $CFG->libdir . '/questionlib.php'; question_bank::cron(); mtrace('done.'); //Run registration updated cron mtrace(get_string('siteupdatesstart', 'hub')); cron_trace_time_and_memory(); require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php'; $registrationmanager = new registration_manager(); $registrationmanager->cron(); mtrace(get_string('siteupdatesend', 'hub')); // If enabled, fetch information about available updates and eventually notify site admins if (empty($CFG->disableupdatenotifications)) { $updateschecker = \core\update\checker::instance(); $updateschecker->cron(); } //cleanup old session linked tokens //deletes the session linked tokens that are over a day old. mtrace("Deleting session linked tokens more than one day old...", ''); cron_trace_time_and_memory(); $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype', array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED)); mtrace('done.'); // all other plugins cron_execute_plugin_type('message', 'message plugins'); cron_execute_plugin_type('filter', 'filters'); cron_execute_plugin_type('editor', 'editors'); cron_execute_plugin_type('format', 'course formats'); cron_execute_plugin_type('profilefield', 'profile fields'); cron_execute_plugin_type('webservice', 'webservices'); cron_execute_plugin_type('repository', 'repository plugins'); cron_execute_plugin_type('qbehaviour', 'question behaviours'); cron_execute_plugin_type('qformat', 'question import/export formats'); cron_execute_plugin_type('qtype', 'question types'); cron_execute_plugin_type('plagiarism', 'plagiarism plugins'); cron_execute_plugin_type('theme', 'themes'); cron_execute_plugin_type('tool', 'admin tools'); // and finally run any local cronjobs, if any if ($locals = core_component::get_plugin_list('local')) { mtrace('Processing customized cron scripts ...', ''); // new cron functions in lib.php first cron_execute_plugin_type('local'); // legacy cron files are executed directly foreach ($locals as $local => $localdir) { if (file_exists("{$localdir}/cron.php")) { include "{$localdir}/cron.php"; } } mtrace('done.'); } mtrace('Running cache cron routines'); cache_helper::cron(); mtrace('done.'); // Run automated backups if required - these may take a long time to execute require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php'; require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php'; backup_cron_automated_helper::run_automated_backup(); // Run stats as at the end because they are known to take very long time on large sites if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) { require_once $CFG->dirroot . '/lib/statslib.php'; // check we're not before our runtime $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour * 60 * 60 + $CFG->statsruntimestartminute * 60; if (time() > $timetocheck) { // process configured number of days as max (defaulting to 31) $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays); if (stats_cron_daily($maxdays)) { if (stats_cron_weekly()) { if (stats_cron_monthly()) { stats_clean_old(); } } } @set_time_limit(0); } else { mtrace('Next stats run after:' . userdate($timetocheck)); } } // Run badges review cron. mtrace("Starting badges cron..."); require_once $CFG->dirroot . '/badges/cron.php'; badge_cron(); mtrace('done.'); // cleanup file trash - not very important $fs = get_file_storage(); $fs->cron(); mtrace("Cron script completed correctly"); gc_collect_cycles(); mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.'); $difftime = microtime_diff($starttime, microtime()); mtrace("Execution took " . $difftime . " seconds"); }
/** * Runs the automated backups if required * * @global moodle_database $DB */ public static function run_automated_backup($rundirective = self::RUN_ON_SCHEDULE) { global $CFG, $DB; $status = true; $emailpending = false; $now = time(); mtrace("Checking automated backup status",'...'); $state = backup_cron_automated_helper::get_automated_backup_state($rundirective); if ($state === backup_cron_automated_helper::STATE_DISABLED) { mtrace('INACTIVE'); return $state; } else if ($state === backup_cron_automated_helper::STATE_RUNNING) { mtrace('RUNNING'); if ($rundirective == self::RUN_IMMEDIATELY) { mtrace('automated backups are already. If this script is being run by cron this constitues an error. You will need to increase the time between executions within cron.'); } else { mtrace("automated backup are already running. Execution delayed"); } return $state; } else { mtrace('OK'); } backup_cron_automated_helper::set_state_running(); mtrace("Getting admin info"); $admin = get_admin(); if (!$admin) { mtrace("Error: No admin account was found"); $state = false; } if ($status) { mtrace("Checking courses"); mtrace("Skipping deleted courses", '...'); mtrace(sprintf("%d courses", backup_cron_automated_helper::remove_deleted_courses_from_schedule())); } if ($status) { mtrace('Running required automated backups...'); // This could take a while! @set_time_limit(0); raise_memory_limit(MEMORY_EXTRA); $nextstarttime = backup_cron_automated_helper::calculate_next_automated_backup($admin->timezone, $now); $showtime = "undefined"; if ($nextstarttime > 0) { $showtime = userdate($nextstarttime,"",$admin->timezone); } $rs = $DB->get_recordset('course'); foreach ($rs as $course) { $backupcourse = $DB->get_record('backup_courses', array('courseid'=>$course->id)); if (!$backupcourse) { $backupcourse = new stdClass; $backupcourse->courseid = $course->id; $DB->insert_record('backup_courses',$backupcourse); $backupcourse = $DB->get_record('backup_courses', array('courseid'=>$course->id)); } // Skip backup of unavailable courses that have remained unmodified in a month $skipped = false; if (empty($course->visible) && ($now - $course->timemodified) > 31*24*60*60) { //Hidden + unmodified last month $backupcourse->laststatus = backup_cron_automated_helper::BACKUP_STATUS_SKIPPED; $DB->update_record('backup_courses', $backupcourse); mtrace('Skipping unchanged course '.$course->fullname); $skipped = true; } else if (($backupcourse->nextstarttime >= 0 && $backupcourse->nextstarttime < $now) || $rundirective == self::RUN_IMMEDIATELY) { mtrace('Backing up '.$course->fullname, '...'); //We have to send a email because we have included at least one backup $emailpending = true; //Only make the backup if laststatus isn't 2-UNFINISHED (uncontrolled error) if ($backupcourse->laststatus != 2) { //Set laststarttime $starttime = time(); $backupcourse->laststarttime = time(); $backupcourse->laststatus = backup_cron_automated_helper::BACKUP_STATUS_UNFINISHED; $DB->update_record('backup_courses', $backupcourse); $backupcourse->laststatus = backup_cron_automated_helper::launch_automated_backup($course, $backupcourse->laststarttime, $admin->id); $backupcourse->lastendtime = time(); $backupcourse->nextstarttime = $nextstarttime; $DB->update_record('backup_courses', $backupcourse); if ($backupcourse->laststatus) { // Clean up any excess course backups now that we have // taken a successful backup. $removedcount = backup_cron_automated_helper::remove_excess_backups($course); } } mtrace("complete - next execution: $showtime"); } } $rs->close(); } //Send email to admin if necessary if ($emailpending) { mtrace("Sending email to admin"); $message = ""; $count = backup_cron_automated_helper::get_backup_status_array(); $haserrors = ($count[backup_cron_automated_helper::BACKUP_STATUS_ERROR] != 0 || $count[backup_cron_automated_helper::BACKUP_STATUS_UNFINISHED] != 0); //Build the message text //Summary $message .= get_string('summary')."\n"; $message .= "==================================================\n"; $message .= " ".get_string('courses').": ".array_sum($count)."\n"; $message .= " ".get_string('ok').": ".$count[backup_cron_automated_helper::BACKUP_STATUS_OK]."\n"; $message .= " ".get_string('skipped').": ".$count[backup_cron_automated_helper::BACKUP_STATUS_SKIPPED]."\n"; $message .= " ".get_string('error').": ".$count[backup_cron_automated_helper::BACKUP_STATUS_ERROR]."\n"; $message .= " ".get_string('unfinished').": ".$count[backup_cron_automated_helper::BACKUP_STATUS_UNFINISHED]."\n\n"; //Reference if ($haserrors) { $message .= " ".get_string('backupfailed')."\n\n"; $dest_url = "$CFG->wwwroot/$CFG->admin/report/backups/index.php"; $message .= " ".get_string('backuptakealook','',$dest_url)."\n\n"; //Set message priority $admin->priority = 1; //Reset unfinished to error $DB->set_field('backup_courses','laststatus','0', array('laststatus'=>'2')); } else { $message .= " ".get_string('backupfinished')."\n"; } //Build the message subject $site = get_site(); $prefix = $site->shortname.": "; if ($haserrors) { $prefix .= "[".strtoupper(get_string('error'))."] "; } $subject = $prefix.get_string('automatedbackupstatus', 'backup'); //Send the message $eventdata = new stdClass(); $eventdata->modulename = 'moodle'; $eventdata->userfrom = $admin; $eventdata->userto = $admin; $eventdata->subject = $subject; $eventdata->fullmessage = $message; $eventdata->fullmessageformat = FORMAT_PLAIN; $eventdata->fullmessagehtml = ''; $eventdata->smallmessage = ''; $eventdata->component = 'moodle'; $eventdata->name = 'backup'; message_send($eventdata); } //Everything is finished stop backup_auto_running backup_cron_automated_helper::set_state_running(false); mtrace('Automated backups complete.'); return $status; }
/** * Test {@link backup_cron_automated_helper::calculate_next_automated_backup}. */ public function test_next_automated_backup() { $this->resetAfterTest(); set_config('backup_auto_active', '1', 'backup'); // Notes // - backup_auto_weekdays starts on Sunday // - Tests cannot be done in the past // - Only the DST on the server side is handled. // Every Tue and Fri at 11pm. set_config('backup_auto_weekdays', '0010010', 'backup'); set_config('backup_auto_hour', '23', 'backup'); set_config('backup_auto_minute', '0', 'backup'); $timezone = 99; $now = strtotime('next Monday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-23:00', date('w-H:i', $next)); $now = strtotime('next Tuesday 18:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-23:00', date('w-H:i', $next)); $now = strtotime('next Wednesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('5-23:00', date('w-H:i', $next)); $now = strtotime('next Thursday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('5-23:00', date('w-H:i', $next)); $now = strtotime('next Friday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('5-23:00', date('w-H:i', $next)); $now = strtotime('next Saturday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-23:00', date('w-H:i', $next)); $now = strtotime('next Sunday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-23:00', date('w-H:i', $next)); // Every Sun and Sat at 12pm. set_config('backup_auto_weekdays', '1000001', 'backup'); set_config('backup_auto_hour', '0', 'backup'); set_config('backup_auto_minute', '0', 'backup'); $timezone = 99; $now = strtotime('next Monday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Tuesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Wednesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Thursday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Friday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Saturday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-00:00', date('w-H:i', $next)); $now = strtotime('next Sunday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); // Every Sun at 4am. set_config('backup_auto_weekdays', '1000000', 'backup'); set_config('backup_auto_hour', '4', 'backup'); set_config('backup_auto_minute', '0', 'backup'); $timezone = 99; $now = strtotime('next Monday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Tuesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Wednesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Thursday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Friday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Saturday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Sunday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); // Every day but Wed at 8:30pm. set_config('backup_auto_weekdays', '1110111', 'backup'); set_config('backup_auto_hour', '20', 'backup'); set_config('backup_auto_minute', '30', 'backup'); $timezone = 99; $now = strtotime('next Monday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('1-20:30', date('w-H:i', $next)); $now = strtotime('next Tuesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-20:30', date('w-H:i', $next)); $now = strtotime('next Wednesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('4-20:30', date('w-H:i', $next)); $now = strtotime('next Thursday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('4-20:30', date('w-H:i', $next)); $now = strtotime('next Friday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('5-20:30', date('w-H:i', $next)); $now = strtotime('next Saturday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-20:30', date('w-H:i', $next)); $now = strtotime('next Sunday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-20:30', date('w-H:i', $next)); // Sun, Tue, Thu, Sat at 12pm. set_config('backup_auto_weekdays', '1010101', 'backup'); set_config('backup_auto_hour', '0', 'backup'); set_config('backup_auto_minute', '0', 'backup'); $timezone = 99; $now = strtotime('next Monday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-00:00', date('w-H:i', $next)); $now = strtotime('next Tuesday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('4-00:00', date('w-H:i', $next)); $now = strtotime('next Wednesday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('4-00:00', date('w-H:i', $next)); $now = strtotime('next Thursday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Friday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Saturday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-00:00', date('w-H:i', $next)); $now = strtotime('next Sunday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-00:00', date('w-H:i', $next)); // None. set_config('backup_auto_weekdays', '0000000', 'backup'); set_config('backup_auto_hour', '15', 'backup'); set_config('backup_auto_minute', '30', 'backup'); $timezone = 99; $now = strtotime('next Sunday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0', $next); // Playing with timezones. set_config('backup_auto_weekdays', '1111111', 'backup'); set_config('backup_auto_hour', '20', 'backup'); set_config('backup_auto_minute', '00', 'backup'); $timezone = 99; date_default_timezone_set('Australia/Perth'); $now = strtotime('18:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-20:00'), date('w-H:i', $next)); $timezone = 99; date_default_timezone_set('Europe/Brussels'); $now = strtotime('18:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-20:00'), date('w-H:i', $next)); $timezone = 99; date_default_timezone_set('America/New_York'); $now = strtotime('18:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-20:00'), date('w-H:i', $next)); // Viva Australia! (UTC+8). date_default_timezone_set('Australia/Perth'); $now = strtotime('18:00:00'); $timezone = -10.0; // 12am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-14:00', strtotime('tomorrow')), date('w-H:i', $next)); $timezone = -5.0; // 5am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-09:00', strtotime('tomorrow')), date('w-H:i', $next)); $timezone = 0.0; // 10am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-04:00', strtotime('tomorrow')), date('w-H:i', $next)); $timezone = 3.0; // 1pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-01:00', strtotime('tomorrow')), date('w-H:i', $next)); $timezone = 8.0; // 6pm for the user (same than the server). $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-20:00'), date('w-H:i', $next)); $timezone = 9.0; // 7pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-19:00'), date('w-H:i', $next)); $timezone = 13.0; // 12am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-15:00', strtotime('tomorrow')), date('w-H:i', $next)); // Let's have a Belgian beer! (UTC+1 / UTC+2 DST). // Warning: Some of these tests will fail if executed "around" // 'Europe/Brussels' DST changes (last Sunday in March and // last Sunday in October right now - 2012). Once Moodle // moves to PHP TZ support this could be fixed properly. date_default_timezone_set('Europe/Brussels'); $now = strtotime('18:00:00'); $dst = date('I', $now); $timezone = -10.0; // 7am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-07:00', strtotime('tomorrow')) : date('w-08:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = -5.0; // 12pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-02:00', strtotime('tomorrow')) : date('w-03:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 0.0; // 5pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-21:00') : date('w-22:00'); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 3.0; // 8pm for the user (note the expected time is today while in DST). $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-18:00', strtotime('tomorrow')) : date('w-19:00'); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 8.0; // 1am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-13:00', strtotime('tomorrow')) : date('w-14:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 9.0; // 2am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-12:00', strtotime('tomorrow')) : date('w-13:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 13.0; // 6am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-08:00', strtotime('tomorrow')) : date('w-09:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); // The big apple! (UTC-5 / UTC-4 DST). // Warning: Some of these tests will fail if executed "around" // 'America/New_York' DST changes (2nd Sunday in March and // 1st Sunday in November right now - 2012). Once Moodle // moves to PHP TZ support this could be fixed properly. date_default_timezone_set('America/New_York'); $now = strtotime('18:00:00'); $dst = date('I', $now); $timezone = -10.0; // 1pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-01:00', strtotime('tomorrow')) : date('w-02:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = -5.0; // 6pm for the user (server time). $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-20:00') : date('w-21:00'); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 0.0; // 11pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-15:00', strtotime('tomorrow')) : date('w-16:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 3.0; // 2am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-12:00', strtotime('tomorrow')) : date('w-13:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 8.0; // 7am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-07:00', strtotime('tomorrow')) : date('w-08:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 9.0; // 8am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-06:00', strtotime('tomorrow')) : date('w-07:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 13.0; // 6am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-02:00', strtotime('tomorrow')) : date('w-03:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); // Some more timezone tests set_config('backup_auto_weekdays', '0100001', 'backup'); set_config('backup_auto_hour', '20', 'backup'); set_config('backup_auto_minute', '00', 'backup'); // Note: These tests should not fail because they are "unnafected" // by DST changes, as far as execution always happens on Monday and // Saturday and those week days are not, right now, the ones rulez // to peform the DST changes (Sunday is). This may change if rules // are modified in the future. date_default_timezone_set('Europe/Brussels'); $now = strtotime('next Monday 18:00:00'); $dst = date('I', $now); $timezone = -12.0; // 1pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '2-09:00' : '2-10:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = -4.0; // 1pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '2-01:00' : '2-02:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 0.0; // 5pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '1-21:00' : '1-22:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 2.0; // 7pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '1-19:00' : '1-20:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 4.0; // 9pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '6-17:00' : '6-18:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 12.0; // 6am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '6-09:00' : '6-10:00'; $this->assertEquals($expected, date('w-H:i', $next)); // Some more timezone tests set_config('backup_auto_weekdays', '0100001', 'backup'); set_config('backup_auto_hour', '02', 'backup'); set_config('backup_auto_minute', '00', 'backup'); // Note: These tests should not fail because they are "unnafected" // by DST changes, as far as execution always happens on Monday and // Saturday and those week days are not, right now, the ones rulez // to peform the DST changes (Sunday is). This may change if rules // are modified in the future. date_default_timezone_set('America/New_York'); $now = strtotime('next Monday 04:00:00'); $dst = date('I', $now); $timezone = -12.0; // 8pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '1-09:00' : '1-10:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = -4.0; // 4am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '6-01:00' : '6-02:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 0.0; // 8am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '5-21:00' : '5-22:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 2.0; // 10am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '5-19:00' : '5-20:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 4.0; // 12pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '5-17:00' : '5-18:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 12.0; // 8pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '5-09:00' : '5-10:00'; $this->assertEquals($expected, date('w-H:i', $next)); }
/** * Cron functions. * * @package core * @subpackage admin * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ function cron_run() { global $DB, $CFG, $OUTPUT; if (CLI_MAINTENANCE) { echo "CLI maintenance mode active, cron execution suspended.\n"; exit(1); } if (moodle_needs_upgrading()) { echo "Moodle upgrade pending, cron execution suspended.\n"; exit(1); } require_once $CFG->libdir . '/adminlib.php'; require_once $CFG->libdir . '/gradelib.php'; if (!empty($CFG->showcronsql)) { $DB->set_debug(true); } if (!empty($CFG->showcrondebugging)) { $CFG->debug = DEBUG_DEVELOPER; $CFG->debugdisplay = true; } set_time_limit(0); $starttime = microtime(); /// increase memory limit raise_memory_limit(MEMORY_EXTRA); /// emulate normal session cron_setup_user(); /// Start output log $timenow = time(); mtrace("Server Time: " . date('r', $timenow) . "\n\n"); /// Session gc mtrace("Cleaning up stale sessions"); session_gc(); /// Run all cron jobs for each module mtrace("Starting activity modules"); get_mailer('buffer'); if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) { foreach ($mods as $mod) { $libfile = "{$CFG->dirroot}/mod/{$mod->name}/lib.php"; if (file_exists($libfile)) { include_once $libfile; $cron_function = $mod->name . "_cron"; if (function_exists($cron_function)) { mtrace("Processing module function {$cron_function} ...", ''); $pre_dbqueries = null; $pre_dbqueries = $DB->perf_get_queries(); $pre_time = microtime(1); if ($cron_function()) { $DB->set_field("modules", "lastcron", $timenow, array("id" => $mod->id)); } if (isset($pre_dbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries"); mtrace("... used " . (microtime(1) - $pre_time) . " seconds"); } /// Reset possible changes by modules to time_limit. MDL-11597 @set_time_limit(0); mtrace("done."); } } } } get_mailer('close'); mtrace("Finished activity modules"); mtrace("Starting blocks"); if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) { // we will need the base class. require_once $CFG->dirroot . '/blocks/moodleblock.class.php'; foreach ($blocks as $block) { $blockfile = $CFG->dirroot . '/blocks/' . $block->name . '/block_' . $block->name . '.php'; if (file_exists($blockfile)) { require_once $blockfile; $classname = 'block_' . $block->name; $blockobj = new $classname(); if (method_exists($blockobj, 'cron')) { mtrace("Processing cron function for " . $block->name . '....', ''); if ($blockobj->cron()) { $DB->set_field('block', 'lastcron', $timenow, array('id' => $block->id)); } /// Reset possible changes by blocks to time_limit. MDL-11597 @set_time_limit(0); mtrace('done.'); } } } } mtrace('Finished blocks'); //now do plagiarism checks require_once $CFG->libdir . '/plagiarismlib.php'; plagiarism_cron(); mtrace("Starting quiz reports"); if ($reports = $DB->get_records_select('quiz_report', "cron > 0 AND ((? - lastcron) > cron)", array($timenow))) { foreach ($reports as $report) { $cronfile = "{$CFG->dirroot}/mod/quiz/report/{$report->name}/cron.php"; if (file_exists($cronfile)) { include_once $cronfile; $cron_function = 'quiz_report_' . $report->name . "_cron"; if (function_exists($cron_function)) { mtrace("Processing quiz report cron function {$cron_function} ...", ''); $pre_dbqueries = null; $pre_dbqueries = $DB->perf_get_queries(); $pre_time = microtime(1); if ($cron_function()) { $DB->set_field('quiz_report', "lastcron", $timenow, array("id" => $report->id)); } if (isset($pre_dbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries"); mtrace("... used " . (microtime(1) - $pre_time) . " seconds"); } mtrace("done."); } } } } mtrace("Finished quiz reports"); mtrace('Starting admin reports'); // Admin reports do not have a database table that lists them. Instead a // report includes cron.php with function report_reportname_cron() if it wishes // to be cronned. It is up to cron.php to handle e.g. if it only needs to // actually do anything occasionally. $reports = get_plugin_list('report'); foreach ($reports as $report => $reportdir) { $cronfile = $reportdir . '/cron.php'; if (file_exists($cronfile)) { require_once $cronfile; $cronfunction = 'report_' . $report . '_cron'; mtrace('Processing cron function for ' . $report . '...', ''); $pre_dbqueries = null; $pre_dbqueries = $DB->perf_get_queries(); $pre_time = microtime(true); $cronfunction(); if (isset($pre_dbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries"); mtrace("... used " . round(microtime(true) - $pre_time, 2) . " seconds"); } mtrace('done.'); } } mtrace('Finished admin reports'); mtrace('Starting main gradebook job ...'); grade_cron(); mtrace('done.'); mtrace('Starting processing the event queue...'); events_cron(); mtrace('done.'); if ($CFG->enablecompletion) { // Completion cron mtrace('Starting the completion cron...'); require_once $CFG->libdir . '/completion/cron.php'; completion_cron(); mtrace('done'); } if ($CFG->enableportfolios) { // Portfolio cron mtrace('Starting the portfolio cron...'); require_once $CFG->libdir . '/portfoliolib.php'; portfolio_cron(); mtrace('done'); } /// Run all core cron jobs, but not every time since they aren't too important. /// These don't have a timer to reduce load, so we'll use a random number /// to randomly choose the percentage of times we should run these jobs. srand((double) microtime() * 10000000); $random100 = rand(0, 100); if ($random100 < 20) { // Approximately 20% of the time. mtrace("Running clean-up tasks..."); /// Delete users who haven't confirmed within required period if (!empty($CFG->deleteunconfirmed)) { $cuttime = $timenow - $CFG->deleteunconfirmed * 3600; $rs = $DB->get_recordset_sql("SELECT id, firstname, lastname\n FROM {user}\n WHERE confirmed = 0 AND firstaccess > 0\n AND firstaccess < ?", array($cuttime)); foreach ($rs as $user) { if ($DB->delete_records('user', array('id' => $user->id))) { mtrace("Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})"); } } $rs->close(); } flush(); /// Delete users who haven't completed profile within required period if (!empty($CFG->deleteincompleteusers)) { $cuttime = $timenow - $CFG->deleteincompleteusers * 3600; $rs = $DB->get_recordset_sql("SELECT id, username\n FROM {user}\n WHERE confirmed = 1 AND lastaccess > 0\n AND lastaccess < ? AND deleted = 0\n AND (lastname = '' OR firstname = '' OR email = '')", array($cuttime)); foreach ($rs as $user) { if (delete_user($user)) { mtrace("Deleted not fully setup user {$user->username} ({$user->id})"); } } $rs->close(); } flush(); /// Delete old logs to save space (this might need a timer to slow it down...) if (!empty($CFG->loglifetime)) { // value in days $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24; if ($DB->delete_records_select("log", "time < ?", array($loglifetime))) { mtrace("Deleted old log records"); } } flush(); // Delete old backup_controllers and logs if (!empty($CFG->loglifetime)) { // value in days $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24; // Delete child records from backup_logs $DB->execute("DELETE FROM {backup_logs}\n WHERE EXISTS (\n SELECT 'x'\n FROM {backup_controllers} bc\n WHERE bc.backupid = {backup_logs}.backupid\n AND bc.timecreated < ?)", array($loglifetime)); // Delete records from backup_controllers $DB->execute("DELETE FROM {backup_controllers}\n WHERE timecreated < ?", array($loglifetime)); mtrace("Deleted old backup records"); } flush(); /// Delete old cached texts if (!empty($CFG->cachetext)) { // Defined in config.php $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites if ($DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime))) { mtrace("Deleted old cache_text records"); } } flush(); if (!empty($CFG->notifyloginfailures)) { notify_login_failures(); mtrace('Notified login failured'); } flush(); // // generate new password emails for users // mtrace('checking for create_password'); if ($DB->count_records('user_preferences', array('name' => 'create_password', 'value' => '1'))) { mtrace('creating passwords for new users'); $newusers = $DB->get_records_sql("SELECT u.id as id, u.email, u.firstname,\n u.lastname, u.username,\n p.id as prefid\n FROM {user} u\n JOIN {user_preferences} p ON u.id=p.userid\n WHERE p.name='create_password' AND p.value='1' AND u.email !='' "); foreach ($newusers as $newuserid => $newuser) { // email user if (setnew_password_and_mail($newuser)) { // remove user pref $DB->delete_records('user_preferences', array('id' => $newuser->prefid)); } else { trigger_error("Could not create and mail new user password!"); } } } if (!empty($CFG->usetags)) { require_once $CFG->dirroot . '/tag/lib.php'; tag_cron(); mtrace('Executed tag cron'); } // Accesslib stuff cleanup_contexts(); mtrace('Cleaned up contexts'); gc_cache_flags(); mtrace('Cleaned cache flags'); // If you suspect that the context paths are somehow corrupt // replace the line below with: build_context_path(true); build_context_path(); mtrace('Built context paths'); if (!empty($CFG->messagingdeletereadnotificationsdelay)) { $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay; $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime' => $notificationdeletetime)); mtrace('Cleaned up read notifications'); } mtrace("Finished clean-up tasks..."); } // End of occasional clean-up tasks // Run automated backups if required. require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php'; require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php'; backup_cron_automated_helper::run_automated_backup(); /// Run the auth cron, if any /// before enrolments because it might add users that will be needed in enrol plugins $auths = get_enabled_auth_plugins(); mtrace("Running auth crons if required..."); foreach ($auths as $auth) { $authplugin = get_auth_plugin($auth); if (method_exists($authplugin, 'cron')) { mtrace("Running cron for auth/{$auth}..."); $authplugin->cron(); if (!empty($authplugin->log)) { mtrace($authplugin->log); } } unset($authplugin); } mtrace("Running enrol crons if required..."); $enrols = enrol_get_plugins(true); foreach ($enrols as $ename => $enrol) { // do this for all plugins, disabled plugins might want to cleanup stuff such as roles if (!$enrol->is_cron_required()) { continue; } mtrace("Running cron for enrol_{$ename}..."); $enrol->cron(); $enrol->set_config('lastcron', time()); } if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) { require_once $CFG->dirroot . '/lib/statslib.php'; // check we're not before our runtime $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour * 60 * 60 + $CFG->statsruntimestartminute * 60; if (time() > $timetocheck) { // process configured number of days as max (defaulting to 31) $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays); if (stats_cron_daily($maxdays)) { if (stats_cron_weekly()) { if (stats_cron_monthly()) { stats_clean_old(); } } } @set_time_limit(0); } else { mtrace('Next stats run after:' . userdate($timetocheck)); } } // run gradebook import/export/report cron if ($gradeimports = get_plugin_list('gradeimport')) { foreach ($gradeimports as $gradeimport => $plugindir) { if (file_exists($plugindir . '/lib.php')) { require_once $plugindir . '/lib.php'; $cron_function = 'grade_import_' . $gradeimport . '_cron'; if (function_exists($cron_function)) { mtrace("Processing gradebook import function {$cron_function} ...", ''); $cron_function(); } } } } if ($gradeexports = get_plugin_list('gradeexport')) { foreach ($gradeexports as $gradeexport => $plugindir) { if (file_exists($plugindir . '/lib.php')) { require_once $plugindir . '/lib.php'; $cron_function = 'grade_export_' . $gradeexport . '_cron'; if (function_exists($cron_function)) { mtrace("Processing gradebook export function {$cron_function} ...", ''); $cron_function(); } } } } if ($gradereports = get_plugin_list('gradereport')) { foreach ($gradereports as $gradereport => $plugindir) { if (file_exists($plugindir . '/lib.php')) { require_once $plugindir . '/lib.php'; $cron_function = 'grade_report_' . $gradereport . '_cron'; if (function_exists($cron_function)) { mtrace("Processing gradebook report function {$cron_function} ...", ''); $cron_function(); } } } } // Run external blog cron if needed if ($CFG->useexternalblogs) { require_once $CFG->dirroot . '/blog/lib.php'; mtrace("Fetching external blog entries...", ''); $sql = "timefetched < ? OR timefetched = 0"; $externalblogs = $DB->get_records_select('blog_external', $sql, array(mktime() - $CFG->externalblogcrontime)); foreach ($externalblogs as $eb) { blog_sync_external_entries($eb); } } // Run blog associations cleanup if ($CFG->useblogassociations) { require_once $CFG->dirroot . '/blog/lib.php'; // delete entries whose contextids no longer exists mtrace("Deleting blog associations linked to non-existent contexts...", ''); $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})'); } //Run registration updated cron mtrace(get_string('siteupdatesstart', 'hub')); require_once $CFG->dirroot . '/admin/registration/lib.php'; $registrationmanager = new registration_manager(); $registrationmanager->cron(); mtrace(get_string('siteupdatesend', 'hub')); // cleanup file trash $fs = get_file_storage(); $fs->cron(); //cleanup old session linked tokens //deletes the session linked tokens that are over a day old. mtrace("Deleting session linked tokens more than one day old...", ''); $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype', array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED)); mtrace('done.'); // run any customized cronjobs, if any if ($locals = get_plugin_list('local')) { mtrace('Processing customized cron scripts ...', ''); foreach ($locals as $local => $localdir) { if (file_exists("{$localdir}/cron.php")) { include "{$localdir}/cron.php"; } } mtrace('done.'); } mtrace("Cron script completed correctly"); $difftime = microtime_diff($starttime, microtime()); mtrace("Execution took " . $difftime . " seconds"); }
die; } if (CLI_MAINTENANCE) { echo "CLI maintenance mode active, backup execution suspended.\n"; exit(1); } if (moodle_needs_upgrading()) { echo "Moodle upgrade pending, backup execution suspended.\n"; exit(1); } require_once $CFG->libdir . '/adminlib.php'; require_once $CFG->libdir . '/gradelib.php'; if (!empty($CFG->showcronsql)) { $DB->set_debug(true); } if (!empty($CFG->showcrondebugging)) { set_debugging(DEBUG_DEVELOPER, true); } $starttime = microtime(); /// emulate normal session cron_setup_user(); /// Start output log $timenow = time(); mtrace("Server Time: " . date('r', $timenow) . "\n\n"); // Run automated backups if required. require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php'; require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php'; backup_cron_automated_helper::run_automated_backup(backup_cron_automated_helper::RUN_IMMEDIATELY); mtrace("Automated cron backups completed correctly"); $difftime = microtime_diff($starttime, microtime()); mtrace("Execution took " . $difftime . " seconds");
public function test_next_automated_backup() { $this->resetAfterTest(); $admin = get_admin(); $timezone = $admin->timezone; // Notes // - The next automated backup will never be on the same date than $now // - backup_auto_weekdays starts on Sunday // - Tests cannot be done in the past. // Every Wed and Sat at 11pm. set_config('backup_auto_active', '1', 'backup'); set_config('backup_auto_weekdays', '0010010', 'backup'); set_config('backup_auto_hour', '23', 'backup'); set_config('backup_auto_minute', '0', 'backup'); $now = strtotime('next Monday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-23:00', date('w-H:i', $next)); $now = strtotime('next Tuesday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('5-23:00', date('w-H:i', $next)); $now = strtotime('next Wednesday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('5-23:00', date('w-H:i', $next)); $now = strtotime('next Thursday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('5-23:00', date('w-H:i', $next)); $now = strtotime('next Friday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-23:00', date('w-H:i', $next)); $now = strtotime('next Saturday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-23:00', date('w-H:i', $next)); $now = strtotime('next Sunday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-23:00', date('w-H:i', $next)); // Every Sun and Sat at 12pm. set_config('backup_auto_active', '1', 'backup'); set_config('backup_auto_weekdays', '1000001', 'backup'); set_config('backup_auto_hour', '0', 'backup'); set_config('backup_auto_minute', '0', 'backup'); $now = strtotime('next Monday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Tuesday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Wednesday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Thursday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Friday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Saturday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-00:00', date('w-H:i', $next)); $now = strtotime('next Sunday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); // Every Sun at 4am. set_config('backup_auto_active', '1', 'backup'); set_config('backup_auto_weekdays', '1000000', 'backup'); set_config('backup_auto_hour', '4', 'backup'); set_config('backup_auto_minute', '0', 'backup'); $now = strtotime('next Monday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Tuesday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Wednesday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Thursday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Friday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Saturday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Sunday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); // Every day but Wed at 8:30pm. set_config('backup_auto_active', '1', 'backup'); set_config('backup_auto_weekdays', '1110111', 'backup'); set_config('backup_auto_hour', '20', 'backup'); set_config('backup_auto_minute', '30', 'backup'); $now = strtotime('next Monday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-20:30', date('w-H:i', $next)); $now = strtotime('next Tuesday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('4-20:30', date('w-H:i', $next)); $now = strtotime('next Wednesday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('4-20:30', date('w-H:i', $next)); $now = strtotime('next Thursday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('5-20:30', date('w-H:i', $next)); $now = strtotime('next Friday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-20:30', date('w-H:i', $next)); $now = strtotime('next Saturday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-20:30', date('w-H:i', $next)); $now = strtotime('next Sunday'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('1-20:30', date('w-H:i', $next)); }
/** * Test {@link backup_cron_automated_helper::calculate_next_automated_backup}. */ public function test_next_automated_backup() { $this->resetAfterTest(); set_config('backup_auto_active', '1', 'backup'); // Notes // - backup_auto_weekdays starts on Sunday // - Tests cannot be done in the past // - Only the DST on the server side is handled. // Every Tue and Fri at 11pm. set_config('backup_auto_weekdays', '0010010', 'backup'); set_config('backup_auto_hour', '23', 'backup'); set_config('backup_auto_minute', '0', 'backup'); $timezone = 99; $now = strtotime('next Monday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-23:00', date('w-H:i', $next)); $now = strtotime('next Tuesday 18:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-23:00', date('w-H:i', $next)); $now = strtotime('next Wednesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('5-23:00', date('w-H:i', $next)); $now = strtotime('next Thursday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('5-23:00', date('w-H:i', $next)); $now = strtotime('next Friday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('5-23:00', date('w-H:i', $next)); $now = strtotime('next Saturday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-23:00', date('w-H:i', $next)); $now = strtotime('next Sunday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-23:00', date('w-H:i', $next)); // Every Sun and Sat at 12pm. set_config('backup_auto_weekdays', '1000001', 'backup'); set_config('backup_auto_hour', '0', 'backup'); set_config('backup_auto_minute', '0', 'backup'); $timezone = 99; $now = strtotime('next Monday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Tuesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Wednesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Thursday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Friday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Saturday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-00:00', date('w-H:i', $next)); $now = strtotime('next Sunday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); // Every Sun at 4am. set_config('backup_auto_weekdays', '1000000', 'backup'); set_config('backup_auto_hour', '4', 'backup'); set_config('backup_auto_minute', '0', 'backup'); $timezone = 99; $now = strtotime('next Monday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Tuesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Wednesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Thursday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Friday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Saturday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Sunday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); // Every day but Wed at 8:30pm. set_config('backup_auto_weekdays', '1110111', 'backup'); set_config('backup_auto_hour', '20', 'backup'); set_config('backup_auto_minute', '30', 'backup'); $timezone = 99; $now = strtotime('next Monday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('1-20:30', date('w-H:i', $next)); $now = strtotime('next Tuesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-20:30', date('w-H:i', $next)); $now = strtotime('next Wednesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('4-20:30', date('w-H:i', $next)); $now = strtotime('next Thursday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('4-20:30', date('w-H:i', $next)); $now = strtotime('next Friday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('5-20:30', date('w-H:i', $next)); $now = strtotime('next Saturday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-20:30', date('w-H:i', $next)); $now = strtotime('next Sunday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-20:30', date('w-H:i', $next)); // Sun, Tue, Thu, Sat at 12pm. set_config('backup_auto_weekdays', '1010101', 'backup'); set_config('backup_auto_hour', '0', 'backup'); set_config('backup_auto_minute', '0', 'backup'); $timezone = 99; $now = strtotime('next Monday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-00:00', date('w-H:i', $next)); $now = strtotime('next Tuesday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('4-00:00', date('w-H:i', $next)); $now = strtotime('next Wednesday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('4-00:00', date('w-H:i', $next)); $now = strtotime('next Thursday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Friday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Saturday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-00:00', date('w-H:i', $next)); $now = strtotime('next Sunday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-00:00', date('w-H:i', $next)); // None. set_config('backup_auto_weekdays', '0000000', 'backup'); set_config('backup_auto_hour', '15', 'backup'); set_config('backup_auto_minute', '30', 'backup'); $timezone = 99; $now = strtotime('next Sunday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0', $next); // Playing with timezones. set_config('backup_auto_weekdays', '1111111', 'backup'); set_config('backup_auto_hour', '20', 'backup'); set_config('backup_auto_minute', '00', 'backup'); $timezone = 99; date_default_timezone_set('Australia/Perth'); $now = strtotime('18:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-20:00'), date('w-H:i', $next)); $timezone = 99; date_default_timezone_set('Europe/Brussels'); $now = strtotime('18:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-20:00'), date('w-H:i', $next)); $timezone = 99; date_default_timezone_set('America/New_York'); $now = strtotime('18:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-20:00'), date('w-H:i', $next)); // Viva Australia! (UTC+8). date_default_timezone_set('Australia/Perth'); $now = strtotime('18:00:00'); $timezone = -10.0; // 12am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-14:00', strtotime('tomorrow')), date('w-H:i', $next)); $timezone = -5.0; // 5am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-09:00', strtotime('tomorrow')), date('w-H:i', $next)); $timezone = 0.0; // 10am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-04:00', strtotime('tomorrow')), date('w-H:i', $next)); $timezone = 3.0; // 1pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-01:00', strtotime('tomorrow')), date('w-H:i', $next)); $timezone = 8.0; // 6pm for the user (same than the server). $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-20:00'), date('w-H:i', $next)); $timezone = 9.0; // 7pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-19:00'), date('w-H:i', $next)); $timezone = 13.0; // 12am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-15:00', strtotime('tomorrow')), date('w-H:i', $next)); // Let's have a Belgian beer! (UTC+1 / UTC+2 DST). date_default_timezone_set('Europe/Brussels'); $now = strtotime('18:00:00'); $dst = date('I'); $timezone = -10.0; // 7am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-07:00', strtotime('tomorrow')) : date('w-08:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = -5.0; // 12pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-02:00', strtotime('tomorrow')) : date('w-03:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 0.0; // 5pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-21:00') : date('w-22:00'); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 3.0; // 8pm for the user (note the expected time is today while in DST). $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-18:00', strtotime('tomorrow')) : date('w-19:00'); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 8.0; // 1am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-13:00', strtotime('tomorrow')) : date('w-14:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 9.0; // 2am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-12:00', strtotime('tomorrow')) : date('w-13:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 13.0; // 6am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-08:00', strtotime('tomorrow')) : date('w-09:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); // The big apple! (UTC-5 / UTC-4 DST). date_default_timezone_set('America/New_York'); $now = strtotime('18:00:00'); $dst = date('I'); $timezone = -10.0; // 1pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-01:00', strtotime('tomorrow')) : date('w-02:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = -5.0; // 6pm for the user (server time). $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-20:00') : date('w-21:00'); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 0.0; // 11pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-15:00', strtotime('tomorrow')) : date('w-16:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 3.0; // 2am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-12:00', strtotime('tomorrow')) : date('w-13:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 8.0; // 7am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-07:00', strtotime('tomorrow')) : date('w-08:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 9.0; // 8am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-06:00', strtotime('tomorrow')) : date('w-07:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 13.0; // 6am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? date('w-02:00', strtotime('tomorrow')) : date('w-03:00', strtotime('tomorrow')); $this->assertEquals($expected, date('w-H:i', $next)); // Some more timezone tests set_config('backup_auto_weekdays', '0100001', 'backup'); set_config('backup_auto_hour', '20', 'backup'); set_config('backup_auto_minute', '00', 'backup'); date_default_timezone_set('Europe/Brussels'); $now = strtotime('next Monday 18:00:00'); $dst = date('I'); $timezone = -12.0; // 1pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '2-09:00' : '2-10:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = -4.0; // 1pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '2-01:00' : '2-02:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 0.0; // 5pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '1-21:00' : '1-22:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 2.0; // 7pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '1-19:00' : '1-20:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 4.0; // 9pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '6-17:00' : '6-18:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 12.0; // 6am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '6-09:00' : '6-10:00'; $this->assertEquals($expected, date('w-H:i', $next)); // Some more timezone tests set_config('backup_auto_weekdays', '0100001', 'backup'); set_config('backup_auto_hour', '02', 'backup'); set_config('backup_auto_minute', '00', 'backup'); date_default_timezone_set('America/New_York'); $now = strtotime('next Monday 04:00:00'); $dst = date('I'); $timezone = -12.0; // 8pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '1-09:00' : '1-10:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = -4.0; // 4am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '6-01:00' : '6-02:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 0.0; // 8am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '5-21:00' : '5-22:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 2.0; // 10am for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '5-19:00' : '5-20:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 4.0; // 12pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '5-17:00' : '5-18:00'; $this->assertEquals($expected, date('w-H:i', $next)); $timezone = 12.0; // 8pm for the user. $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $expected = !$dst ? '5-09:00' : '5-10:00'; $this->assertEquals($expected, date('w-H:i', $next)); }
/** * Provides access to protected method get_backups_to_remove. * * @param array $backupfiles Existing backup files * @param int $now Starting time of the process * @return array Backup files to remove */ public static function testable_get_backups_to_delete($backupfiles, $now) { return parent::get_backups_to_delete($backupfiles, $now); }
/** * Test {@link backup_cron_automated_helper::calculate_next_automated_backup}. */ public function test_next_automated_backup() { global $CFG; $this->resetAfterTest(); set_config('backup_auto_active', '1', 'backup'); $this->setTimezone('Australia/Perth'); // Notes // - backup_auto_weekdays starts on Sunday // - Tests cannot be done in the past // - Only the DST on the server side is handled. // Every Tue and Fri at 11pm. set_config('backup_auto_weekdays', '0010010', 'backup'); set_config('backup_auto_hour', '23', 'backup'); set_config('backup_auto_minute', '0', 'backup'); $timezone = 99; // Ignored, everything is calculated in server timezone!!! $now = strtotime('next Monday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-23:00', date('w-H:i', $next)); $now = strtotime('next Tuesday 18:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-23:00', date('w-H:i', $next)); $now = strtotime('next Wednesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('5-23:00', date('w-H:i', $next)); $now = strtotime('next Thursday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('5-23:00', date('w-H:i', $next)); $now = strtotime('next Friday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('5-23:00', date('w-H:i', $next)); $now = strtotime('next Saturday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-23:00', date('w-H:i', $next)); $now = strtotime('next Sunday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-23:00', date('w-H:i', $next)); // Every Sun and Sat at 12pm. set_config('backup_auto_weekdays', '1000001', 'backup'); set_config('backup_auto_hour', '0', 'backup'); set_config('backup_auto_minute', '0', 'backup'); $now = strtotime('next Monday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Tuesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Wednesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Thursday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Friday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Saturday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-00:00', date('w-H:i', $next)); $now = strtotime('next Sunday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); // Every Sun at 4am. set_config('backup_auto_weekdays', '1000000', 'backup'); set_config('backup_auto_hour', '4', 'backup'); set_config('backup_auto_minute', '0', 'backup'); $now = strtotime('next Monday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Tuesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Wednesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Thursday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Friday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Saturday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); $now = strtotime('next Sunday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-04:00', date('w-H:i', $next)); // Every day but Wed at 8:30pm. set_config('backup_auto_weekdays', '1110111', 'backup'); set_config('backup_auto_hour', '20', 'backup'); set_config('backup_auto_minute', '30', 'backup'); $now = strtotime('next Monday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('1-20:30', date('w-H:i', $next)); $now = strtotime('next Tuesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-20:30', date('w-H:i', $next)); $now = strtotime('next Wednesday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('4-20:30', date('w-H:i', $next)); $now = strtotime('next Thursday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('4-20:30', date('w-H:i', $next)); $now = strtotime('next Friday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('5-20:30', date('w-H:i', $next)); $now = strtotime('next Saturday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-20:30', date('w-H:i', $next)); $now = strtotime('next Sunday 17:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-20:30', date('w-H:i', $next)); // Sun, Tue, Thu, Sat at 12pm. set_config('backup_auto_weekdays', '1010101', 'backup'); set_config('backup_auto_hour', '0', 'backup'); set_config('backup_auto_minute', '0', 'backup'); $now = strtotime('next Monday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-00:00', date('w-H:i', $next)); $now = strtotime('next Tuesday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('4-00:00', date('w-H:i', $next)); $now = strtotime('next Wednesday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('4-00:00', date('w-H:i', $next)); $now = strtotime('next Thursday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Friday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('6-00:00', date('w-H:i', $next)); $now = strtotime('next Saturday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0-00:00', date('w-H:i', $next)); $now = strtotime('next Sunday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('2-00:00', date('w-H:i', $next)); // None. set_config('backup_auto_weekdays', '0000000', 'backup'); set_config('backup_auto_hour', '15', 'backup'); set_config('backup_auto_minute', '30', 'backup'); $now = strtotime('next Sunday 13:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals('0', $next); // Playing with timezones. set_config('backup_auto_weekdays', '1111111', 'backup'); set_config('backup_auto_hour', '20', 'backup'); set_config('backup_auto_minute', '00', 'backup'); $this->setTimezone('Australia/Perth'); $now = strtotime('18:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-20:00'), date('w-H:i', $next)); $this->setTimezone('Europe/Brussels'); $now = strtotime('18:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-20:00'), date('w-H:i', $next)); $this->setTimezone('America/New_York'); $now = strtotime('18:00:00'); $next = backup_cron_automated_helper::calculate_next_automated_backup($timezone, $now); $this->assertEquals(date('w-20:00'), date('w-H:i', $next)); }