-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlocallib.php
executable file
·546 lines (474 loc) · 20.4 KB
/
locallib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
<?php
// This file is part of local/courseduplication
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package local/courseduplication
* @copyright 2014-2018 Liip AG <https://www.liip.ch/>
* @author Brian King <[email protected]>
* @author Claude Bossy <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once(__DIR__ . '/../../backup/util/includes/backup_includes.php');
require_once(__DIR__ . '/../../backup/util/includes/restore_includes.php');
require_once(__DIR__ . '/../../group/lib.php');
require_once(__DIR__ . '/../../course/format/weeks/lib.php');
class local_courseduplication_controller
{
protected $options = array(
'activities' => 1,
'blocks' => 1,
'filters' => 1,
'users' => 0,
'role_assignments' => 0,
'comments' => 0,
'logs' => 0,
'groups' => 0,
);
public function backup_course($courseid, $userid, $log=false) {
$bc = new backup_controller(
backup::TYPE_1COURSE, $courseid, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_SAMESITE, $userid);
if ($log) {
ob_end_flush();
$bc->get_logger()->set_next(new output_indented_logger(backup::LOG_DEBUG, false, true));
}
// Can set custom settings here.
foreach ($this->options as $name => $value) {
$setting = $bc->get_plan()->get_setting($name);
$setting->set_status(backup_setting::NOT_LOCKED);
$setting->set_value($value);
}
$backupid = $bc->get_backupid();
$backupbasepath = $bc->get_plan()->get_basepath();
$bc->execute_plan();
$results = $bc->get_results();
$backupfile = $results['backup_destination'];
$bc->destroy();
return array(
'id' => $backupid,
'basepath' => $backupbasepath,
'file' => $backupfile
);
}
/**
* Restore a course that was backed up.
* @param object $course containing fields: fullname, shortname, category
* @param array $backup array as returned from $this->backup_course()
* @param int $userid
* @param bool $removebackupfile whether or not to remove the backup file after restoring
* @param bool $log
* @return int newcourseid
* @throws base_logger_exception
* @throws base_plan_exception
* @throws base_setting_exception
* @throws moodle_exception
* @throws restore_controller_exception
*/
public function restore_course($course, $backup, $userid, $removebackupfile=true, $log=false) {
global $DB, $CFG;
$backupfile = $backup['file'];
// Check if we need to unzip the file because the backup temp dir does not contains backup files.
if (!file_exists($backup['basepath'] . "/moodle_backup.xml")) {
$backupfile->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backup['basepath']);
}
$newcourseid = restore_dbops::create_new_course($course->fullname, $course->shortname, $course->category);
$rc = new restore_controller(
$backup['id'], $newcourseid, backup::INTERACTIVE_NO,
backup::MODE_SAMESITE, $userid, backup::TARGET_NEW_COURSE
);
if ($log) {
$rc->get_logger()->set_next(new output_indented_logger(backup::LOG_DEBUG, false, true));
}
foreach ($this->options as $name => $value) {
$setting = $rc->get_plan()->get_setting($name);
$setting->set_status(backup_setting::NOT_LOCKED);
$setting->set_value($value);
}
if (!$rc->execute_precheck()) {
$precheckresults = $rc->get_precheck_results();
if (is_array($precheckresults) && !empty($precheckresults['errors'])) {
if (empty($CFG->keeptempdirectoriesonbackup)) {
fulldelete($backup['basepath']);
}
$errorinfo = '';
foreach ($precheckresults['errors'] as $error) {
$errorinfo .= ' ' . $error;
}
if (array_key_exists('warnings', $precheckresults)) {
foreach ($precheckresults['warnings'] as $warning) {
$errorinfo .= ' ' . $warning;
}
}
$rc->destroy();
throw new moodle_exception('errorrestoreprecheck', 'local_courseduplication', '', $errorinfo);
}
}
// Executing restoration will copy content (sections, activities, ...)
// But it will override the data defined in the duplication_form.
// It also uses the default course format options.
$rc->execute_plan();
$rc->destroy();
// So, update the record afterward with our custom values.
$course->id = $newcourseid;
$DB->update_record('course', $course);
// Also update course format option (weeks -> automaticenddate).
$cfo = $DB->get_record('course_format_options', array(
'courseid' => $course->id,
'name' => 'automaticenddate'
));
if ($cfo) {
$DB->update_record('course_format_options', (object)array(
'id' => $cfo->id,
'value' => $course->automaticenddate
));
}
if (empty($CFG->keeptempdirectoriesonbackup)) {
fulldelete($backup['basepath']);
}
if ($removebackupfile) {
$backupfile->delete();
}
return $newcourseid;
}
/**
* Create new groups, copied from existing $groupidlist, in the course identified
* by $courseid.
*
* @param $courseid
* @param $groupidlist
* @return array
* @throws dml_exception
* @throws coding_exception
*/
public function copy_groups($courseid, $groupidlist) {
global $DB;
$errors = array();
$groups = $DB->get_records_list('groups', 'id', $groupidlist);
foreach ($groups as $group) {
$groupdata = new stdClass();
$groupdata->courseid = $courseid;
$groupdata->name = $group->name;
$groupdata->description = $group->description;
$groupdata->descriptionformat = $group->descriptionformat;
// Also available in $group:
// enrolmentkey, picture, hidepicture.
// Unwanted or not taken upon group creation:
// id, courseid, idnumber, timecreated, timemodified.
try {
groups_create_group($groupdata);
} catch (Exception $e) {
$string = new lang_string('warningcopygroupfailed', 'local_courseduplication', array(
'groupname' => $group->name,
'reason' => $e->getMessage(),
));
$errors[] = $string->out();
}
}
return $errors;
}
public function enrol_from_roles($basecourseid, $newcourseid, $roleidlist, $jobuser) {
global $DB;
// Get users enrolled in the basecourse with a role included in $roleidlist.
$enroledusers = get_enrolled_users(context_course::instance($basecourseid));
$enroledusersbyroles = array();
foreach ($roleidlist as $roleid) {
// Use get_role_users with parent true, to include users by system roles.
if ($roleusers = get_role_users($roleid, context_course::instance($basecourseid), true, '', false)) {
$enroledusersbyroles[$roleid] = array_intersect_key($roleusers, $enroledusers);
}
}
$duplicatorroleid = intval(get_config('local_courseduplication', 'duplicatorrole'));
if ($duplicatorroleid > 0) {
$duplicatorrole = $DB->get_record('role', array('id' => $duplicatorroleid));
if ($duplicatorrole) {
$enroledusersbyroles[$duplicatorrole->id][$jobuser->id] = $jobuser;
}
}
// Enrol these users in the new course.
$errors = array();
foreach ($enroledusersbyroles as $roleid => $roleusers) {
foreach ($roleusers as $user) {
if (!enrol_try_internal_enrol($newcourseid, $user->id, $roleid)) {
$string = new lang_string('warningenrollingfailed', 'local_courseduplication', array(
"userid" => $user->id,
"roleid" => $roleid,
));
$errors[] = $string->out();
}
}
}
return $errors;
}
}
class local_course_duplication_queue {
const STATUS_QUEUED = 0;
const STATUS_RUNNING = 1;
const STATUS_SUCCESS = 2;
const STATUS_FAILED = 3;
protected $runid;
/**
* Retrieve the queued task data, some are course attributes but not necessarily.
* @param $userid int The user who submitted the duplication form.
* @param $data stdClass The duplication form data
* @throws dml_exception
*/
public static function queue($userid, $data) {
global $DB;
$duplication = new stdClass();
$duplication->courseid = $data->id;
$duplication->categoryid = $data->categoryid;
$duplication->status = self::STATUS_QUEUED;
$duplication->userid = $userid;
$duplication->fullname = $data->targetfullname;
$duplication->shortname = $data->targetshortname;
$duplication->startdate = $data->startdate;
$duplication->enddate = $data->enddate;
$duplication->automaticenddate = (
!isset($data->targetautomaticenddate) || is_null($data->targetautomaticenddate)
) ? 0 : $data->targetautomaticenddate;
$duplication->coursegroups = serialize($data->coursegroups);
$duplication->enrolfromroles = serialize($data->enrolfromroles);
$DB->insert_record('courseduplication_queue', $duplication);
}
public function __construct() {
$this->runid = uniqid(getmypid(), true);
}
/**
* Process the queue and launch job processes sequentially
*/
public function process_queue() {
global $DB;
$info = array(
'succeeded' => array(),
'failed' => array()
);
$queued = $this->get_queued_jobs();
if (!count($queued)) {
return;
}
foreach ($queued as $job) {
$jobuser = $DB->get_record('user', array('id' => $job->userid));
$userlang = $jobuser->lang ? $jobuser->lang : 'en';
// Switch session to user who initiated the backup,
// so we have correct capabilities validation and same user reflected in event.
\core\session\manager::set_user($jobuser);
list($status, $errors, $warnings, $newcourseid) = $this->process_job($job, $userlang);
if ($status == self::STATUS_FAILED) {
$info['failed'][] = "course id $job->courseid to category $job->categoryid";
$info['failed'] = array_merge($info['failed'], $errors);
$event = \local_courseduplication\event\duplication_failed::create(
array(
'objectid' => $job->courseid,
'context' => context_course::instance($job->courseid),
'other' => array(
'newcategoryid' => $job->categoryid,
)
));
$event->trigger();
// Database connection may have been reset if there was a failure. So pull in $DB
// from the globals again.
global $DB;
} else {
$info['succeeded'][] = "course id $job->courseid to category $job->categoryid (new course id: $newcourseid)";
$event = \local_courseduplication\event\duplication_succeeded::create(
array(
'objectid' => $job->courseid,
'context' => context_course::instance($job->courseid),
'other' => array(
'newcourseid' => $newcourseid,
'newcategoryid' => $job->categoryid,
)
));
$event->trigger();
}
$this->send_mail($job, $status, $errors, $warnings, $newcourseid, $userlang);
$DB->delete_records('courseduplication_queue', array('id' => $job->id));
}
// Switch back to admin.
\core\session\manager::set_user(get_admin());
return $info;
}
protected function send_mail($job, $status, $errors, $warnings, $newcourseid, $userlang) {
global $DB;
$a = new stdClass();
$oldcourse = $DB->get_record('course', array('id' => $job->courseid), 'id, fullname, shortname');
$a->oldfullname = $oldcourse->fullname;
$category = $DB->get_record('course_categories', array('id' => $job->categoryid), 'id, name');
$a->categoryname = $category->name;
if (count($errors)) {
$errorstr = new lang_string('error', 'error', null, $userlang);
$a->errors = $errorstr . ":\n * " . implode("\n * ", $errors);
$event = \local_courseduplication\event\duplication_errors::create(
array(
'objectid' => $job->courseid,
'context' => context_course::instance($job->courseid),
'other' => array(
'newcategoryid' => $job->categoryid,
'errors' => $a->errors,
)
));
$event->trigger();
} else {
$a->errors = '';
}
if (count($warnings)) {
$warningstr = new lang_string('warning', 'moodle', null, $userlang);
$a->warnings = $warningstr . ":\n * " . implode("\n * ", $warnings);
$event = \local_courseduplication\event\duplication_warnings::create(
array(
'objectid' => $job->courseid,
'context' => context_course::instance($job->courseid),
'other' => array(
'newcategoryid' => $job->categoryid,
'warnings' => $a->warnings,
)
));
$event->trigger();
} else {
$a->warnings = '';
}
$subjectstringkey = 'mailduplicationfailsubject';
$bodystringkey = 'mailduplicationfailbody';
if ($status == self::STATUS_SUCCESS) {
$subjectstringkey = 'mailduplicationsuccesssubject';
$bodystringkey = 'mailduplicationsuccessbody';
$newcourse = $DB->get_record('course', array('id' => $newcourseid), 'id, fullname, shortname, category');
$a->newfullname = $newcourse->fullname;
$url = new moodle_url('/course/view.php', array('id' => $newcourse->id));
$a->newcourseurl = $url->out();
}
$subject = new lang_string($subjectstringkey, 'local_courseduplication', $a, $userlang);
$body = new lang_string($bodystringkey, 'local_courseduplication', $a, $userlang);
$user = $DB->get_record('user', array('id' => $job->userid));
email_to_user($user, \core_user::get_noreply_user(), $subject, $body);
}
/**
* Gets queued jobs
*
* This marks the jobs in the table with a run id, so that no other process
* tries to simultaneously process the same job.
*/
protected function get_queued_jobs() {
global $DB;
$queued = $DB->get_records('courseduplication_queue', array('status' => self::STATUS_QUEUED));
if (!count($queued)) {
return array();
}
foreach ($queued as $job) {
$job->status = self::STATUS_RUNNING;
$job->runid = $this->runid;
$DB->update_record('courseduplication_queue', $job);
}
return $DB->get_records('courseduplication_queue',
array('status' => self::STATUS_RUNNING, 'runid' => $this->runid));
}
/**
* Process a job from the queue
* @param $job
* @param string $stringlang
* @return array
* @throws coding_exception
* @throws dml_exception
*/
protected function process_job($job, $stringlang='en') {
global $DB;
$status = 0;
$errors = 1;
$warnings = 2;
$courseid = 3;
$return = array(
$status => self::STATUS_FAILED,
$errors => array(),
$warnings => array(),
$courseid => 0
);
// Course to duplicate.
if (!$course = $DB->get_record('course', array('id' => $job->courseid))) {
$return[$errors][] = get_string('duplicatefailedbackup', 'local_courseduplication') . ': ' . get_string('invalidcourseid');
}
// Target category.
if (!$category = $DB->get_record('course_categories', array('id' => $job->categoryid))) {
$string1 = new lang_string('duplicatefailedbackup', 'local_courseduplication', null, $stringlang);
$string2 = new lang_string('errornosuchcategory', 'local_courseduplication', null, $stringlang);
$return[$errors][] = $string1 . ': ' . $string2;
}
if (count($return[$errors])) {
return $return;
}
if (!has_capability('local/courseduplication:restore_course', context_coursecat::instance($category->id))) {
$return[$errors][] = get_string('errornopermsintarget', 'local_courseduplication');
return $return;
}
$jobuser = $DB->get_record('user', array('id' => $job->userid));
$admin = get_admin();
$dup = new local_courseduplication_controller();
try {
// HERE WE CALL BACKUP.
$backup = $dup->backup_course($course->id, $admin->id);
} catch (Exception $e) {
$return[$errors][] = get_string('duplicatefailedbackup', 'local_courseduplication');
$return[$errors][] = $e->getMessage();
debugging($e->getMessage());
$this->database_reconnect();
return $return;
}
$newcourse = new stdClass();
$newcourse->fullname = $job->fullname;
$newcourse->shortname = $job->shortname;
$newcourse->category = $category->id;
$newcourse->timecreated = time();
$newcourse->startdate = $job->startdate;
$newcourse->enddate = $job->enddate;
$newcourse->automaticenddate = $job->automaticenddate;
try {
$return[$courseid] = $dup->restore_course($newcourse, $backup, $admin->id);
} catch (Exception $e) {
$return[$errors][] = get_string('duplicatefailedrestore', 'local_courseduplication');
$return[$errors][] = $e->getMessage();
debugging($e->getMessage());
$this->database_reconnect();
return $return;
}
$return[$warnings] = $dup->copy_groups($return[$courseid], unserialize($job->coursegroups));
array_merge(
$return[$warnings],
$dup->enrol_from_roles(
$job->courseid,
$return[$courseid],
unserialize($job->enrolfromroles),
$jobuser
)
);
if ($job->automaticenddate === '1') {
format_weeks::update_end_date($return[$courseid]);
}
$return[$status] = self::STATUS_SUCCESS;
return $return;
}
/**
* Reconnect to the Moodle database. This drops any temp tables
* which were created during a backup / restore process.
*
* Note that it will be necessary to re-initialize any references to the global $DB
* in call-stack ancestor functions after this is called.
*/
protected function database_reconnect() {
global $DB;
$DB->dispose();
// @codingStandardsIgnoreLine .
$GLOBALS['DB'] = null;
setup_DB();
}
}