3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * Utility helper for automated backups run through cron.
24 * @copyright 2010 Sam Hemelryk
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 * This class is an abstract class with methods that can be called to aid the
30 * running of automated backups over cron.
32 abstract class backup_cron_automated_helper {
34 /** automated backups are active and ready to run */
36 /** automated backups are disabled and will not be run */
37 const STATE_DISABLED = 1;
38 /** automated backups are all ready running! */
39 const STATE_RUNNING = 2;
41 /** Course automated backup completed successfully */
42 const BACKUP_STATUS_OK = 1;
43 /** Course automated backup errored */
44 const BACKUP_STATUS_ERROR = 0;
45 /** Course automated backup never finished */
46 const BACKUP_STATUS_UNFINISHED = 2;
47 /** Course automated backup was skipped */
48 const BACKUP_STATUS_SKIPPED = 3;
50 /** Run if required by the schedule set in config. Default. **/
51 const RUN_ON_SCHEDULE = 0;
52 /** Run immediately. **/
53 const RUN_IMMEDIATELY = 1;
55 const AUTO_BACKUP_DISABLED = 0;
56 const AUTO_BACKUP_ENABLED = 1;
57 const AUTO_BACKUP_MANUAL = 2;
60 * Runs the automated backups if required
62 * @global moodle_database $DB
64 public static function run_automated_backup($rundirective = self::RUN_ON_SCHEDULE) {
68 $emailpending = false;
71 mtrace("Checking automated backup status",'...');
72 $state = backup_cron_automated_helper::get_automated_backup_state($rundirective);
73 if ($state === backup_cron_automated_helper::STATE_DISABLED) {
76 } else if ($state === backup_cron_automated_helper::STATE_RUNNING) {
78 if ($rundirective == self::RUN_IMMEDIATELY) {
79 mtrace('Automated backups are already running. If this script is being run by cron this constitues an error. You will need to increase the time between executions within cron.');
81 mtrace("automated backup are already running. Execution delayed");
87 backup_cron_automated_helper::set_state_running();
89 mtrace("Getting admin info");
92 mtrace("Error: No admin account was found");
97 mtrace("Checking courses");
98 mtrace("Skipping deleted courses", '...');
99 mtrace(sprintf("%d courses", backup_cron_automated_helper::remove_deleted_courses_from_schedule()));
104 mtrace('Running required automated backups...');
106 // This could take a while!
108 raise_memory_limit(MEMORY_EXTRA);
110 $nextstarttime = backup_cron_automated_helper::calculate_next_automated_backup($admin->timezone, $now);
111 $showtime = "undefined";
112 if ($nextstarttime > 0) {
113 $showtime = userdate($nextstarttime,"",$admin->timezone);
116 $rs = $DB->get_recordset('course');
117 foreach ($rs as $course) {
118 $backupcourse = $DB->get_record('backup_courses', array('courseid'=>$course->id));
119 if (!$backupcourse) {
120 $backupcourse = new stdClass;
121 $backupcourse->courseid = $course->id;
122 $DB->insert_record('backup_courses',$backupcourse);
123 $backupcourse = $DB->get_record('backup_courses', array('courseid'=>$course->id));
126 // Skip courses that do not yet need backup
127 $skipped = !(($backupcourse->nextstarttime >= 0 && $backupcourse->nextstarttime < $now) || $rundirective == self::RUN_IMMEDIATELY);
128 // Skip backup of unavailable courses that have remained unmodified in a month
129 if (!$skipped && empty($course->visible) && ($now - $course->timemodified) > 31*24*60*60) { //Hidden + settings were unmodified last month
130 //Check log if there were any modifications to the course content
131 $sqlwhere = "course=:courseid AND time>:time AND ". $DB->sql_like('action', ':action', false, true, true);
132 $params = array('courseid' => $course->id, 'time' => $now-31*24*60*60, 'action' => '%view%');
133 $logexists = $DB->record_exists_select('log', $sqlwhere, $params);
135 $backupcourse->laststatus = backup_cron_automated_helper::BACKUP_STATUS_SKIPPED;
136 $backupcourse->nextstarttime = $nextstarttime;
137 $DB->update_record('backup_courses', $backupcourse);
138 mtrace('Skipping unchanged course '.$course->fullname);
142 //Now we backup every non-skipped course
144 mtrace('Backing up '.$course->fullname, '...');
146 //We have to send a email because we have included at least one backup
147 $emailpending = true;
149 //Only make the backup if laststatus isn't 2-UNFINISHED (uncontrolled error)
150 if ($backupcourse->laststatus != 2) {
154 $backupcourse->laststarttime = time();
155 $backupcourse->laststatus = backup_cron_automated_helper::BACKUP_STATUS_UNFINISHED;
156 $DB->update_record('backup_courses', $backupcourse);
158 $backupcourse->laststatus = backup_cron_automated_helper::launch_automated_backup($course, $backupcourse->laststarttime, $admin->id);
159 $backupcourse->lastendtime = time();
160 $backupcourse->nextstarttime = $nextstarttime;
162 $DB->update_record('backup_courses', $backupcourse);
164 if ($backupcourse->laststatus) {
165 // Clean up any excess course backups now that we have
166 // taken a successful backup.
167 $removedcount = backup_cron_automated_helper::remove_excess_backups($course);
171 mtrace("complete - next execution: $showtime");
177 //Send email to admin if necessary
179 mtrace("Sending email to admin");
182 $count = backup_cron_automated_helper::get_backup_status_array();
183 $haserrors = ($count[backup_cron_automated_helper::BACKUP_STATUS_ERROR] != 0 || $count[backup_cron_automated_helper::BACKUP_STATUS_UNFINISHED] != 0);
185 //Build the message text
187 $message .= get_string('summary')."\n";
188 $message .= "==================================================\n";
189 $message .= " ".get_string('courses').": ".array_sum($count)."\n";
190 $message .= " ".get_string('ok').": ".$count[backup_cron_automated_helper::BACKUP_STATUS_OK]."\n";
191 $message .= " ".get_string('skipped').": ".$count[backup_cron_automated_helper::BACKUP_STATUS_SKIPPED]."\n";
192 $message .= " ".get_string('error').": ".$count[backup_cron_automated_helper::BACKUP_STATUS_ERROR]."\n";
193 $message .= " ".get_string('unfinished').": ".$count[backup_cron_automated_helper::BACKUP_STATUS_UNFINISHED]."\n\n";
197 $message .= " ".get_string('backupfailed')."\n\n";
198 $dest_url = "$CFG->wwwroot/report/backups/index.php";
199 $message .= " ".get_string('backuptakealook','',$dest_url)."\n\n";
200 //Set message priority
201 $admin->priority = 1;
202 //Reset unfinished to error
203 $DB->set_field('backup_courses','laststatus','0', array('laststatus'=>'2'));
205 $message .= " ".get_string('backupfinished')."\n";
208 //Build the message subject
210 $prefix = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID))).": ";
212 $prefix .= "[".strtoupper(get_string('error'))."] ";
214 $subject = $prefix.get_string('automatedbackupstatus', 'backup');
217 $eventdata = new stdClass();
218 $eventdata->modulename = 'moodle';
219 $eventdata->userfrom = $admin;
220 $eventdata->userto = $admin;
221 $eventdata->subject = $subject;
222 $eventdata->fullmessage = $message;
223 $eventdata->fullmessageformat = FORMAT_PLAIN;
224 $eventdata->fullmessagehtml = '';
225 $eventdata->smallmessage = '';
227 $eventdata->component = 'moodle';
228 $eventdata->name = 'backup';
230 message_send($eventdata);
233 //Everything is finished stop backup_auto_running
234 backup_cron_automated_helper::set_state_running(false);
236 mtrace('Automated backups complete.');
242 * Gets the results from the last automated backup that was run based upon
243 * the statuses of the courses that were looked at.
245 * @global moodle_database $DB
248 public static function get_backup_status_array() {
252 self::BACKUP_STATUS_ERROR => 0,
253 self::BACKUP_STATUS_OK => 0,
254 self::BACKUP_STATUS_UNFINISHED => 0,
255 self::BACKUP_STATUS_SKIPPED => 0,
258 $statuses = $DB->get_records_sql('SELECT DISTINCT bc.laststatus, COUNT(bc.courseid) AS statuscount FROM {backup_courses} bc GROUP BY bc.laststatus');
260 foreach ($statuses as $status) {
261 if (empty($status->statuscount)) {
262 $status->statuscount = 0;
264 $result[(int)$status->laststatus] += $status->statuscount;
271 * Works out the next time the automated backup should be run.
273 * @param mixed $timezone
277 public static function calculate_next_automated_backup($timezone, $now) {
280 $config = get_config('backup');
281 $midnight = usergetmidnight($now, $timezone);
282 $date = usergetdate($now, $timezone);
284 // Get number of days (from today) to execute backups
285 $automateddays = substr($config->backup_auto_weekdays, $date['wday']) . $config->backup_auto_weekdays;
286 $daysfromtoday = strpos($automateddays, "1", 1);
288 // If we can't find the next day, we set it to tomorrow
289 if (empty($daysfromtoday)) {
293 // If some day has been found
294 if ($daysfromtoday !== false) {
295 // Calculate distance
296 $dist = ($daysfromtoday * 86400) + // Days distance
297 ($config->backup_auto_hour * 3600) + // Hours distance
298 ($config->backup_auto_minute * 60); // Minutes distance
299 $result = $midnight + $dist;
302 // If that time is past, call the function recursively to obtain the next valid day
303 if ($result > 0 && $result < time()) {
304 $result = self::calculate_next_automated_backup($timezone, $result);
311 * Launches a automated backup routine for the given course
313 * @param stdClass $course
314 * @param int $starttime
318 public static function launch_automated_backup($course, $starttime, $userid) {
321 $config = get_config('backup');
322 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_AUTOMATED, $userid);
327 'users' => 'backup_auto_users',
328 'role_assignments' => 'backup_auto_role_assignments',
329 'activities' => 'backup_auto_activities',
330 'blocks' => 'backup_auto_blocks',
331 'filters' => 'backup_auto_filters',
332 'comments' => 'backup_auto_comments',
333 'completion_information' => 'backup_auto_userscompletion',
334 'logs' => 'backup_auto_logs',
335 'histories' => 'backup_auto_histories'
337 foreach ($settings as $setting => $configsetting) {
338 if ($bc->get_plan()->setting_exists($setting)) {
339 $bc->get_plan()->get_setting($setting)->set_value($config->{$configsetting});
343 // Set the default filename
344 $format = $bc->get_format();
345 $type = $bc->get_type();
347 $users = $bc->get_plan()->get_setting('users')->get_value();
348 $anonymised = $bc->get_plan()->get_setting('anonymize')->get_value();
349 $bc->get_plan()->get_setting('filename')->set_value(backup_plan_dbops::get_default_backup_filename($format, $type, $id, $users, $anonymised));
351 $bc->set_status(backup::STATUS_AWAITING);
354 $results = $bc->get_results();
355 $file = $results['backup_destination']; // may be empty if file already moved to target location
356 $dir = $config->backup_auto_destination;
357 $storage = (int)$config->backup_auto_storage;
358 if (!file_exists($dir) || !is_dir($dir) || !is_writable($dir)) {
361 if ($file && !empty($dir) && $storage !== 0) {
362 $filename = backup_plan_dbops::get_default_backup_filename($format, $type, $course->id, $users, $anonymised, !$config->backup_shortname);
363 $outcome = $file->copy_content_to($dir.'/'.$filename);
364 if ($outcome && $storage === 1) {
369 } catch (moodle_exception $e) {
370 $bc->log('backup_auto_failed_on_course', backup::LOG_ERROR, $course->shortname); // Log error header.
371 $bc->log('Exception: ' . $e->errorcode, backup::LOG_ERROR, $e->a, 1); // Log original exception problem.
372 $bc->log('Debug: ' . $e->debuginfo, backup::LOG_DEBUG, null, 1); // Log original debug information.
383 * Removes deleted courses fromn the backup_courses table so that we don't
384 * waste time backing them up.
386 * @global moodle_database $DB
389 public static function remove_deleted_courses_from_schedule() {
392 $sql = "SELECT bc.courseid FROM {backup_courses} bc WHERE bc.courseid NOT IN (SELECT c.id FROM {course} c)";
393 $rs = $DB->get_recordset_sql($sql);
394 foreach ($rs as $deletedcourse) {
395 //Doesn't exist, so delete from backup tables
396 $DB->delete_records('backup_courses', array('courseid'=>$deletedcourse->courseid));
404 * Gets the state of the automated backup system.
406 * @global moodle_database $DB
407 * @return int One of self::STATE_*
409 public static function get_automated_backup_state($rundirective = self::RUN_ON_SCHEDULE) {
412 $config = get_config('backup');
413 $active = (int)$config->backup_auto_active;
414 if ($active === self::AUTO_BACKUP_DISABLED || ($rundirective == self::RUN_ON_SCHEDULE && $active === self::AUTO_BACKUP_MANUAL)) {
415 return self::STATE_DISABLED;
416 } else if (!empty($config->backup_auto_running)) {
417 // Detect if the backup_auto_running semaphore is a valid one
418 // by looking for recent activity in the backup_controllers table
419 // for backups of type backup::MODE_AUTOMATED
420 $timetosee = 60 * 90; // Time to consider in order to clean the semaphore
421 $params = array( 'purpose' => backup::MODE_AUTOMATED, 'timetolook' => (time() - $timetosee));
422 if ($DB->record_exists_select('backup_controllers',
423 "operation = 'backup' AND type = 'course' AND purpose = :purpose AND timemodified > :timetolook", $params)) {
424 return self::STATE_RUNNING; // Recent activity found, still running
426 // No recent activity found, let's clean the semaphore
427 mtrace('Automated backups activity not found in last ' . (int)$timetosee/60 . ' minutes. Cleaning running status');
428 backup_cron_automated_helper::set_state_running(false);
431 return self::STATE_OK;
435 * Sets the state of the automated backup system.
437 * @param bool $running
440 public static function set_state_running($running = true) {
441 if ($running === true) {
442 if (self::get_automated_backup_state() === self::STATE_RUNNING) {
443 throw new backup_exception('backup_automated_already_running');
445 set_config('backup_auto_running', '1', 'backup');
447 unset_config('backup_auto_running', 'backup');
453 * Removes excess backups from the external system and the local file system.
455 * The number of backups keep comes from $config->backup_auto_keep
457 * @param stdClass $course
460 public static function remove_excess_backups($course) {
461 $config = get_config('backup');
462 $keep = (int)$config->backup_auto_keep;
463 $storage = $config->backup_auto_storage;
464 $dir = $config->backup_auto_destination;
467 // means keep all backup files
471 $backupword = str_replace(' ', '_', textlib::strtolower(get_string('backupfilename')));
472 $backupword = trim(clean_filename($backupword), '_');
474 if (!file_exists($dir) || !is_dir($dir) || !is_writable($dir)) {
478 // Clean up excess backups in the course backup filearea
479 if ($storage == 0 || $storage == 2) {
480 $fs = get_file_storage();
481 $context = get_context_instance(CONTEXT_COURSE, $course->id);
482 $component = 'backup';
483 $filearea = 'automated';
486 // Store all the matching files into timemodified => stored_file array
487 foreach ($fs->get_area_files($context->id, $component, $filearea, $itemid) as $file) {
488 if (strpos($file->get_filename(), $backupword) !== 0) {
491 $files[$file->get_timemodified()] = $file;
493 if (count($files) <= $keep) {
494 // There are less matching files than the desired number to keep
495 // do there is nothing to clean up.
498 // Sort by keys descending (newer to older filemodified)
500 $remove = array_splice($files, $keep);
501 foreach ($remove as $file) {
504 //mtrace('Removed '.count($remove).' old backup file(s) from the automated filearea');
507 // Clean up excess backups in the specified external directory
508 if (!empty($dir) && ($storage == 1 || $storage == 2)) {
509 // Calculate backup filename regex, ignoring the date/time/info parts that can be
510 // variable, depending of languages, formats and automated backup settings
513 // MDL-33531: use different filenames depending on backup_shortname option
514 if ( !empty($config->backup_shortname) ) {
515 $context = get_context_instance(CONTEXT_COURSE, $course->id);
516 $courseref = format_string($course->shortname, true, array('context' => $context));
517 $courseref = str_replace(' ', '_', $courseref);
518 $courseref = textlib::strtolower(trim(clean_filename($courseref), '_'));
520 $courseref = $course->id;
522 $filename = $backupword . '-' . backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-' .$courseref . '-';
523 $regex = '#^'.preg_quote($filename, '#').'.*\.mbz$#';
525 // Store all the matching files into fullpath => timemodified array
527 foreach (scandir($dir) as $file) {
528 if (preg_match($regex, $file, $matches)) {
529 $files[$file] = filemtime($dir . '/' . $file);
532 if (count($files) <= $keep) {
533 // There are less matching files than the desired number to keep
534 // do there is nothing to clean up.
537 // Sort by values descending (newer to older filemodified)
539 $remove = array_splice($files, $keep);
540 foreach (array_keys($remove) as $file) {
541 unlink($dir . '/' . $file);
543 //mtrace('Removed '.count($remove).' old backup file(s) from external directory');