-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathprocessor.php
More file actions
1825 lines (1623 loc) · 74.5 KB
/
processor.php
File metadata and controls
1825 lines (1623 loc) · 74.5 KB
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of
//
// 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/>.
/**
* File containing processor class.
*
* @package tool_coursearchiver
* @copyright 2015 Matthew Davidson
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Processor class.
*
* @package tool_coursearchiver
* @copyright 2015 Matthew Davidson
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class tool_coursearchiver_processor {
/**
* Only Show the Course list.
*/
const MODE_COURSELIST = 1;
/**
* Get email address for the owners of selected courses.
*/
const MODE_GETEMAILS = 2;
/**
* Hide courses.
*/
const MODE_HIDE = 3;
/**
* Archive courses.
*/
const MODE_ARCHIVE = 4;
/**
* Send emails about pending course hides.
*/
const MODE_HIDEEMAIL = 5;
/**
* Back up courses without removal.
*/
const MODE_BACKUP = 6;
/**
* Send emails about pending course archival.
*/
const MODE_ARCHIVEEMAIL = 7;
/**
* Send emails about pending course deletion.
*/
const MODE_DELETEEMAIL = 8;
/**
* Delete courses.
*/
const MODE_DELETE = 9;
/**
* Optout courses.
*/
const MODE_OPTOUT = 10;
/** @var int processor mode. */
protected $mode;
/** @var int total processed. */
public $total = 0;
/** @var int sub folder of archive process. */
public $folder = false;
/** @var int only return empty courses. */
public $emptyonly = false;
/** @var int only return empty courses. */
public $ignadmins = false;
/** @var int only return empty courses. */
public $ignsiteroles = false;
/** @var int recursive category search. */
public $subcats = false;
/** @var int data passed into processor. */
protected $data = [];
/** @var array of errors. */
protected $errors = [];
/** @var array of notices. */
protected $notices = [];
/** @var bool whether the process has been started or not. */
protected $processstarted = false;
/** @var array list of viable search criteria. */
protected $searchcriteria = [
"id" => "id",
"short" => "shortname",
"full" => "fullname",
"idnum" => "idnumber",
"teacher" => "teacher",
"catid" => "category",
"subcats" => "subcats",
"createdbefore" => "createdbefore",
"createdafter" => "createdafter",
"accessbefore" => "accessbefore",
"accessafter" => "accessafter",
"ignadmins" => "ignadmins",
"ignsiteroles" => "ignsiteroles",
"startbefore" => "startbefore",
"startafter" => "startafter",
"endbefore" => "endbefore",
"endafter" => "endafter",
"emptyonly" => "emptyonly",
];
/**
* Constructor
*
* @param array $options options of the process
*/
public function __construct(array $options) {
if (!isset($options['mode']) || !in_array($options['mode'], [self::MODE_COURSELIST,
self::MODE_GETEMAILS,
self::MODE_HIDE,
self::MODE_BACKUP,
self::MODE_ARCHIVE,
self::MODE_DELETE,
self::MODE_HIDEEMAIL,
self::MODE_ARCHIVEEMAIL,
self::MODE_DELETEEMAIL,
self::MODE_OPTOUT,
])) {
throw new coding_exception('Unknown process mode');
}
// Force int to make sure === comparison work as expected.
$this->mode = (int)$options['mode'];
$this->data = (array)$options['data'];
$this->reset();
}
/**
* Execute the process.
*
* @param int $outputtype tracker output type.
* @param object $tracker the output tracker to use.
* @param object $mform moodle_form object to use (optional)
* @param object $form $this moodle_form object to use (optional)
* @return void
*/
public function execute($outputtype = tool_coursearchiver_tracker::NO_OUTPUT, $tracker = null, $mform = null, $form = null) {
if ($this->processstarted) {
throw new coding_exception(get_string('processstarted', 'tool_coursearchiver'));
}
$this->processstarted = true;
if (empty($tracker)) {
$tracker = new tool_coursearchiver_tracker($outputtype, $this->mode);
}
if ($outputtype == tool_coursearchiver_tracker::OUTPUT_HTML) {
if (!in_array($this->mode, [self::MODE_HIDE,
self::MODE_BACKUP,
self::MODE_ARCHIVE,
self::MODE_DELETE,
self::MODE_HIDEEMAIL,
self::MODE_ARCHIVEEMAIL,
self::MODE_DELETEEMAIL,
self::MODE_OPTOUT,
])) {
if (empty($mform)) {
throw new coding_exception(get_string('errornoform', 'tool_coursearchiver'));
} else {
$tracker->form = $form;
$tracker->mform = $mform;
}
}
}
// We will most certainly need extra time and memory to process big files.
core_php_time_limit::raise(0);
raise_memory_limit(MEMORY_EXTRA);
switch ($this->mode) {
case self::MODE_COURSELIST:
$tracker->start();
if (!empty($this->data["resume"])) {
$courses = $this->recreate_courselist($this->data);
} else {
$courses = $this->get_courselist();
}
$courselist = [];
if (!empty($courses)) {
// Loop over the course array.
$tracker->jobsize = count($courses);
foreach ($courses as $currentcourse) {
$tracker->empty = $this->is_empty_course($currentcourse->id);
if (!$this->is_opted_out($currentcourse->id)) {
if ($this->emptyonly && $tracker->empty || !$this->emptyonly) {
$this->total++;
if (!empty($currentcourse->id)) {
$tracker->error = false;
$courselist[] = $currentcourse->id;
$tracker->output($currentcourse);
} else {
$tracker->error = true;
$this->errors[] = get_string('error_nocourseid', 'tool_coursearchiver');
}
$tracker->jobsdone++;
} else {
$tracker->jobsize--;
}
} else {
$tracker->jobsize--;
}
}
}
$tracker->finish();
$tracker->results($this->mode, $this->total, $this->errors, $this->notices);
return $courselist;
break;
case self::MODE_GETEMAILS:
$tracker->start();
if (!empty($this->data["resume"])) {
$courses = $this->recreate_courseowners($this->data);
} else {
$courses = $this->get_courses_and_their_owners();
}
if (!empty($courses)) {
$tracker->jobsize = count($courses);
$return = [];
$unique = [];
// Loop over the course array.
foreach ($courses as $currentcourse) {
if (!$this->is_opted_out($currentcourse["course"]->id)) {
$tracker->output($currentcourse, true); // Output course header.
if (!empty($currentcourse["owners"])) {
foreach ($currentcourse["owners"] as $owner) {
$owner->course = $currentcourse["course"]->id;
$tracker->output($owner); // Output users.
$unique[$owner->id] = $owner->id;
$return[] = $currentcourse["course"]->id . "_" . $owner->id;
$this->total++;
}
} else {
$tracker->jobsize--;
}
$tracker->jobsdone++;
} else {
$tracker->jobsize--;
}
}
$this->total = count($unique);
$tracker->finish();
} else {
$this->errors[] = get_string('errorinsufficientdata', 'tool_coursearchiver');
}
$tracker->results($this->mode, $this->total, $this->errors, $this->notices);
return $return;
break;
case self::MODE_HIDE:
$tracker->start();
$courses = $this->get_courses_and_their_owners();
if (!empty($courses)) {
// Loop over the course array.
$tracker->jobsize = count($courses);
foreach ($courses as $currentcourse) {
if ($currentcourse["course"]->visible) {
if ($this->hidecourse($currentcourse)) {
$tracker->error = false;
$this->total++;
} else {
$tracker->error = true;
$this->errors[] = get_string('errorhidingcourse', 'tool_coursearchiver', $currentcourse["course"]);
}
}
$tracker->jobsdone++;
$tracker->output($currentcourse);
}
$tracker->finish();
} else {
$tracker->jobsize = 1;
$tracker->jobsdone++;
$tracker->output(false);
$this->errors[] = get_string('errorinsufficientdata', 'tool_coursearchiver');
}
$tracker->results($this->mode, $this->total, $this->errors, $this->notices);
break;
case self::MODE_BACKUP:
case self::MODE_ARCHIVE:
$tracker->start();
$courses = $this->get_courses_and_their_owners();
$delete = $this->mode == self::MODE_ARCHIVE ? true : false;
if (!empty($courses)) {
// Loop over the course array.
$tracker->jobsize = count($courses);
foreach ($courses as $currentcourse) {
if ($this->archivecourse($currentcourse, $delete)) {
$tracker->error = false;
$this->total++;
} else {
$tracker->error = true;
$this->errors[] = get_string('errorarchivingcourse', 'tool_coursearchiver', $currentcourse["course"]);
}
$tracker->jobsdone++;
$tracker->output($currentcourse);
}
$tracker->finish();
} else {
$tracker->jobsize = 1;
$tracker->jobsdone++;
$tracker->output(false);
$this->errors[] = get_string('errorinsufficientdata', 'tool_coursearchiver');
}
$tracker->results($this->mode, $this->total, $this->errors, $this->notices);
break;
case self::MODE_DELETE:
$tracker->start();
$courses = $this->get_courses_and_their_owners();
if (!empty($courses)) {
// Loop over the course array.
$tracker->jobsize = count($courses);
foreach ($courses as $currentcourse) {
// Remove Course.
if (delete_course($currentcourse["course"]->id, false)) {
$tracker->error = false;
$this->total++;
} else {
$tracker->error = true;
$this->errors[] = get_string('errordeletingcourse', 'tool_coursearchiver', $currentcourse["course"]);
}
$tracker->jobsdone++;
$tracker->output($currentcourse);
}
$tracker->finish();
} else {
$tracker->jobsize = 1;
$tracker->jobsdone++;
$tracker->output(false);
$this->errors[] = get_string('errorinsufficientdata', 'tool_coursearchiver');
}
$tracker->results($this->mode, $this->total, $this->errors, $this->notices);
break;
case self::MODE_HIDEEMAIL:
case self::MODE_ARCHIVEEMAIL:
case self::MODE_DELETEEMAIL:
$tracker->start();
if (!empty($this->data)) {
// Loop over the user array.
$tracker->jobsize = count($this->data);
foreach ($this->data as $user) {
if ($amountsent = $this->sendemail($user)) {
$tracker->error = false;
$this->total += $amountsent;
} else {
$tracker->error = true;
$this->errors[] = get_string('errorsendingemail', 'tool_coursearchiver', $user["user"]);
}
$tracker->jobsdone++;
$tracker->output(false);
}
} else {
$tracker->jobsize = 1;
$tracker->jobsdone++;
$tracker->output(false);
$this->errors[] = get_string('errorinsufficientdata', 'tool_coursearchiver');
}
$tracker->finish();
$tracker->results($this->mode, $this->total, $this->errors, $this->notices);
break;
case self::MODE_OPTOUT:
$tracker->start();
$courses = $this->get_courses_and_their_owners();
if (!empty($courses)) {
// Loop over the course array.
$tracker->jobsize = count($courses);
foreach ($courses as $currentcourse) {
// Opt out Course.
if ($this->optout_course($currentcourse["course"]->id, false)) {
$tracker->error = false;
$this->total++;
} else {
$tracker->error = true;
$this->errors[] = get_string('erroroptoutcourse', 'tool_coursearchiver', $currentcourse["course"]);
}
$tracker->jobsdone++;
$tracker->output($currentcourse);
}
$tracker->finish();
} else {
$tracker->jobsize = 1;
$tracker->jobsdone++;
$tracker->output(false);
$this->errors[] = get_string('errorinsufficientdata', 'tool_coursearchiver');
}
$tracker->results($this->mode, $this->total, $this->errors, $this->notices);
break;
}
}
/**
* Return an full list of courses and the teachers in them.
*
* @return array of courses and array of owners attached to it
*/
protected function get_courses_and_their_owners() {
$owners = [];
foreach ($this->data as $course) {
if ($this->exists($course)) {
$owners[$course] = $this->get_course_users_with_role($course,
get_config('tool_coursearchiver', 'ownerroleid'));
}
}
return $owners;
}
/**
* Return an array of users in a course with a given role.
*
* @param int $courseid id of the moodle course.
* @param int $roleids id's of selected owner roles.
* @return array of users in a course with a given role
*/
protected function get_course_users_with_role($courseid, $roleids) {
global $DB;
if ($course = $DB->get_record('course', ['id' => $courseid], '*', IGNORE_MISSING)) {
$params = ['courseid' => $courseid];
if (!empty($roleids)) {
$roleids = explode(',', $roleids);
list($insql, $inparams) = $DB->get_in_or_equal($roleids, SQL_PARAMS_NAMED);
} else {
// Default back to editing teacher.
list($insql, $inparams) = [' = :roleid', ['roleid' => 3]];
}
$params = array_merge($params, $inparams);
$sql = 'SELECT a.id, a.email, a.firstname, a.lastname
FROM {user} a
WHERE a.id IN (SELECT userid
FROM {role_assignments} b
WHERE b.roleid ' . $insql . '
AND b.contextid IN (
SELECT c.id
FROM {context} c
WHERE c.contextlevel = 50
AND c.instanceid = :courseid
)
)';
return ['course' => $course, 'owners' => $DB->get_records_sql($sql, $params)];
}
return [];
}
/**
* Return an each course and the teachers in them from save.
*
* @param object $data course object
* @return array of courses and array of owners attached to it
*/
protected function recreate_courseowners($data) {
global $DB, $SITE;
$owners = [];
foreach ($data as $key => $value) {
if ($key !== 'resume') {
$d = explode("_", ltrim($value, 'x')); // Remove 'x' from unselected values.
if ($d[0] !== 0 && $d[0] !== $SITE->id) {
if (isset($owners[$d[0]])) { // Course exists in array.
$owners[$d[0]][$d[1]]["userid"] = $d[1];
} else {
$owners[$d[0]] = [];
$owners[$d[0]][$d[1]]["userid"] = $d[1];
}
if (substr($value, 0, 1) !== 'x') { // This course/user was not selected.
$owners[$d[0]][$d[1]]["selected"] = true;
} else {
$owners[$d[0]][$d[1]]["selected"] = false;
}
}
}
}
$return = [];
foreach ($owners as $key => $value) {
if ($course = $DB->get_record('course', ['id' => $key], '*', IGNORE_MISSING)) {
$return[$key] = ['course' => $course, 'owners' => []];
foreach ($value as $users) {
if ($record = $DB->get_record('user', ['id' => $users["userid"]])) {
$record->selected = $users["selected"];
$return[$key]["owners"][$users["userid"]] = $record;
}
}
}
}
return $return;
}
/**
* Return an array of owners and a list of each course they are owners of.
*
* @return array owners and an array of their courses attached
*/
protected function get_owners_and_their_courses() {
global $DB;
$owners = [];
foreach ($this->data as $course) {
$params = ['courseid' => $course];
$roleids = get_config('tool_coursearchiver', 'ownerroleid');
if (!empty($roleids)) {
$roleids = explode(',', $roleids);
list($insql, $inparams) = $DB->get_in_or_equal($roleids, SQL_PARAMS_NAMED);
} else {
// Default back to editing teacher.
list($insql, $inparams) = [' = :roleid', ['roleid' => 3]];
}
$params = array_merge($params, $inparams);
$sql = 'SELECT a.id, a.email, a.firstname, a.lastname
FROM {user} a
WHERE a.id IN (
SELECT userid
FROM {role_assignments} b
WHERE b.roleid ' . $insql . '
AND b.contextid IN (
SELECT c.id
FROM {context} c
WHERE c.contextlevel = 50
AND c.instanceid = :courseid
)
)';
$users = $DB->get_records_sql($sql, $params);
foreach ($users as $user) {
if (array_key_exists($user->id, $owners)) {
if ($this->exists($course)) {
$temp = $owners[$user->id]['courses'];
$owners[$user->id]['courses'] = array_merge($temp,
[$course => $DB->get_record('course',
['id' => $course],
'*',
IGNORE_MISSING),
]);
}
} else {
if ($this->exists($course)) {
$owners[$user->id]['user'] = $user;
$owners[$user->id]['courses'] = [$course => $DB->get_record('course',
['id' => $course],
'*',
IGNORE_MISSING),
];
}
}
}
}
return $owners;
}
/**
* Hide course.
*
* @param object $obj course object
* @return bool
*/
protected function hidecourse($obj) {
global $DB;
if (!empty($obj["course"]->visible)) {
$obj["course"]->visible = 0;
if (!$DB->update_record('course', $obj["course"])) {
return false;
}
}
return true;
}
/**
* Return an array of owners and a list of each course they are teachers of.
*
* @param object $obj course obj
* @param bool $delete delete course after backup
* @return bool of courses that match the search
*/
protected function archivecourse($obj, $delete = true) {
global $CFG, $DB;
require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
require_once($CFG->dirroot . '/backup/controller/backup_controller.class.php');
if (empty($CFG->siteadmins)) { // Should not happen on an ordinary site.
return false;
}
$admin = get_admin();
$userdoingthebackup = $admin->id; // Set this to the id of your admin account.
try {
// Prepare path.
$rootpath = rtrim(get_config('tool_coursearchiver', 'coursearchiverrootpath'), "/\\");
$archivepath = trim(str_replace(str_split(':*?"<>|'),
'',
get_config('tool_coursearchiver', 'coursearchiverpath')),
"/\\");
// Prepare backup filename.
$suffix = '-ID-' . $obj["course"]->id;
if (!empty($obj["course"]->idnumber)) {
$suffix .= '-IDNUM-' . $obj["course"]->idnumber;
}
// Clean backup filename.
$matchers = ['/\s/', '/\//', '/\;/', '/\:/', '/\?/', '/\%/', '/\*/', '/\|/', '/\</', '/\>/'];
$dirtyname = date("Y-m-d") . $suffix . "-" . $obj["course"]->shortname . ".mbz";
$archivefile = preg_replace($matchers, '-', $dirtyname);
// Check for custom folder.
$folder = $this->get_archive_folder();
// Final full path of file.
$path = $rootpath . '/' . $archivepath . '/' . $folder;
// If the path doesn't exist, make it so!
if (!is_dir($path)) {
umask(0000);
// Create the directory for CourseArchival.
if (!mkdir($path, $CFG->directorypermissions, true)) {
throw new Exception(get_string('errorarchivepath', 'tool_coursearchiver'));
}
}
// Close the session so that it doesn't lock other tabs/windows.
\core\session\manager::write_close();
// Perform Backup.
$bc = new backup_controller(backup::TYPE_1COURSE, $obj["course"]->id, backup::FORMAT_MOODLE,
backup::INTERACTIVE_NO, backup::MODE_GENERAL, $userdoingthebackup);
$bc->execute_plan(); // Execute backup.
$results = $bc->get_results(); // Get the file information needed.
$bc->destroy();
unset($bc);
if (!empty($results['backup_destination'])) { // Course backup file area.
$results['backup_destination']->copy_content_to($path . '/' . $archivefile);
} else { // Specified backup file area.
throw new Exception(get_string('errorbackup', 'tool_coursearchiver'));
}
if (file_exists($path . '/' . $archivefile)) { // Make sure file got moved.
$owners = $this->get_course_users_with_role($obj["course"]->id,
get_config('tool_coursearchiver', 'ownerroleid'));
$ownerslist = '|';
foreach ($owners["owners"] as $owner) {
$ownerslist .= $owner->id . '|';
}
// Save course info to the database.
$record = new stdClass();
$record->filename = $folder . '/' . $archivefile;
$record->owners = $ownerslist;
$record->timetodelete = 0;
// Backup alone could overwrite a previous backup. Don't make duplicate records.
if (!$DB->get_record('tool_coursearchiver_archived', ['filename' => $record->filename])) {
$DB->insert_record('tool_coursearchiver_archived', $record, false);
}
// Remove Course.
if ($delete) {
// Remove Course.
$task = new \tool_coursearchiver\task\delete_course();
$task->set_custom_data(['course' => $obj["course"]]);
\core\task\manager::queue_adhoc_task($task, true);
}
} else {
throw new Exception(get_string('errorarchivefile', 'tool_coursearchiver'));
}
} catch (Exception $e) {
return false;
}
return true;
}
/**
* Find and return the path to the last course archive file.
*
* @param int $courseid Moodle course id.
* @param string $dir path to course archives.
* @return string $filename name of the file path to rename.
*/
protected function find_course_file($courseid, $dir) {
// Calculate backup filename regex, ignoring the date/time/info parts that can be
// variable, depending of languages, formats and automated backup settings.
$filename = backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-' . $courseid . '-';
$regex = '#' . preg_quote($filename, '#') . '.*\.mbz#';
// Store all the matching files into filename => timemodified array.
$files = [];
foreach (scandir($dir) as $file) {
// Skip files not matching the naming convention.
if (!preg_match($regex, $file)) {
continue;
}
// Read the information contained in the backup itself.
try {
$bcinfo = backup_general_helper::get_backup_information_from_mbz($dir . '/' . $file);
} catch (backup_helper_exception $e) {
throw new Exception('Error: ' . $file . ' ' .
get_string('errorvalidarchive', 'tool_coursearchiver') .
' (' . $e->errorcode . ')');
continue;
}
// Make sure this backup concerns the course and site we are looking for.
if ($bcinfo->format === backup::FORMAT_MOODLE &&
$bcinfo->type === backup::TYPE_1COURSE &&
$bcinfo->original_course_id == $courseid &&
backup_general_helper::backup_is_samesite($bcinfo)) {
$files[$file] = $bcinfo->backup_date;
}
}
return $this->find_latest_file($files);
}
/**
* Sort and return the path to the last course archive file.
*
* @param array $files Moodle archive file list.
* @return string $filename name of the file path to rename.
*/
protected function find_latest_file($files) {
// Sort by values descending (newer to older filemodified).
arsort($files);
foreach ($files as $filename => $backupdate) {
// Make sure the backup is from today.
if (date('m/d/Y', $backupdate) == date('m/d/Y')) {
return $filename;
}
break; // Just the last backup...thanks!
}
return false;
}
/**
* Find and return archived course files.
*
* @return string of the folder name to be used.
*/
protected function get_archive_folder() {
if (!empty($this->folder)) {
$this->folder = str_replace(str_split('\\/:*?"<>|'), '', $this->folder);
} else { // If no custom folder is given, use the current year.
$this->folder = date('Y');
}
return $this->folder;
}
/**
* Sends an email to each course owner
*
* @param object $obj user array with courses attached (an array of userObject->courseObjects)
* @return # of emails sent (0 or 1)
*/
protected function sendemail($obj) {
global $CFG;
if (empty($CFG->siteadmins)) { // Should not happen on an ordinary site.
return false;
} else {
$admin = get_admin();
}
$config = get_config('tool_coursearchiver');
switch ($this->mode) {
case self::MODE_HIDEEMAIL:
$subject = get_string('hidewarningsubject', 'tool_coursearchiver');
$message = $config->hidewarningemailsetting;
break;
case self::MODE_ARCHIVEEMAIL:
$subject = get_string('archivewarningsubject', 'tool_coursearchiver');
$message = $config->archivewarningemailsetting;
break;
case self::MODE_DELETEEMAIL:
$subject = get_string('deletewarningsubject', 'tool_coursearchiver');
$message = $config->deletewarningemailsetting;
break;
default:
$this->errors[] = get_string('invalidmode', 'tool_coursearchiver');
return false;
}
// Note: get_email_courses() may return an empty HTML table.
if (strstr($message, '%courses_nolink')) {
$courses = $this->get_email_courses($obj, $config->optoutbyemailsetting);
$placeholder = '%courses_nolink';
} else {
$courses = $this->get_email_courses($obj, $config->optoutbyemailsetting);
$placeholder = '%courses';
}
if (empty($courses)) {
// This can only be an error.
throw new Exception('Incorrectly got an empty coures HTML table - this should be impossible');
} else if ($this->mode === self::MODE_HIDEEMAIL && empty(trim(strip_tags(implode('', $courses))))) {
// The user had no visible courses, so don't send an email to this user.
return 0;
} else {
$c = "";
foreach ($courses as $coursetext) {
$c .= $coursetext;
}
// Make sure both the %to variable and the %courses variable exist in the message template.
if (!strstr($message, '%to')) {
$this->errors[] = get_string('errormissingto', 'tool_coursearchiver');
return 0;
}
if (!strstr($message, $placeholder)) {
$this->errors[] = get_string('errormissingcourses', 'tool_coursearchiver');
return 0;
}
$vars = ['%to' => $obj["user"]->firstname . ' ' . $obj["user"]->lastname,
$placeholder => $c,
];
$message = strtr(nl2br($message), $vars);
$event = new \core\message\message();
$event->component = 'tool_coursearchiver';
$event->name = 'courseowner';
$event->userfrom = core_user::get_noreply_user();
$event->userto = $obj["user"];
$event->subject = $subject;
$event->fullmessage = '';
$event->fullmessageformat = FORMAT_MARKDOWN;
$event->fullmessagehtml = $message;
$event->smallmessage = $subject;
$event->notification = '1';
$event->contexturl = $CFG->wwwroot;
$event->contexturlname = get_string('coursearchiver', 'tool_coursearchiver');
$event->replyto = $admin->email;
if ($CFG->version > 2016110200) { // Moodle 3.2 and after.
$event->courseid = SITEID;
}
try {
if (message_send($event) === false) {
throw new Exception('There was a problem with data submitted to message_send()');
}
} catch (Exception $e) {
$this->errors[] = get_string('errorsendingemail', 'tool_coursearchiver', $obj["user"]) . ' ' . $e->getMessage();
return false;
}
return 1;
}
}
/**
* Reset the current process.
*
* @return void.
*/
public function reset() {
$this->processstarted = false;
$this->errors = [];
}
/**
* Return whether the course is empty or not.
*
* @param int $courseid the course id.
* @return bool
*/
protected function is_empty_course($courseid) {
global $DB;
// THIS FUNCTION IS BEING MODULARIZED SO THAT IN THE FUTURE WE CAN
// SELECT AT SEARCH TIME WHAT CONSTITUTES AN EMPTY COURSE.
// Course module count.
$modularsql = "1 < (
SELECT count(*)
FROM {course_modules}
WHERE course = :courseid1
)";
$params['courseid1'] = $courseid;
// Grade category count.
$modularsql .= !empty($modularsql) ? " OR " : "";
$modularsql .= "1 < (
SELECT count(*)
FROM {grade_categories}
WHERE courseid = :courseid2
)";
$params['courseid2'] = $courseid;
// Grade items count.
$modularsql .= !empty($modularsql) ? " OR " : "";
$modularsql .= "1 < (
SELECT count(*)
FROM {grade_items}
WHERE courseid = :courseid3
)";
$params['courseid3'] = $courseid;
// Check to see if course is meta child.
$modularsql .= !empty($modularsql) ? " OR " : "";
$modularsql .= "c.id IN (
SELECT customint1
FROM {enrol}
WHERE enrol = 'meta'
AND
status = 0
)";
$sql = "SELECT *
FROM {course} c
WHERE c.id = :courseid
AND ($modularsql)";
$params['courseid'] = $courseid;
if ($DB->get_records_sql($sql, $params)) {
return false;
} else {
return true;
}
}
/**
* Return whether the course has been opted out.
*
* @param int $courseid the course id.
* @return bool
*/
protected function is_opted_out($courseid) {
global $DB;
$sql = "SELECT *
FROM {tool_coursearchiver_optout} c
WHERE c.courseid = :courseid";
$params['courseid'] = $courseid;
if ($optout = $DB->get_record_sql($sql, $params)) {
$date = new DateTime("now", core_date::get_user_timezone_object());
$months = $optout->optoutlength;
$date->modify("-$months months");
$optouttime = $date->getTimestamp();
if ($months == 0 || $optout->optouttime - $optouttime >= 0) {
return true;
}