Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Utility helper for automated backups run through cron.
19
 *
20
 * This class is an abstract class with methods that can be called to aid the
21
 * running of automated backups over cron.
22
 *
23
 * @package    core
24
 * @subpackage backup
25
 * @copyright  2010 Sam Hemelryk
26
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27
 */
28
abstract class backup_cron_automated_helper {
29
    /** Automated backups are active and ready to run */
30
    const STATE_OK = 0;
31
    /** Automated backups are disabled and will not be run */
32
    const STATE_DISABLED = 1;
33
    /** Automated backups are all ready running! */
34
    const STATE_RUNNING = 2;
35
 
36
    /** Course automated backup completed successfully */
37
    const BACKUP_STATUS_OK = 1;
38
    /** Course automated backup errored */
39
    const BACKUP_STATUS_ERROR = 0;
40
    /** Course automated backup never finished */
41
    const BACKUP_STATUS_UNFINISHED = 2;
42
    /** Course automated backup was skipped */
43
    const BACKUP_STATUS_SKIPPED = 3;
44
    /** Course automated backup had warnings */
45
    const BACKUP_STATUS_WARNING = 4;
46
    /** Course automated backup has yet to be run */
47
    const BACKUP_STATUS_NOTYETRUN = 5;
48
    /** Course automated backup has been added to adhoc task queue */
49
    const BACKUP_STATUS_QUEUED = 6;
50
 
51
    /** Run if required by the schedule set in config. Default. **/
52
    const RUN_ON_SCHEDULE = 0;
53
    /** Run immediately. **/
54
    const RUN_IMMEDIATELY = 1;
55
 
56
    const AUTO_BACKUP_DISABLED = 0;
57
    const AUTO_BACKUP_ENABLED = 1;
58
    const AUTO_BACKUP_MANUAL = 2;
59
 
60
    /** Automated backup storage in course backup filearea */
61
    const STORAGE_COURSE = 0;
62
    /** Automated backup storage in specified directory */
63
    const STORAGE_DIRECTORY = 1;
64
    /** Automated backup storage in course backup filearea and specified directory */
65
    const STORAGE_COURSE_AND_DIRECTORY = 2;
66
 
67
    /**
68
     * Get the courses to backup.
69
     *
70
     * When there are multiple courses to backup enforce some order to the record set.
71
     * The following is the preference order.
72
     * First backup courses that do not have an entry in backup_courses first,
73
     * as they are likely new and never been backed up. Do the oldest modified courses first.
74
     * Then backup courses that have previously been backed up starting with the oldest next start time.
75
     * Finally, all else being equal, defer to the sortorder of the courses.
76
     *
77
     * @param null|int $now timestamp to use in course selection.
78
     * @return moodle_recordset The recordset of matching courses.
79
     */
80
    protected static function get_courses($now = null) {
81
        global $DB;
82
        if ($now == null) {
83
            $now = time();
84
        }
85
 
86
        $sql = 'SELECT c.*,
87
                       COALESCE(bc.nextstarttime, 1) nextstarttime
88
                  FROM {course} c
89
             LEFT JOIN {backup_courses} bc ON bc.courseid = c.id
90
                 WHERE bc.nextstarttime IS NULL OR bc.nextstarttime < ?
91
              ORDER BY nextstarttime ASC,
92
                       c.timemodified DESC,
93
                       c.sortorder';
94
 
95
        $params = array(
96
            $now,  // Only get courses where the backup start time is in the past.
97
        );
98
        $rs = $DB->get_recordset_sql($sql, $params);
99
 
100
        return $rs;
101
    }
102
 
103
    /**
104
     * Runs the automated backups if required
105
     *
106
     * @param bool $rundirective
107
     */
108
    public static function run_automated_backup($rundirective = self::RUN_ON_SCHEDULE) {
109
        $now = time();
110
 
111
        $lock = self::get_automated_backup_lock($rundirective);
112
        if (!$lock) {
113
            return;
114
        }
115
 
116
        try {
117
            mtrace("Checking courses");
118
            mtrace("Skipping deleted courses", '...');
119
            mtrace(sprintf("%d courses", self::remove_deleted_courses_from_schedule()));
120
            mtrace('Running required automated backups...');
121
            \core\cron::trace_time_and_memory();
122
 
123
            mtrace("Getting admin info");
124
            $admin = get_admin();
125
            if (!$admin) {
126
                mtrace("Error: No admin account was found");
127
                return;
128
            }
129
 
130
            $rs = self::get_courses($now); // Get courses to backup.
131
            $emailpending = self::check_and_push_automated_backups($rs, $admin);
132
            $rs->close();
133
 
134
            // Send email to admin if necessary.
135
            set_config(
136
                'backup_auto_emailpending',
137
                $emailpending ? 1 : 0,
138
                'backup',
139
            );
140
        } finally {
141
            // Everything is finished release lock.
142
            $lock->release();
143
            mtrace('Automated backups complete.');
144
        }
145
    }
146
 
147
    /**
148
     * Gets the results from the last automated backup that was run based upon
149
     * the statuses of the courses that were looked at.
150
     *
151
     * @return array
152
     */
153
    public static function get_backup_status_array() {
154
        global $DB;
155
 
156
        $result = array(
157
            self::BACKUP_STATUS_ERROR => 0,
158
            self::BACKUP_STATUS_OK => 0,
159
            self::BACKUP_STATUS_UNFINISHED => 0,
160
            self::BACKUP_STATUS_SKIPPED => 0,
161
            self::BACKUP_STATUS_WARNING => 0,
162
            self::BACKUP_STATUS_NOTYETRUN => 0,
163
            self::BACKUP_STATUS_QUEUED => 0,
164
        );
165
 
166
        $statuses = $DB->get_records_sql('SELECT DISTINCT bc.laststatus,
167
                                            COUNT(bc.courseid) AS statuscount
168
                                            FROM {backup_courses} bc
169
                                            GROUP BY bc.laststatus');
170
 
171
        foreach ($statuses as $status) {
172
            if (empty($status->statuscount)) {
173
                $status->statuscount = 0;
174
            }
175
            $result[(int)$status->laststatus] += $status->statuscount;
176
        }
177
 
178
        return $result;
179
    }
180
 
181
    /**
182
     * Collect details for all statuses of the courses
183
     * and send report to admin.
184
     *
185
     * @param stdClass $admin
186
     * @return array
187
     */
188
    public static function send_backup_status_to_admin($admin) {
189
        global $DB, $CFG;
190
 
191
        mtrace("Sending email to admin");
192
        $message = "";
193
 
194
        $count = self::get_backup_status_array();
195
        $haserrors = ($count[self::BACKUP_STATUS_ERROR] != 0 || $count[self::BACKUP_STATUS_UNFINISHED] != 0);
196
 
197
        // Build the message text.
198
        // Summary.
199
        $message .= get_string('summary') . "\n";
200
        $message .= "==================================================\n";
201
        $message .= '  ' . get_string('courses') . ': ' . array_sum($count) . "\n";
202
        $message .= '  ' . get_string('statusok') . ': ' . $count[self::BACKUP_STATUS_OK] . "\n";
203
        $message .= '  ' . get_string('skipped') . ': ' . $count[self::BACKUP_STATUS_SKIPPED] . "\n";
204
        $message .= '  ' . get_string('error') . ': ' . $count[self::BACKUP_STATUS_ERROR] . "\n";
205
        $message .= '  ' . get_string('unfinished') . ': ' . $count[self::BACKUP_STATUS_UNFINISHED] . "\n";
206
        $message .= '  ' . get_string('backupadhocpending') . ': ' . $count[self::BACKUP_STATUS_QUEUED] . "\n";
207
        $message .= '  ' . get_string('warning') . ': ' . $count[self::BACKUP_STATUS_WARNING] . "\n";
208
        $message .= '  ' . get_string('backupnotyetrun') . ': ' . $count[self::BACKUP_STATUS_NOTYETRUN]."\n\n";
209
 
210
        // Reference.
211
        if ($haserrors) {
212
            $message .= "  ".get_string('backupfailed')."\n\n";
213
            $desturl = "$CFG->wwwroot/report/backups/index.php";
214
            $message .= "  ".get_string('backuptakealook', '', $desturl)."\n\n";
215
            // Set message priority.
216
            $admin->priority = 1;
217
            // Reset error and unfinished statuses to ok if longer than 24 hours.
218
            $sql = "laststatus IN (:statuserror,:statusunfinished) AND laststarttime < :yesterday";
219
            $params = [
220
                'statuserror' => self::BACKUP_STATUS_ERROR,
221
                'statusunfinished' => self::BACKUP_STATUS_UNFINISHED,
222
                'yesterday' => time() - 86400,
223
            ];
224
            $DB->set_field_select('backup_courses', 'laststatus', self::BACKUP_STATUS_OK, $sql, $params);
225
        } else {
226
            $message .= "  ".get_string('backupfinished')."\n";
227
        }
228
 
229
        // Build the message subject.
230
        $site = get_site();
231
        $prefix = format_string($site->shortname, true, array('context' => context_course::instance(SITEID))).": ";
232
        if ($haserrors) {
233
            $prefix .= "[".strtoupper(get_string('error'))."] ";
234
        }
235
        $subject = $prefix.get_string('automatedbackupstatus', 'backup');
236
 
237
        // Send the message.
238
        $eventdata = new \core\message\message();
239
        $eventdata->courseid          = SITEID;
240
        $eventdata->modulename        = 'moodle';
241
        $eventdata->userfrom          = $admin;
242
        $eventdata->userto            = $admin;
243
        $eventdata->subject           = $subject;
244
        $eventdata->fullmessage       = $message;
245
        $eventdata->fullmessageformat = FORMAT_PLAIN;
246
        $eventdata->fullmessagehtml   = '';
247
        $eventdata->smallmessage      = '';
248
 
249
        $eventdata->component         = 'moodle';
250
        $eventdata->name         = 'backup';
251
 
252
        return message_send($eventdata);
253
    }
254
 
255
    /**
256
     * Loop through courses and push to course ad-hoc task if required
257
     *
258
     * @param \record_set $courses
259
     * @param stdClass $admin
260
     * @return boolean
261
     */
262
    private static function check_and_push_automated_backups($courses, $admin) {
263
        global $DB;
264
 
265
        $now = time();
266
        $emailpending = false;
267
 
268
        $nextstarttime = self::calculate_next_automated_backup(null, $now);
269
        $showtime = "undefined";
270
        if ($nextstarttime > 0) {
271
            $showtime = date('r', $nextstarttime);
272
        }
273
 
274
        foreach ($courses as $course) {
275
            $backupcourse = $DB->get_record('backup_courses', array('courseid' => $course->id));
276
            if (!$backupcourse) {
277
                $backupcourse = new stdClass;
278
                $backupcourse->courseid = $course->id;
279
                $backupcourse->laststatus = self::BACKUP_STATUS_NOTYETRUN;
280
                $DB->insert_record('backup_courses', $backupcourse);
281
                $backupcourse = $DB->get_record('backup_courses', array('courseid' => $course->id));
282
            }
283
 
284
            // Check if we are going to be running the backup now.
285
            $shouldrunnow = ($backupcourse->nextstarttime > 0 && $backupcourse->nextstarttime < $now);
286
 
287
            // Check if the course is not scheduled to run right now, or it has been put in queue.
288
            if (!$shouldrunnow || $backupcourse->laststatus == self::BACKUP_STATUS_QUEUED) {
289
                $backupcourse->nextstarttime = $nextstarttime;
290
                $DB->update_record('backup_courses', $backupcourse);
291
                mtrace('Skipping course id ' . $course->id . ': Not scheduled for backup until ' . $showtime);
292
            } else {
293
                $skipped = self::should_skip_course_backup($backupcourse, $course, $nextstarttime);
294
                if (!$skipped) { // If it should not be skipped.
295
 
296
                    // Only make the backup if laststatus isn't 2-UNFINISHED (uncontrolled error or being backed up).
297
                    if ($backupcourse->laststatus != self::BACKUP_STATUS_UNFINISHED) {
298
                        // Add every non-skipped courses to backup adhoc task queue.
299
                        mtrace('Putting backup of course id ' . $course->id . ' in adhoc task queue');
300
 
301
                        // We have to send an email because we have included at least one backup.
302
                        $emailpending = true;
303
                        // Create adhoc task for backup.
304
                        self::push_course_backup_adhoc_task($backupcourse, $admin);
305
                    }
306
                }
307
            }
308
        }
309
 
310
        return $emailpending;
311
    }
312
 
313
    /**
314
     * Check if we can skip this course backup.
315
     *
316
     * @param stdClass $backupcourse
317
     * @param stdClass $course
318
     * @param int $nextstarttime
319
     * @return boolean
320
     */
321
    private static function should_skip_course_backup($backupcourse, $course, $nextstarttime) {
322
        global $DB;
323
 
324
        $config = get_config('backup');
325
        $now = time();
326
         // Assume that we are not skipping anything.
327
         $skipped = false;
328
         $skippedmessage = '';
329
 
330
        // The last backup is considered as successful when OK or SKIPPED.
331
        $lastbackupwassuccessful = ($backupcourse->laststatus == self::BACKUP_STATUS_SKIPPED ||
332
        $backupcourse->laststatus == self::BACKUP_STATUS_OK) && (
333
        $backupcourse->laststarttime > 0 && $backupcourse->lastendtime > 0);
334
 
335
        // If config backup_auto_skip_hidden is set to true, skip courses that are not visible.
336
        if ($config->backup_auto_skip_hidden) {
337
            $skipped = ($config->backup_auto_skip_hidden && !$course->visible);
338
            $skippedmessage = 'Not visible';
339
        }
340
 
341
        // If config backup_auto_skip_modif_days is set to true, skip courses
342
        // that have not been modified since the number of days defined.
343
        if (!$skipped && $lastbackupwassuccessful && $config->backup_auto_skip_modif_days) {
344
            $timenotmodifsincedays = $now - ($config->backup_auto_skip_modif_days * DAYSECS);
345
            // Check log if there were any modifications to the course content.
346
            $logexists = self::is_course_modified($course->id, $timenotmodifsincedays);
347
            $skipped = ($course->timemodified <= $timenotmodifsincedays && !$logexists);
348
            $skippedmessage = 'Not modified in the past '.$config->backup_auto_skip_modif_days.' days';
349
        }
350
 
351
        // If config backup_auto_skip_modif_prev is set to true, skip courses
352
        // that have not been modified since previous backup.
353
        if (!$skipped && $lastbackupwassuccessful && $config->backup_auto_skip_modif_prev) {
354
            // Check log if there were any modifications to the course content.
355
            $logexists = self::is_course_modified($course->id, $backupcourse->laststarttime);
356
            $skipped = ($course->timemodified <= $backupcourse->laststarttime && !$logexists);
357
            $skippedmessage = 'Not modified since previous backup';
358
        }
359
 
360
        if ($skipped) { // Must have been skipped for a reason.
361
            $backupcourse->laststatus = self::BACKUP_STATUS_SKIPPED;
362
            $backupcourse->nextstarttime = $nextstarttime;
363
            $DB->update_record('backup_courses', $backupcourse);
364
            mtrace('Skipping course id ' . $course->id . ': ' . $skippedmessage);
365
        }
366
 
367
        return $skipped;
368
    }
369
 
370
    /**
371
     * Create course backup adhoc task
372
     *
373
     * @param stdClass $backupcourse
374
     * @param stdClass $admin
375
     * @return void
376
     */
377
    private static function push_course_backup_adhoc_task($backupcourse, $admin) {
378
        global $DB;
379
 
380
        $asynctask = new \core\task\course_backup_task();
381
        $asynctask->set_custom_data(array(
382
            'courseid' => $backupcourse->courseid,
383
            'adminid' => $admin->id
384
        ));
385
        $taskid = \core\task\manager::queue_adhoc_task($asynctask);
386
 
387
        // Get the queued tasks.
388
        $queuedtasks = [];
389
        if ($value = get_config('backup', 'backup_auto_adhoctasks')) {
390
            $queuedtasks = explode(',', $value);
391
        }
392
        if ($taskid) {
393
            $queuedtasks[] = (int) $taskid;
394
        }
395
        // Save the queued tasks.
396
        set_config(
397
            'backup_auto_adhoctasks',
398
            implode(',', $queuedtasks),
399
            'backup',
400
        );
401
 
402
        $backupcourse->laststatus = self::BACKUP_STATUS_QUEUED;
403
        $DB->update_record('backup_courses', $backupcourse);
404
    }
405
 
406
    /**
407
     * Works out the next time the automated backup should be run.
408
     *
409
     * @param mixed $ignoredtimezone all settings are in server timezone!
410
     * @param int $now timestamp, should not be in the past, most likely time()
411
     * @return int timestamp of the next execution at server time
412
     */
413
    public static function calculate_next_automated_backup($ignoredtimezone, $now) {
414
 
415
        $config = get_config('backup');
416
 
417
        $backuptime = new DateTime('@' . $now);
418
        $backuptime->setTimezone(core_date::get_server_timezone_object());
419
        $backuptime->setTime($config->backup_auto_hour, $config->backup_auto_minute);
420
 
421
        while ($backuptime->getTimestamp() < $now) {
422
            $backuptime->add(new DateInterval('P1D'));
423
        }
424
 
425
        // Get number of days from backup date to execute backups.
426
        $automateddays = substr($config->backup_auto_weekdays, $backuptime->format('w')) . $config->backup_auto_weekdays;
427
        $daysfromnow = strpos($automateddays, "1");
428
 
429
        // Error, there are no days to schedule the backup for.
430
        if ($daysfromnow === false) {
431
            return 0;
432
        }
433
 
434
        if ($daysfromnow > 0) {
435
            $backuptime->add(new DateInterval('P' . $daysfromnow . 'D'));
436
        }
437
 
438
        return $backuptime->getTimestamp();
439
    }
440
 
441
    /**
442
     * Launches a automated backup routine for the given course
443
     *
444
     * @param stdClass $course
445
     * @param int $starttime
446
     * @param int $userid
447
     * @return bool
448
     */
449
    public static function launch_automated_backup($course, $starttime, $userid) {
450
 
451
        $outcome = self::BACKUP_STATUS_OK;
452
        $config = get_config('backup');
453
        $dir = $config->backup_auto_destination;
454
        $storage = (int)$config->backup_auto_storage;
455
 
456
        $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO,
457
                backup::MODE_AUTOMATED, $userid);
458
 
459
        try {
460
 
461
            // Set the default filename.
462
            $format = $bc->get_format();
463
            $type = $bc->get_type();
464
            $id = $bc->get_id();
465
            $users = $bc->get_plan()->get_setting('users')->get_value();
466
            $anonymised = $bc->get_plan()->get_setting('anonymize')->get_value();
467
            $incfiles = (bool)$config->backup_auto_files;
468
            $bc->get_plan()->get_setting('filename')->set_value(backup_plan_dbops::get_default_backup_filename($format, $type,
469
                    $id, $users, $anonymised, false, $incfiles));
470
 
471
            $bc->set_status(backup::STATUS_AWAITING);
472
 
473
            $bc->execute_plan();
474
            $results = $bc->get_results();
475
            $outcome = self::outcome_from_results($results);
476
            $file = $results['backup_destination']; // May be empty if file already moved to target location.
477
 
478
            // If we need to copy the backup file to an external dir and it is not writable, change status to error.
479
            // This is a feature to prevent moodledata to be filled up and break a site when the admin misconfigured
480
            // the automated backups storage type and destination directory.
481
            if ($storage !== 0 && (empty($dir) || !file_exists($dir) || !is_dir($dir) || !is_writable($dir))) {
482
                $bc->log('Specified backup directory is not writable - ', backup::LOG_ERROR, $dir);
483
                $dir = null;
484
                $outcome = self::BACKUP_STATUS_ERROR;
485
            }
486
 
487
            // Copy file only if there was no error.
488
            if ($file && !empty($dir) && $storage !== 0 && $outcome != self::BACKUP_STATUS_ERROR) {
489
                $filename = backup_plan_dbops::get_default_backup_filename($format, $type, $course->id, $users, $anonymised,
490
                        !$config->backup_shortname);
491
                if (!$file->copy_content_to($dir.'/'.$filename)) {
492
                    $bc->log('Attempt to copy backup file to the specified directory failed - ',
493
                            backup::LOG_ERROR, $dir);
494
                    $outcome = self::BACKUP_STATUS_ERROR;
495
                }
496
                if ($outcome != self::BACKUP_STATUS_ERROR && $storage === 1) {
497
                    if (!$file->delete()) {
498
                        $outcome = self::BACKUP_STATUS_WARNING;
499
                        $bc->log('Attempt to delete the backup file from course automated backup area failed - ',
500
                                backup::LOG_WARNING, $file->get_filename());
501
                    }
502
                }
503
            }
504
 
505
        } catch (moodle_exception $e) {
506
            $bc->log('backup_auto_failed_on_course', backup::LOG_ERROR, $course->shortname); // Log error header.
507
            $bc->log('Exception: ' . $e->errorcode, backup::LOG_ERROR, $e->a, 1); // Log original exception problem.
508
            $bc->log('Debug: ' . $e->debuginfo, backup::LOG_DEBUG, null, 1); // Log original debug information.
509
            $outcome = self::BACKUP_STATUS_ERROR;
510
        }
511
 
512
        // Delete the backup file immediately if something went wrong.
513
        if ($outcome === self::BACKUP_STATUS_ERROR) {
514
 
515
            // Delete the file from file area if exists.
516
            if (!empty($file)) {
517
                $file->delete();
518
            }
519
 
520
            // Delete file from external storage if exists.
521
            if ($storage !== 0 && !empty($filename) && file_exists($dir.'/'.$filename)) {
522
                @unlink($dir.'/'.$filename);
523
            }
524
        }
525
 
526
        $bc->destroy();
527
        unset($bc);
528
 
529
        return $outcome;
530
    }
531
 
532
    /**
533
     * Returns the backup outcome by analysing its results.
534
     *
535
     * @param array $results returned by a backup
536
     * @return int {@link self::BACKUP_STATUS_OK} and other constants
537
     */
538
    public static function outcome_from_results($results) {
539
        $outcome = self::BACKUP_STATUS_OK;
540
        foreach ($results as $code => $value) {
541
            // Each possible error and warning code has to be specified in this switch
542
            // which basically analyses the results to return the correct backup status.
543
            switch ($code) {
544
                case 'missing_files_in_pool':
545
                    $outcome = self::BACKUP_STATUS_WARNING;
546
                    break;
547
            }
548
            // If we found the highest error level, we exit the loop.
549
            if ($outcome == self::BACKUP_STATUS_ERROR) {
550
                break;
551
            }
552
        }
553
        return $outcome;
554
    }
555
 
556
    /**
557
     * Removes deleted courses fromn the backup_courses table so that we don't
558
     * waste time backing them up.
559
     *
560
     * @return int
561
     */
562
    public static function remove_deleted_courses_from_schedule() {
563
        global $DB;
564
        $skipped = 0;
565
        $sql = "SELECT bc.courseid FROM {backup_courses} bc WHERE bc.courseid NOT IN (SELECT c.id FROM {course} c)";
566
        $rs = $DB->get_recordset_sql($sql);
567
        foreach ($rs as $deletedcourse) {
568
            // Doesn't exist, so delete from backup tables.
569
            $DB->delete_records('backup_courses', array('courseid' => $deletedcourse->courseid));
570
            $skipped++;
571
        }
572
        $rs->close();
573
        return $skipped;
574
    }
575
 
576
    /**
577
     * Try to get lock for automated backup.
578
     * @param int $rundirective
579
     *
580
     * @return \core\lock\lock|boolean - An instance of \core\lock\lock if the lock was obtained, or false.
581
     */
582
    public static function get_automated_backup_lock($rundirective = self::RUN_ON_SCHEDULE) {
583
        $config = get_config('backup');
584
        $active = (int)$config->backup_auto_active;
585
        $weekdays = (string)$config->backup_auto_weekdays;
586
 
587
        mtrace("Checking automated backup status", '...');
588
        $locktype = 'automated_backup';
589
        $resource = 'queue_backup_jobs_running';
590
        $lockfactory = \core\lock\lock_config::get_lock_factory($locktype);
591
 
592
        // In case of automated backup also check that it is scheduled for at least one weekday.
593
        if ($active === self::AUTO_BACKUP_DISABLED ||
594
                ($rundirective == self::RUN_ON_SCHEDULE && $active === self::AUTO_BACKUP_MANUAL) ||
595
                ($rundirective == self::RUN_ON_SCHEDULE && strpos($weekdays, '1') === false)) {
596
            mtrace('INACTIVE');
597
            return false;
598
        }
599
 
600
        if (!$lock = $lockfactory->get_lock($resource, 10)) {
601
            return false;
602
        }
603
 
604
        mtrace('OK');
605
        return $lock;
606
    }
607
 
608
    /**
609
     * Removes excess backups from a specified course.
610
     *
611
     * @param stdClass $course Course object
612
     * @param int $now Starting time of the process
613
     * @return bool Whether or not backups is being removed
614
     */
615
    public static function remove_excess_backups($course, $now = null) {
616
        $config = get_config('backup');
617
        $maxkept = (int)$config->backup_auto_max_kept;
618
        $storage = $config->backup_auto_storage;
619
        $deletedays = (int)$config->backup_auto_delete_days;
620
 
621
        if ($maxkept == 0 && $deletedays == 0) {
622
            // Means keep all backup files and never delete backup after x days.
623
            return true;
624
        }
625
 
626
        if (!isset($now)) {
627
            $now = time();
628
        }
629
 
630
        // Clean up excess backups in the course backup filearea.
631
        $deletedcoursebackups = false;
632
        if ($storage == self::STORAGE_COURSE || $storage == self::STORAGE_COURSE_AND_DIRECTORY) {
633
            $deletedcoursebackups = self::remove_excess_backups_from_course($course, $now);
634
        }
635
 
636
        // Clean up excess backups in the specified external directory.
637
        $deleteddirectorybackups = false;
638
        if ($storage == self::STORAGE_DIRECTORY || $storage == self::STORAGE_COURSE_AND_DIRECTORY) {
639
            $deleteddirectorybackups = self::remove_excess_backups_from_directory($course, $now);
640
        }
641
 
642
        if ($deletedcoursebackups || $deleteddirectorybackups) {
643
            return true;
644
        } else {
645
            return false;
646
        }
647
    }
648
 
649
    /**
650
     * Removes excess backups in the course backup filearea from a specified course.
651
     *
652
     * @param stdClass $course Course object
653
     * @param int $now Starting time of the process
654
     * @return bool Whether or not backups are being removed
655
     */
656
    protected static function remove_excess_backups_from_course($course, $now) {
657
        $fs = get_file_storage();
658
        $context = context_course::instance($course->id);
659
        $component = 'backup';
660
        $filearea = 'automated';
661
        $itemid = 0;
662
        $backupfiles = array();
663
        $backupfilesarea = $fs->get_area_files($context->id, $component, $filearea, $itemid, 'timemodified DESC', false);
664
        // Store all the matching files into timemodified => stored_file array.
665
        foreach ($backupfilesarea as $backupfile) {
666
            $backupfiles[$backupfile->get_timemodified()] = $backupfile;
667
        }
668
 
669
        $backupstodelete = self::get_backups_to_delete($backupfiles, $now);
670
        if ($backupstodelete) {
671
            foreach ($backupstodelete as $backuptodelete) {
672
                $backuptodelete->delete();
673
            }
674
            mtrace('Deleted ' . count($backupstodelete) . ' old backup file(s) from the automated filearea');
675
            return true;
676
        } else {
677
            return false;
678
        }
679
    }
680
 
681
    /**
682
     * Removes excess backups in the specified external directory from a specified course.
683
     *
684
     * @param stdClass $course Course object
685
     * @param int $now Starting time of the process
686
     * @return bool Whether or not backups are being removed
687
     */
688
    protected static function remove_excess_backups_from_directory($course, $now) {
689
        $config = get_config('backup');
690
        $dir = $config->backup_auto_destination;
691
 
692
        $isnotvaliddir = !file_exists($dir) || !is_dir($dir) || !is_writable($dir);
693
        if ($isnotvaliddir) {
694
            mtrace('Error: ' . $dir . ' does not appear to be a valid directory');
695
            return false;
696
        }
697
 
698
        // Calculate backup filename regex, ignoring the date/time/info parts that can be
699
        // variable, depending of languages, formats and automated backup settings.
700
        $filename = backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-' . $course->id . '-';
701
        $regex = '#' . preg_quote($filename, '#') . '.*\.mbz$#';
702
 
703
        // Store all the matching files into filename => timemodified array.
704
        $backupfiles = array();
705
        foreach (scandir($dir) as $backupfile) {
706
            // Skip files not matching the naming convention.
707
            if (!preg_match($regex, $backupfile)) {
708
                continue;
709
            }
710
 
711
            // Read the information contained in the backup itself.
712
            try {
713
                $bcinfo = backup_general_helper::get_backup_information_from_mbz($dir . '/' . $backupfile);
714
            } catch (backup_helper_exception $e) {
715
                mtrace('Error: ' . $backupfile . ' does not appear to be a valid backup (' . $e->errorcode . ')');
716
                continue;
717
            }
718
 
719
            // Make sure this backup concerns the course and site we are looking for.
720
            if ($bcinfo->format === backup::FORMAT_MOODLE &&
721
                    $bcinfo->type === backup::TYPE_1COURSE &&
722
                    $bcinfo->original_course_id == $course->id &&
723
                    backup_general_helper::backup_is_samesite($bcinfo)) {
724
                $backupfiles[$bcinfo->backup_date] = $backupfile;
725
            }
726
        }
727
 
728
        $backupstodelete = self::get_backups_to_delete($backupfiles, $now);
729
        if ($backupstodelete) {
730
            foreach ($backupstodelete as $backuptodelete) {
731
                unlink($dir . '/' . $backuptodelete);
732
            }
733
            mtrace('Deleted ' . count($backupstodelete) . ' old backup file(s) from external directory');
734
            return true;
735
        } else {
736
            return false;
737
        }
738
    }
739
 
740
    /**
741
     * Get the list of backup files to delete depending on the automated backup settings.
742
     *
743
     * @param array $backupfiles Existing backup files
744
     * @param int $now Starting time of the process
745
     * @return array Backup files to delete
746
     */
747
    protected static function get_backups_to_delete($backupfiles, $now) {
748
        $config = get_config('backup');
749
        $maxkept = (int)$config->backup_auto_max_kept;
750
        $deletedays = (int)$config->backup_auto_delete_days;
751
        $minkept = (int)$config->backup_auto_min_kept;
752
 
753
        // Sort by keys descending (newer to older filemodified).
754
        krsort($backupfiles);
755
        $tokeep = $maxkept;
756
        if ($deletedays > 0) {
757
            $deletedayssecs = $deletedays * DAYSECS;
758
            $tokeep = 0;
759
            $backupfileskeys = array_keys($backupfiles);
760
            foreach ($backupfileskeys as $timemodified) {
761
                $mustdeletebackup = $timemodified < ($now - $deletedayssecs);
762
                if ($mustdeletebackup || $tokeep >= $maxkept) {
763
                    break;
764
                }
765
                $tokeep++;
766
            }
767
 
768
            if ($tokeep < $minkept) {
769
                $tokeep = $minkept;
770
            }
771
        }
772
 
773
        if (count($backupfiles) <= $tokeep) {
774
            // There are less or equal matching files than the desired number to keep, there is nothing to clean up.
775
            return false;
776
        } else {
777
            $backupstodelete = array_splice($backupfiles, $tokeep);
778
            return $backupstodelete;
779
        }
780
    }
781
 
782
    /**
783
     * Check logs to find out if a course was modified since the given time.
784
     *
785
     * @param int $courseid course id to check
786
     * @param int $since timestamp, from which to check
787
     *
788
     * @return bool true if the course was modified, false otherwise. This also returns false if no readers are enabled. This is
789
     * intentional, since we cannot reliably determine if any modification was made or not.
790
     */
791
    protected static function is_course_modified($courseid, $since) {
792
        global $DB;
793
 
794
        /** @var \core\log\sql_reader[] */
795
        $readers = get_log_manager()->get_readers('core\log\sql_reader');
796
 
797
        // Exclude events defined by hook.
798
        $hook = new \core_backup\hook\before_course_modified_check();
799
        \core\di::get(\core\hook\manager::class)->dispatch($hook);
800
 
801
        foreach ($readers as $readerpluginname => $reader) {
802
            $params = [
803
                'courseid' => $courseid,
804
                'since' => $since,
805
            ];
806
            $where = "courseid = :courseid and timecreated > :since and crud <> 'r'";
807
 
808
            $excludeevents = $hook->get_excluded_events();
809
            // Prevent logs of previous backups causing a false positive.
810
            if ($readerpluginname !== 'logstore_legacy') {
811
                $excludeevents[] = '\core\event\course_backup_created';
812
            }
813
 
814
            if ($excludeevents) {
815
                [$notinsql, $notinparams] = $DB->get_in_or_equal($excludeevents, SQL_PARAMS_NAMED, 'eventname', false);
816
                $where .= 'AND eventname ' . $notinsql;
817
                $params = array_merge($params, $notinparams);
818
            }
819
            if ($reader->get_events_select_exists($where, $params)) {
820
                return true;
821
            }
822
        }
823
        return false;
824
    }
825
}