Merge branch 'w23_MDL-33555_m23_assignfk' of git://github.com/skodak/moodle
[moodle.git] / backup / util / helper / backup_cron_helper.class.php
CommitLineData
bac233d3
SH
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
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.
9//
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.
14//
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/>.
17
18
19/**
20 * Utility helper for automated backups run through cron.
21 *
22 * @package core
23 * @subpackage backup
24 * @copyright 2010 Sam Hemelryk
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 */
27
28/**
29 * This class is an abstract class with methods that can be called to aid the
30 * running of automated backups over cron.
31 */
32abstract class backup_cron_automated_helper {
33
34 /** automated backups are active and ready to run */
35 const STATE_OK = 0;
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;
40
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;
49
081c914b
SH
50 /** Run if required by the schedule set in config. Default. **/
51 const RUN_ON_SCHEDULE = 0;
743fff98
PS
52 /** Run immediately. **/
53 const RUN_IMMEDIATELY = 1;
081c914b
SH
54
55 const AUTO_BACKUP_DISABLED = 0;
56 const AUTO_BACKUP_ENABLED = 1;
57 const AUTO_BACKUP_MANUAL = 2;
bac233d3
SH
58
59 /**
60 * Runs the automated backups if required
61 *
62 * @global moodle_database $DB
63 */
081c914b 64 public static function run_automated_backup($rundirective = self::RUN_ON_SCHEDULE) {
bac233d3
SH
65 global $CFG, $DB;
66
67 $status = true;
68 $emailpending = false;
69 $now = time();
70
71 mtrace("Checking automated backup status",'...');
081c914b 72 $state = backup_cron_automated_helper::get_automated_backup_state($rundirective);
bac233d3
SH
73 if ($state === backup_cron_automated_helper::STATE_DISABLED) {
74 mtrace('INACTIVE');
081c914b 75 return $state;
bac233d3
SH
76 } else if ($state === backup_cron_automated_helper::STATE_RUNNING) {
77 mtrace('RUNNING');
743fff98 78 if ($rundirective == self::RUN_IMMEDIATELY) {
beae4a66 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.');
081c914b
SH
80 } else {
81 mtrace("automated backup are already running. Execution delayed");
82 }
83 return $state;
bac233d3
SH
84 } else {
85 mtrace('OK');
86 }
87 backup_cron_automated_helper::set_state_running();
88
89 mtrace("Getting admin info");
90 $admin = get_admin();
91 if (!$admin) {
92 mtrace("Error: No admin account was found");
93 $state = false;
94 }
95
96 if ($status) {
97 mtrace("Checking courses");
98 mtrace("Skipping deleted courses", '...');
99 mtrace(sprintf("%d courses", backup_cron_automated_helper::remove_deleted_courses_from_schedule()));
100 }
101
102 if ($status) {
103
104 mtrace('Running required automated backups...');
105
106 // This could take a while!
107 @set_time_limit(0);
108 raise_memory_limit(MEMORY_EXTRA);
109
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);
114 }
115
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));
124 }
125
e2558cd3
MG
126 // Skip courses that do not yet need backup
127 $skipped = !(($backupcourse->nextstarttime >= 0 && $backupcourse->nextstarttime < $now) || $rundirective == self::RUN_IMMEDIATELY);
bac233d3 128 // Skip backup of unavailable courses that have remained unmodified in a month
e2558cd3
MG
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
a6c124f5 131 $sqlwhere = "course=:courseid AND time>:time AND ". $DB->sql_like('action', ':action', false, true, true);
e2558cd3 132 $params = array('courseid' => $course->id, 'time' => $now-31*24*60*60, 'action' => '%view%');
a6c124f5
MG
133 $logexists = $DB->record_exists_select('log', $sqlwhere, $params);
134 if (!$logexists) {
e2558cd3
MG
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);
139 $skipped = true;
140 }
141 }
142 //Now we backup every non-skipped course
143 if (!$skipped) {
bac233d3
SH
144 mtrace('Backing up '.$course->fullname, '...');
145
146 //We have to send a email because we have included at least one backup
147 $emailpending = true;
743fff98 148
bac233d3
SH
149 //Only make the backup if laststatus isn't 2-UNFINISHED (uncontrolled error)
150 if ($backupcourse->laststatus != 2) {
151 //Set laststarttime
152 $starttime = time();
153
154 $backupcourse->laststarttime = time();
155 $backupcourse->laststatus = backup_cron_automated_helper::BACKUP_STATUS_UNFINISHED;
156 $DB->update_record('backup_courses', $backupcourse);
157
158 $backupcourse->laststatus = backup_cron_automated_helper::launch_automated_backup($course, $backupcourse->laststarttime, $admin->id);
159 $backupcourse->lastendtime = time();
160 $backupcourse->nextstarttime = $nextstarttime;
161
162 $DB->update_record('backup_courses', $backupcourse);
163
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);
168 }
169 }
170
171 mtrace("complete - next execution: $showtime");
172 }
173 }
174 $rs->close();
175 }
176
177 //Send email to admin if necessary
178 if ($emailpending) {
179 mtrace("Sending email to admin");
180 $message = "";
181
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);
184
185 //Build the message text
186 //Summary
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";
194
195 //Reference
196 if ($haserrors) {
197 $message .= " ".get_string('backupfailed')."\n\n";
daca599f 198 $dest_url = "$CFG->wwwroot/report/backups/index.php";
bac233d3
SH
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'));
204 } else {
205 $message .= " ".get_string('backupfinished')."\n";
206 }
207
208 //Build the message subject
209 $site = get_site();
8ebbb06a 210 $prefix = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID))).": ";
bac233d3
SH
211 if ($haserrors) {
212 $prefix .= "[".strtoupper(get_string('error'))."] ";
213 }
214 $subject = $prefix.get_string('automatedbackupstatus', 'backup');
215
216 //Send the message
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 = '';
226
227 $eventdata->component = 'moodle';
228 $eventdata->name = 'backup';
229
230 message_send($eventdata);
231 }
232
233 //Everything is finished stop backup_auto_running
234 backup_cron_automated_helper::set_state_running(false);
235
236 mtrace('Automated backups complete.');
237
238 return $status;
239 }
240
241 /**
242 * Gets the results from the last automated backup that was run based upon
243 * the statuses of the courses that were looked at.
244 *
245 * @global moodle_database $DB
246 * @return array
247 */
248 public static function get_backup_status_array() {
249 global $DB;
250
251 $result = 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,
256 );
257
258 $statuses = $DB->get_records_sql('SELECT DISTINCT bc.laststatus, COUNT(bc.courseid) statuscount FROM {backup_courses} bc GROUP BY bc.laststatus');
259
260 foreach ($statuses as $status) {
261 if (empty($status->statuscount)) {
262 $status->statuscount = 0;
263 }
264 $result[(int)$status->laststatus] += $status->statuscount;
265 }
266
267 return $result;
268 }
269
270 /**
271 * Works out the next time the automated backup should be run.
272 *
273 * @param mixed $timezone
274 * @param int $now
275 * @return int
276 */
277 public static function calculate_next_automated_backup($timezone, $now) {
278
279 $result = -1;
280 $config = get_config('backup');
281 $midnight = usergetmidnight($now, $timezone);
282 $date = usergetdate($now, $timezone);
743fff98 283
bac233d3
SH
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");
287 if (empty($daysfromtoday)) {
288 $daysfromtoday = 1;
289 }
290
291 //If some day has been found
292 if ($daysfromtoday !== false) {
293 //Calculate distance
294 $dist = ($daysfromtoday * 86400) + //Days distance
295 ($config->backup_auto_hour * 3600) + //Hours distance
296 ($config->backup_auto_minute * 60); //Minutes distance
297 $result = $midnight + $dist;
298 }
299
300 //If that time is past, call the function recursively to obtain the next valid day
301 if ($result > 0 && $result < time()) {
302 $result = self::calculate_next_automated_backup($timezone, $result);
303 }
304
305 return $result;
306 }
307
308 /**
309 * Launches a automated backup routine for the given course
310 *
311 * @param stdClass $course
312 * @param int $starttime
313 * @param int $userid
314 * @return bool
315 */
316 public static function launch_automated_backup($course, $starttime, $userid) {
317
fde4c609 318 $outcome = true;
bac233d3
SH
319 $config = get_config('backup');
320 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_AUTOMATED, $userid);
321
322 try {
323
324 $settings = array(
325 'users' => 'backup_auto_users',
0d5e5644 326 'role_assignments' => 'backup_auto_role_assignments',
bac233d3
SH
327 'activities' => 'backup_auto_activities',
328 'blocks' => 'backup_auto_blocks',
329 'filters' => 'backup_auto_filters',
330 'comments' => 'backup_auto_comments',
331 'completion_information' => 'backup_auto_userscompletion',
332 'logs' => 'backup_auto_logs',
333 'histories' => 'backup_auto_histories'
334 );
335 foreach ($settings as $setting => $configsetting) {
336 if ($bc->get_plan()->setting_exists($setting)) {
337 $bc->get_plan()->get_setting($setting)->set_value($config->{$configsetting});
338 }
339 }
340
341 // Set the default filename
342 $format = $bc->get_format();
343 $type = $bc->get_type();
344 $id = $bc->get_id();
345 $users = $bc->get_plan()->get_setting('users')->get_value();
346 $anonymised = $bc->get_plan()->get_setting('anonymize')->get_value();
347 $bc->get_plan()->get_setting('filename')->set_value(backup_plan_dbops::get_default_backup_filename($format, $type, $id, $users, $anonymised));
743fff98 348
bac233d3
SH
349 $bc->set_status(backup::STATUS_AWAITING);
350
fde4c609 351 $bc->execute_plan();
bac233d3
SH
352 $results = $bc->get_results();
353 $file = $results['backup_destination'];
354 $dir = $config->backup_auto_destination;
355 $storage = (int)$config->backup_auto_storage;
356 if (!file_exists($dir) || !is_dir($dir) || !is_writable($dir)) {
357 $dir = null;
358 }
359 if (!empty($dir) && $storage !== 0) {
66150286 360 $filename = backup_plan_dbops::get_default_backup_filename($format, $type, $course->id, $users, $anonymised, !$config->backup_shortname);
bac233d3
SH
361 $outcome = $file->copy_content_to($dir.'/'.$filename);
362 if ($outcome && $storage === 1) {
363 $file->delete();
364 }
365 }
366
fde4c609
EL
367 } catch (moodle_exception $e) {
368 $bc->log('backup_auto_failed_on_course', backup::LOG_ERROR, $course->shortname); // Log error header.
369 $bc->log('Exception: ' . $e->errorcode, backup::LOG_ERROR, $e->a, 1); // Log original exception problem.
370 $bc->log('Debug: ' . $e->debuginfo, backup::LOG_DEBUG, null, 1); // Log original debug information.
ca1292e0 371 $outcome = false;
bac233d3
SH
372 }
373
ca1292e0
SH
374 $bc->destroy();
375 unset($bc);
376
fde4c609 377 return $outcome;
bac233d3
SH
378 }
379
bac233d3
SH
380 /**
381 * Removes deleted courses fromn the backup_courses table so that we don't
382 * waste time backing them up.
383 *
384 * @global moodle_database $DB
385 * @return int
386 */
387 public static function remove_deleted_courses_from_schedule() {
388 global $DB;
389 $skipped = 0;
390 $sql = "SELECT bc.courseid FROM {backup_courses} bc WHERE bc.courseid NOT IN (SELECT c.id FROM {course} c)";
391 $rs = $DB->get_recordset_sql($sql);
392 foreach ($rs as $deletedcourse) {
393 //Doesn't exist, so delete from backup tables
394 $DB->delete_records('backup_courses', array('courseid'=>$deletedcourse->courseid));
395 $skipped++;
396 }
397 $rs->close();
398 return $skipped;
399 }
400
401 /**
402 * Gets the state of the automated backup system.
403 *
404 * @global moodle_database $DB
405 * @return int One of self::STATE_*
406 */
081c914b 407 public static function get_automated_backup_state($rundirective = self::RUN_ON_SCHEDULE) {
bac233d3
SH
408 global $DB;
409
410 $config = get_config('backup');
081c914b
SH
411 $active = (int)$config->backup_auto_active;
412 if ($active === self::AUTO_BACKUP_DISABLED || ($rundirective == self::RUN_ON_SCHEDULE && $active === self::AUTO_BACKUP_MANUAL)) {
bac233d3
SH
413 return self::STATE_DISABLED;
414 } else if (!empty($config->backup_auto_running)) {
beae4a66
EL
415 // Detect if the backup_auto_running semaphore is a valid one
416 // by looking for recent activity in the backup_controllers table
417 // for backups of type backup::MODE_AUTOMATED
418 $timetosee = 60 * 90; // Time to consider in order to clean the semaphore
419 $params = array( 'purpose' => backup::MODE_AUTOMATED, 'timetolook' => (time() - $timetosee));
420 if ($DB->record_exists_select('backup_controllers',
421 "operation = 'backup' AND type = 'course' AND purpose = :purpose AND timemodified > :timetolook", $params)) {
422 return self::STATE_RUNNING; // Recent activity found, still running
423 } else {
424 // No recent activity found, let's clean the semaphore
425 mtrace('Automated backups activity not found in last ' . (int)$timetosee/60 . ' minutes. Cleaning running status');
426 backup_cron_automated_helper::set_state_running(false);
427 }
bac233d3
SH
428 }
429 return self::STATE_OK;
430 }
431
432 /**
433 * Sets the state of the automated backup system.
434 *
435 * @param bool $running
436 * @return bool
437 */
438 public static function set_state_running($running = true) {
439 if ($running === true) {
440 if (self::get_automated_backup_state() === self::STATE_RUNNING) {
441 throw new backup_exception('backup_automated_already_running');
442 }
443 set_config('backup_auto_running', '1', 'backup');
444 } else {
445 unset_config('backup_auto_running', 'backup');
446 }
447 return true;
448 }
449
450 /**
451 * Removes excess backups from the external system and the local file system.
452 *
453 * The number of backups keep comes from $config->backup_auto_keep
454 *
455 * @param stdClass $course
456 * @return bool
457 */
458 public static function remove_excess_backups($course) {
459 $config = get_config('backup');
460 $keep = (int)$config->backup_auto_keep;
461 $storage = $config->backup_auto_storage;
462 $dir = $config->backup_auto_destination;
463
6f3451e5 464 $backupword = str_replace(' ', '_', textlib::strtolower(get_string('backupfilename')));
bac233d3
SH
465 $backupword = trim(clean_filename($backupword), '_');
466
467 if (!file_exists($dir) || !is_dir($dir) || !is_writable($dir)) {
468 $dir = null;
469 }
470
471 // Clean up excess backups in the course backup filearea
472 if ($storage == 0 || $storage == 2) {
473 $fs = get_file_storage();
474 $context = get_context_instance(CONTEXT_COURSE, $course->id);
475 $component = 'backup';
476 $filearea = 'automated';
477 $itemid = 0;
478 $files = array();
8afbe44f 479 // Store all the matching files into timemodified => stored_file array
bac233d3
SH
480 foreach ($fs->get_area_files($context->id, $component, $filearea, $itemid) as $file) {
481 if (strpos($file->get_filename(), $backupword) !== 0) {
482 continue;
483 }
484 $files[$file->get_timemodified()] = $file;
485 }
8afbe44f
EL
486 if (count($files) <= $keep) {
487 // There are less matching files than the desired number to keep
488 // do there is nothing to clean up.
489 return 0;
490 }
491 // Sort by keys descending (newer to older filemodified)
492 krsort($files);
bac233d3
SH
493 $remove = array_splice($files, $keep);
494 foreach ($remove as $file) {
495 $file->delete();
496 }
8afbe44f 497 //mtrace('Removed '.count($remove).' old backup file(s) from the automated filearea');
bac233d3
SH
498 }
499
500 // Clean up excess backups in the specified external directory
501 if (!empty($dir) && ($storage == 1 || $storage == 2)) {
8afbe44f
EL
502 // Calculate backup filename regex, ignoring the date/time/info parts that can be
503 // variable, depending of languages, formats and automated backup settings
bac233d3 504 $filename = $backupword . '-' . backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-' .$course->id . '-';
8afbe44f 505 $regex = '#^'.preg_quote($filename, '#').'.*\.mbz$#';
bac233d3 506
8afbe44f 507 // Store all the matching files into fullpath => timemodified array
bac233d3
SH
508 $files = array();
509 foreach (scandir($dir) as $file) {
510 if (preg_match($regex, $file, $matches)) {
8afbe44f 511 $files[$file] = filemtime($dir . '/' . $file);
bac233d3
SH
512 }
513 }
514 if (count($files) <= $keep) {
515 // There are less matching files than the desired number to keep
516 // do there is nothing to clean up.
517 return 0;
518 }
8afbe44f 519 // Sort by values descending (newer to older filemodified)
bac233d3
SH
520 arsort($files);
521 $remove = array_splice($files, $keep);
522 foreach (array_keys($remove) as $file) {
8afbe44f 523 unlink($dir . '/' . $file);
bac233d3
SH
524 }
525 //mtrace('Removed '.count($remove).' old backup file(s) from external directory');
526 }
527
528 return true;
529 }
02cf6919 530}