MDL-33531 backup Added format_string to course shortname
[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) {
67ab929c 113 $showtime = userdate($nextstarttime,"",$admin->timezone);
bac233d3
SH
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 126 // Skip courses that do not yet need backup
67ab929c 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) {
67ab929c 144 mtrace('Backing up '.$course->fullname, '...');
bac233d3
SH
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();
a689cd1d 210 $prefix = format_string($site->shortname, true, array('context' => context_course::instance(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 *
67ab929c
AB
273 * @param mixed $timezone
274 * @param int $now
275 * @return int
bac233d3
SH
276 */
277 public static function calculate_next_automated_backup($timezone, $now) {
278
67ab929c 279 $result = -1;
bac233d3 280 $config = get_config('backup');
67ab929c 281 $midnight = usergetmidnight($now, $timezone);
bac233d3 282 $date = usergetdate($now, $timezone);
743fff98 283
67ab929c 284 // Get number of days (from today) to execute backups
d4a49ba2 285 $automateddays = substr($config->backup_auto_weekdays, $date['wday']) . $config->backup_auto_weekdays;
67ab929c 286 $daysfromtoday = strpos($automateddays, "1", 1);
d4a49ba2 287
67ab929c
AB
288 // If we can't find the next day, we set it to tomorrow
289 if (empty($daysfromtoday)) {
290 $daysfromtoday = 1;
bac233d3
SH
291 }
292
67ab929c
AB
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;
bac233d3
SH
300 }
301
67ab929c
AB
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);
bac233d3
SH
305 }
306
307 return $result;
308 }
309
310 /**
311 * Launches a automated backup routine for the given course
312 *
313 * @param stdClass $course
314 * @param int $starttime
315 * @param int $userid
316 * @return bool
317 */
318 public static function launch_automated_backup($course, $starttime, $userid) {
319
fde4c609 320 $outcome = true;
bac233d3
SH
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);
323
324 try {
325
326 $settings = array(
327 'users' => 'backup_auto_users',
0d5e5644 328 'role_assignments' => 'backup_auto_role_assignments',
bac233d3
SH
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'
336 );
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});
340 }
341 }
342
343 // Set the default filename
344 $format = $bc->get_format();
345 $type = $bc->get_type();
346 $id = $bc->get_id();
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));
743fff98 350
bac233d3
SH
351 $bc->set_status(backup::STATUS_AWAITING);
352
fde4c609 353 $bc->execute_plan();
bac233d3 354 $results = $bc->get_results();
096702f6 355 $file = $results['backup_destination']; // may be empty if file already moved to target location
bac233d3
SH
356 $dir = $config->backup_auto_destination;
357 $storage = (int)$config->backup_auto_storage;
358 if (!file_exists($dir) || !is_dir($dir) || !is_writable($dir)) {
359 $dir = null;
360 }
096702f6 361 if ($file && !empty($dir) && $storage !== 0) {
66150286 362 $filename = backup_plan_dbops::get_default_backup_filename($format, $type, $course->id, $users, $anonymised, !$config->backup_shortname);
bac233d3
SH
363 $outcome = $file->copy_content_to($dir.'/'.$filename);
364 if ($outcome && $storage === 1) {
365 $file->delete();
366 }
367 }
368
fde4c609
EL
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.
ca1292e0 373 $outcome = false;
bac233d3
SH
374 }
375
ca1292e0
SH
376 $bc->destroy();
377 unset($bc);
378
fde4c609 379 return $outcome;
bac233d3
SH
380 }
381
bac233d3
SH
382 /**
383 * Removes deleted courses fromn the backup_courses table so that we don't
384 * waste time backing them up.
385 *
386 * @global moodle_database $DB
387 * @return int
388 */
389 public static function remove_deleted_courses_from_schedule() {
390 global $DB;
391 $skipped = 0;
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));
397 $skipped++;
398 }
399 $rs->close();
400 return $skipped;
401 }
402
403 /**
404 * Gets the state of the automated backup system.
405 *
406 * @global moodle_database $DB
407 * @return int One of self::STATE_*
408 */
081c914b 409 public static function get_automated_backup_state($rundirective = self::RUN_ON_SCHEDULE) {
bac233d3
SH
410 global $DB;
411
412 $config = get_config('backup');
081c914b 413 $active = (int)$config->backup_auto_active;
67ab929c 414 if ($active === self::AUTO_BACKUP_DISABLED || ($rundirective == self::RUN_ON_SCHEDULE && $active === self::AUTO_BACKUP_MANUAL)) {
bac233d3
SH
415 return self::STATE_DISABLED;
416 } else if (!empty($config->backup_auto_running)) {
beae4a66
EL
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
425 } else {
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);
429 }
bac233d3
SH
430 }
431 return self::STATE_OK;
432 }
433
434 /**
435 * Sets the state of the automated backup system.
436 *
437 * @param bool $running
438 * @return bool
439 */
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');
444 }
445 set_config('backup_auto_running', '1', 'backup');
446 } else {
447 unset_config('backup_auto_running', 'backup');
448 }
449 return true;
450 }
451
452 /**
453 * Removes excess backups from the external system and the local file system.
454 *
455 * The number of backups keep comes from $config->backup_auto_keep
456 *
457 * @param stdClass $course
458 * @return bool
459 */
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;
465
dbf7784e
PS
466 if ($keep == 0) {
467 // means keep all backup files
468 return true;
469 }
470
6f3451e5 471 $backupword = str_replace(' ', '_', textlib::strtolower(get_string('backupfilename')));
bac233d3
SH
472 $backupword = trim(clean_filename($backupword), '_');
473
474 if (!file_exists($dir) || !is_dir($dir) || !is_writable($dir)) {
475 $dir = null;
476 }
477
478 // Clean up excess backups in the course backup filearea
479 if ($storage == 0 || $storage == 2) {
480 $fs = get_file_storage();
a689cd1d 481 $context = context_course::instance($course->id);
bac233d3
SH
482 $component = 'backup';
483 $filearea = 'automated';
484 $itemid = 0;
485 $files = array();
8afbe44f 486 // Store all the matching files into timemodified => stored_file array
bac233d3
SH
487 foreach ($fs->get_area_files($context->id, $component, $filearea, $itemid) as $file) {
488 if (strpos($file->get_filename(), $backupword) !== 0) {
489 continue;
490 }
491 $files[$file->get_timemodified()] = $file;
492 }
8afbe44f
EL
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.
496 return 0;
497 }
498 // Sort by keys descending (newer to older filemodified)
499 krsort($files);
bac233d3
SH
500 $remove = array_splice($files, $keep);
501 foreach ($remove as $file) {
502 $file->delete();
503 }
8afbe44f 504 //mtrace('Removed '.count($remove).' old backup file(s) from the automated filearea');
bac233d3
SH
505 }
506
507 // Clean up excess backups in the specified external directory
508 if (!empty($dir) && ($storage == 1 || $storage == 2)) {
8afbe44f
EL
509 // Calculate backup filename regex, ignoring the date/time/info parts that can be
510 // variable, depending of languages, formats and automated backup settings
ab519e88
LN
511
512
513 // MDL-33531: use different filenames depending on backup_shortname option
bde0eac5 514 if ( !empty($config->backup_shortname) ) {
f4162eff
DM
515 $context = get_context_instance(CONTEXT_COURSE, $course->id);
516 $courseref = format_string($course->shortname, true, array('context' => $context));
ab519e88
LN
517 $courseref = str_replace(' ', '_', $courseref);
518 $courseref = textlib::strtolower(trim(clean_filename($courseref), '_'));
519 } else {
520 $courseref = $course->id;
521 }
522 $filename = $backupword . '-' . backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-' .$courseref . '-';
8afbe44f 523 $regex = '#^'.preg_quote($filename, '#').'.*\.mbz$#';
bac233d3 524
8afbe44f 525 // Store all the matching files into fullpath => timemodified array
bac233d3
SH
526 $files = array();
527 foreach (scandir($dir) as $file) {
528 if (preg_match($regex, $file, $matches)) {
8afbe44f 529 $files[$file] = filemtime($dir . '/' . $file);
bac233d3
SH
530 }
531 }
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.
535 return 0;
536 }
8afbe44f 537 // Sort by values descending (newer to older filemodified)
bac233d3
SH
538 arsort($files);
539 $remove = array_splice($files, $keep);
540 foreach (array_keys($remove) as $file) {
8afbe44f 541 unlink($dir . '/' . $file);
bac233d3
SH
542 }
543 //mtrace('Removed '.count($remove).' old backup file(s) from external directory');
544 }
545
546 return true;
547 }
02cf6919 548}