Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | 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
 * Adhoc task that performs asynchronous course copies.
19
 *
20
 * @package    core
21
 * @copyright  2020 onward The Moodle Users Association <https://moodleassociation.org/>
22
 * @author     Matt Porritt <mattp@catalyst-au.net>
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25
 
26
namespace core\task;
27
 
1441 ariadna 28
use core\di;
1 efrain 29
use async_helper;
30
use cache_helper;
1441 ariadna 31
use core\hook\manager;
32
use core_backup\hook\before_copy_course_execute;
1 efrain 33
 
34
defined('MOODLE_INTERNAL') || die();
35
 
36
global $CFG;
37
require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
38
require_once($CFG->dirroot . '/backup/moodle2/backup_plan_builder.class.php');
39
 
40
/**
41
 * Adhoc task that performs asynchronous course copies.
42
 *
43
 * @package     core
44
 * @copyright  2020 onward The Moodle Users Association <https://moodleassociation.org/>
45
 * @author     Matt Porritt <mattp@catalyst-au.net>
46
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47
 */
48
class asynchronous_copy_task extends adhoc_task {
49
 
50
    /**
51
     * Run the adhoc task and preform the backup.
52
     */
53
    public function execute() {
54
        global $CFG, $DB;
55
        $started = time();
56
 
57
        $backupid = $this->get_custom_data()->backupid;
58
        $restoreid = $this->get_custom_data()->restoreid;
59
        $backuprecord = $DB->get_record('backup_controllers', array('backupid' => $backupid), 'id, itemid', MUST_EXIST);
60
        $restorerecord = $DB->get_record('backup_controllers', array('backupid' => $restoreid), 'id, itemid', MUST_EXIST);
61
 
62
        // First backup the course.
63
        mtrace('Course copy: Processing asynchronous course copy for course id: ' . $backuprecord->itemid);
64
        try {
65
            $bc = \backup_controller::load_controller($backupid); // Get the backup controller by backup id.
66
        } catch (\backup_dbops_exception $e) {
67
            mtrace('Course copy: Can not load backup controller for copy, marking job as failed');
68
            delete_course($restorerecord->itemid, false); // Clean up partially created destination course.
69
            return; // Return early as we can't continue.
70
        }
71
 
72
        $rc = \restore_controller::load_controller($restoreid);  // Get the restore controller by restore id.
73
        $bc->set_progress(new \core\progress\db_updater($backuprecord->id, 'backup_controllers', 'progress'));
74
        $copyinfo = $rc->get_copy();
75
        $backupplan = $bc->get_plan();
76
 
77
        $keepuserdata = (bool)$copyinfo->userdata;
78
        $keptroles = $copyinfo->keptroles;
79
 
80
        $bc->set_kept_roles($keptroles);
81
 
82
        // If we are not keeping user data don't include users or data in the backup.
83
        // In this case we'll add the user enrolments at the end.
84
        // Also if we have no roles to keep don't backup users.
85
        if (empty($keptroles) || !$keepuserdata) {
86
            $backupplan->get_setting('users')->set_status(\backup_setting::NOT_LOCKED);
87
            $backupplan->get_setting('users')->set_value('0');
88
        } else {
89
            $backupplan->get_setting('users')->set_value('1');
90
        }
91
 
92
        // Do some preflight checks on the backup.
93
        $status = $bc->get_status();
94
        $execution = $bc->get_execution();
95
        // Check that the backup is in the correct status and
96
        // that is set for asynchronous execution.
97
        if ($status == \backup::STATUS_AWAITING && $execution == \backup::EXECUTION_DELAYED) {
98
            // Execute the backup.
99
            mtrace('Course copy: Backing up course, id: ' . $backuprecord->itemid);
100
            $bc->execute_plan();
101
 
102
        } else {
103
            // If status isn't 700, it means the process has failed.
104
            // Retrying isn't going to fix it, so marked operation as failed.
105
            mtrace('Course copy: Bad backup controller status, is: ' . $status . ' should be 700, marking job as failed.');
106
            $bc->set_status(\backup::STATUS_FINISHED_ERR);
107
            delete_course($restorerecord->itemid, false); // Clean up partially created destination course.
108
            $bc->destroy();
109
            return; // Return early as we can't continue.
110
 
111
        }
112
 
113
        $results = $bc->get_results();
114
        $backupbasepath = $backupplan->get_basepath();
115
        $file = $results['backup_destination'];
116
        $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
117
        // Start the restore process.
118
        $rc->set_progress(new \core\progress\db_updater($restorerecord->id, 'backup_controllers', 'progress'));
119
        $rc->prepare_copy();
120
 
121
        // Set the course settings we can do now (the remaining settings will be done after restore completes).
122
        $plan = $rc->get_plan();
123
 
124
        $startdate = $plan->get_setting('course_startdate');
125
        $startdate->set_value($copyinfo->startdate);
126
        $fullname = $plan->get_setting('course_fullname');
127
        $fullname->set_value($copyinfo->fullname);
128
        $shortname = $plan->get_setting('course_shortname');
129
        $shortname->set_value($copyinfo->shortname);
130
 
1441 ariadna 131
        // Create and dispatch a hook to allow interaction with the task immediately prior to execution.
132
        $hook = new before_copy_course_execute($plan, $copyinfo);
133
        di::get(manager::class)->dispatch($hook);
134
 
1 efrain 135
        // Do some preflight checks on the restore.
136
        $rc->execute_precheck();
137
        $status = $rc->get_status();
138
        $execution = $rc->get_execution();
139
 
140
        // Check that the restore is in the correct status and
141
        // that is set for asynchronous execution.
142
        if ($status == \backup::STATUS_AWAITING && $execution == \backup::EXECUTION_DELAYED) {
143
            // Execute the restore.
144
            mtrace('Course copy: Restoring into course, id: ' . $restorerecord->itemid);
145
            $rc->execute_plan();
146
 
147
        } else {
148
            // If status isn't 700, it means the process has failed.
149
            // Retrying isn't going to fix it, so marked operation as failed.
150
            mtrace('Course copy: Bad backup controller status, is: ' . $status . ' should be 700, marking job as failed.');
151
            $rc->set_status(\backup::STATUS_FINISHED_ERR);
152
            delete_course($restorerecord->itemid, false); // Clean up partially created destination course.
153
            $file->delete();
154
            if (empty($CFG->keeptempdirectoriesonbackup)) {
155
                fulldelete($backupbasepath);
156
            }
157
            $rc->destroy();
158
            return; // Return early as we can't continue.
159
 
160
        }
161
 
162
        // Copy user enrolments from source course to destination.
163
        if (!empty($keptroles) && !$keepuserdata) {
164
            mtrace('Course copy: Creating user enrolments in destination course.');
165
            $context = \context_course::instance($backuprecord->itemid);
166
 
167
            $enrol = enrol_get_plugin('manual');
168
            $instance = null;
169
            $enrolinstances = enrol_get_instances($restorerecord->itemid, true);
170
            foreach ($enrolinstances as $courseenrolinstance) {
171
                if ($courseenrolinstance->enrol == 'manual') {
172
                    $instance = $courseenrolinstance;
173
                    break;
174
                }
175
            }
176
 
177
            // Abort if there enrolment plugin problems.
178
            if (empty($enrol) || empty($instance)) {
179
                mtrace('Course copy: Could not enrol users in course.');;
180
                delete_course($restorerecord->itemid, false);
181
                return;
182
            }
183
 
184
            // Enrol the users from the source course to the destination.
185
            foreach ($keptroles as $roleid) {
186
                $sourceusers = get_role_users($roleid, $context);
187
                foreach ($sourceusers as $sourceuser) {
188
                    $enrol->enrol_user($instance, $sourceuser->id, $roleid);
189
                }
190
            }
191
        }
192
 
193
        // Set up remaining course settings.
194
        $course = $DB->get_record('course', array('id' => $restorerecord->itemid), '*', MUST_EXIST);
195
        $course->visible = $copyinfo->visible;
196
        $course->idnumber = $copyinfo->idnumber;
197
        $course->enddate = $copyinfo->enddate;
198
 
199
        $DB->update_record('course', $course);
200
 
201
        // Send message to user if enabled.
202
        $messageenabled = (bool)get_config('backup', 'backup_async_message_users');
203
        if ($messageenabled && $rc->get_status() == \backup::STATUS_FINISHED_OK) {
204
            mtrace('Course copy: Sending user notification.');
205
            $asynchelper = new async_helper('copy', $restoreid);
206
            $messageid = $asynchelper->send_message();
207
            mtrace('Course copy: Sent message: ' . $messageid);
208
        }
209
 
210
        // Cleanup.
211
        $bc->destroy();
212
        $rc->destroy();
213
        $file->delete();
214
        if (empty($CFG->keeptempdirectoriesonbackup)) {
215
            fulldelete($backupbasepath);
216
        }
217
 
218
        rebuild_course_cache($restorerecord->itemid, true);
219
        cache_helper::purge_by_event('changesincourse');
220
 
221
        $duration = time() - $started;
222
        mtrace('Course copy: Copy completed in: ' . $duration . ' seconds');
223
    }
224
}