-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.php
2025 lines (1632 loc) · 67.5 KB
/
lib.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
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 - http://moodle.org/
//
// 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 enrol_ues
* @copyright 2008 onwards Louisiana State University
* @copyright 2008 onwards Philip Cali, Adam Zapletal, Chad Mazilly, Robert Russo, Dave Elliott
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once(dirname(__FILE__) . '/publiclib.php');
class enrol_ues_plugin extends enrol_plugin {
/**
* Typical error log
*
* @var array
*/
private $errors = array();
/**
* Typical email log
*
* @var array
*/
private $emaillog = array();
/**
* admin config setting
*
* @var bool
*/
public $issilent = false;
/**
* an instance of the ues enrollment provider.
*
* Provider is configured in admin settings.
*
* @var enrollment_provider $_provider
*/
private $_provider;
/**
* Provider initialization status.
*
* @var bool
*/
private $_loaded = false;
/**
* Require internal and external libs.
*
* @global object $CFG
*/
public function __construct() {
global $CFG;
ues::require_daos();
require_once($CFG->dirroot . '/group/lib.php');
require_once($CFG->dirroot . '/course/lib.php');
}
/**
* Master method for kicking off UES enrollment
* First checks a few top-level requirements to run, and then passes on to a secondary method for handling the process
*
* @param boolean $run_as_adhoc whether or not the task has been run "ad-hoc" or "scheduled" (default)
* @return boolean
*/
public function run_enrollment_process($runasadhoc = false) {
global $CFG;
// Capture start time for later use.
$starttime = microtime(true);
// First, run a few top-level checks before processing enrollment.
try {
// Make sure task is NOT disabled (if not run adhoc).
if (!$runasadhoc and ! $this->task_is_enabled()) {
// TODO: Make a real lang string for this.
throw new UesInitException('This scheduled task has been disabled.');
}
// Make sure UES is NOT running.
if ($this->is_running()) {
throw new UesInitException(
ues::_s('already_running', $CFG->wwwroot . '/admin/settings.php?section=enrolsettingsues')
);
}
// Make sure UES is not within grace period threshold.
if ($this->is_within_graceperiod()) {
throw new UesInitException(
ues::_s('within_grace_period', $CFG->wwwroot . '/admin/settings.php?section=enrolsettingsues')
);
}
// Attempt to fetch the configured enrollment provider.
$provider = $this->provider();
// Make sure we have a provider loaded before we proceed any further.
if (!$provider) {
// TODO: Make a real lang string for this.
throw new UesInitException('Could not load the enrollment provider.');
}
// Catch any initial errors here before attempting to run.
} catch (UesInitException $e) {
// Add the error to the stack.
$this->add_error($e->getMessage());
// Email the error report, reporting errors only.
$this->email_reports(true);
// Leave the process.
return false;
}
// Now, begin using the provider to pull data and manifest enrollment.
// Note start time for reporting.
return $this->run_provider_enrollment($provider, $starttime);
}
/**
* Runs enrollment for a given UES provider
*
* @param enrollment_provider $provider
* @param float $start_time the current time in seconds since the Unix epoch
* @return boolean success
*/
public function run_provider_enrollment($provider, $starttime) {
// First, flag the process as running.
$this->setting('running', true);
// Send startup email.
$this->email_startup_report($starttime);
// Begin log messages.
$this->log('------------------------------------------------');
$this->log(ues::_s('pluginname'));
$this->log('------------------------------------------------');
// Handle any provider preprocesses.
if (!$provider->preprocess($this)) {
$this->add_error('Error during preprocess.');
}
// Pull provider data.
$this->log('Pulling information from ' . $provider->get_name());
$this->process_all();
$this->log('------------------------------------------------');
// Manifest provider data.
$this->log('Begin manifestation ...');
$this->handle_enrollments();
// Handle any provider postprocesses.
if (!$provider->postprocess($this)) {
$this->add_error('Error during postprocess.');
}
// End log messages.
$this->log('------------------------------------------------');
$this->log('UES enrollment took: ' . $this->get_time_elapsed_during_enrollment($starttime));
$this->log('------------------------------------------------');
// Flag the process as no longer running.
$this->setting('running', false);
// Email final report.
$this->email_reports(false, $starttime);
// Handle any errors automatically per threshold settings.
// TODO: This causes a blank email to be sent even if everything ran OK.
$this->handle_automatic_errors();
$this->email_reports(true);
return true;
}
/**
* Emails a UES "startup" report to moodle administrators
*
* @param float $start_time the current time in seconds since the Unix epoch
* @return void
*/
private function email_startup_report($starttime) {
// Get all moodle admin users.
$users = get_admins();
// Email these users the job has begun.
$this->email_ues_startup_report_to_users($users, $starttime);
}
/**
* Emails a UES startup report (notification of start time) to given users
*
* @param array $users moodle users
* @param float $start_time the current time in seconds since the Unix epoch
* @return void
*/
private function email_ues_startup_report_to_users($users, $starttime) {
global $CFG;
$starttimedisplay = $this->format_time_display($starttime);
// Get email content from email log.
$emailcontent = 'This email is to let you know that UES Enrollment has begun at:' . $starttimedisplay;
// Send to each admin.
foreach ($users as $user) {
email_to_user($user, ues::_s('pluginname'), sprintf('UES Enrollment Begun [%s]', $CFG->wwwroot), $emailcontent);
}
}
/**
* Finds and emails moodle administrators enrollment reports
*
* Optionally, skips the default log report and send errors only
*
* @param boolean $report_errors_only
* @param float $start_time the current time in seconds since the Unix epoch
* @return void
*/
public function email_reports($reporterrorsonly = false, $starttime = '') {
// Get all moodle admin users.
$users = get_admins();
// Determine whether or not we're sending an email log report to admins.
if (!$reporterrorsonly and $this->setting('email_report')) {
$this->email_ues_log_report_to_users($users, $starttime);
}
// Determine whether or not there are errors to report.
if ($this->errors_exist()) {
$this->email_ues_error_report_to_users($users, $starttime);
}
}
/**
* Emails a UES log report (from emaillog) to given users
*
* @param array $users moodle users
* @param float $start_time the current time in seconds since the Unix epoch
* @return void
*/
private function email_ues_log_report_to_users($users, $starttime) {
global $CFG;
// Get email content from email log.
$emailcontent = implode("\n", $this->emaillog);
if ($starttime) {
$starttimedisplay = $this->format_time_display($starttime);
$emailcontent .= "\n\nThis process began at: " . $starttimedisplay;
}
// Send to each admin.
foreach ($users as $user) {
email_to_user($user, ues::_s('pluginname'), sprintf('UES Log [%s]', $CFG->wwwroot), $emailcontent);
}
}
/**
* Emails a UES error report (from errors stack) to given users
*
* @param array $users moodle users
* @param float $start_time the current time in seconds since the Unix epoch
* @return void
*/
private function email_ues_error_report_to_users($users, $starttime) {
global $CFG;
// Get email content from error log.
$emailerrorcontent = implode("\n", $this->get_errors());
if ($starttime) {
$starttimedisplay = $this->format_time_display($starttime);
$emailerrorcontent .= "\n\nThis process begun at: " . $starttimedisplay;
}
// Send to each admin.
foreach ($users as $user) {
email_to_user($user, ues::_s('pluginname'), sprintf('[SEVERE] UES Errors [%s]', $CFG->wwwroot), $emailerrorcontent);
}
}
/**
* Determines whether or not there are any saved errors at this point
*
* @return bool
*/
private function errors_exist() {
return (empty($this->get_errors())) ? false : true;
}
/**
* Formats a Unix time for display
*
* @param float $start_time the current time in seconds since the Unix epoch
* @return string
*/
private function format_time_display($time) {
$dformat = "l jS F, Y - H:i:s";
$msecs = $time - floor($time);
$msecs = substr($msecs, 1);
$formatted = sprintf('%s%s', date($dformat), $msecs);
return $formatted;
}
/**
* Calculates amount of time (in seconds) that has elapsed since a given start time
*
* @param float $start_time the current time in seconds since the Unix epoch
* @return string time difference in seconds
*/
private function get_time_elapsed_during_enrollment($starttime) {
// Get the difference between start and end in microseconds, as a float value.
$diff = microtime(true) - $starttime;
// Break the difference into seconds and microseconds.
$sec = intval($diff);
$micro = $diff - $sec;
// Format the result as you want it - will contain something like "00:00:02.452".
$timeelapsed = strftime('%T', mktime(0, 0, $sec)) . str_replace('0.', '.', sprintf('%.3f', $micro));
return $timeelapsed;
}
/**
* Getter for self::$_provider.
*
* If self::$provider is not set already, this method
* will attempt to initialize it by calling self::init()
* before returning the value of self::$_provider
* @return enrollment_provider
*/
public function provider() {
if (empty($this->_provider) and !$this->_loaded) {
$this->init();
}
return $this->_provider;
}
/**
* Try to initialize the provider.
*
* Tries to create and initialize the provider.
* Tests whether provider supports departmental or section lookups.
* @throws Exception if provider cannot be created of if provider supports
* neither section nor department lookups.
*/
public function init() {
try {
$this->_provider = ues::create_provider();
if (empty($this->_provider)) {
throw new Exception('enrollment_unsupported');
}
$works = (
$this->_provider->supports_section_lookups() or
$this->_provider->supports_department_lookups()
);
if ($works === false) {
throw new Exception('enrollment_unsupported');
}
} catch (Exception $e) {
$a = ues::translate_error($e);
$this->add_error(ues::_s('provider_cron_problem', $a));
}
$this->_loaded = true;
}
public function course_updated($inserted, $course, $data) {
// UES is the one to create the course.
if ($inserted) {
return;
}
}
private function handle_automatic_errors() {
$errors = ues_error::get_all();
$errorthreshold = $this->setting('error_threshold');
$running = (bool)$this->setting('running');
// Don't reprocess if the module is running.
if ($running) {
return;
}
if (count($errors) > $errorthreshold) {
$this->add_error(ues::_s('error_threshold_log'));
return;
}
ues::reprocess_errors($errors, true);
}
public function handle_enrollments() {
// Users will be unenrolled.
$pending = ues_section::get_all(array('status' => ues::PENDING));
$this->handle_pending_sections($pending);
// Users will be enrolled.
$processed = ues_section::get_all(array('status' => ues::PROCESSED));
$this->handle_processed_sections($processed);
}
/**
* Get (fetch, instantiate, save) semesters
* considered valid at the current time, and
* process enrollment for each.
*/
public function process_all() {
$time = time();
$processedsemesters = $this->get_semesters($time);
foreach ($processedsemesters as $semester) {
$this->process_semester($semester);
}
}
/**
* @param ues_semester[] $semester
*/
public function process_semester($semester) {
$processcourses = $this->get_courses($semester);
if (empty($processcourses)) {
return;
}
$setbydepartment = (bool) $this->setting('process_by_department');
$supportsdepartment = $this->provider()->supports_department_lookups();
$supportssection = $this->provider()->supports_section_lookups();
if ($setbydepartment and $supportsdepartment) {
$this->process_semester_by_department($semester, $processcourses);
} else if (!$setbydepartment and $supportssection) {
$this->process_semester_by_section($semester, $processcourses);
} else {
$message = ues::_s('could_not_enroll', $semester);
$this->log($message);
$this->add_error($message);
}
}
/**
* @param ues_semester $semester
* @param ues_course[] $courses NB: must have department attribute set
*/
private function process_semester_by_department($semester, $courses) {
$departments = ues_course::flatten_departments($courses);
foreach ($departments as $department => $courseids) {
$filters = ues::where()->semesterid->equal($semester->id)->courseid->in($courseids);
// Current means they already exist in the DB.
$currentsections = ues_section::get_all($filters);
$this->process_enrollment_by_department(
$semester, $department, $currentsections
);
}
}
private function process_semester_by_section($semester, $courses) {
foreach ($courses as $course) {
foreach ($course->sections as $section) {
$uessection = ues_section::by_id($section->id);
$this->process_enrollment(
$semester, $course, $uessection
);
}
}
}
/**
* From enrollment provider, get, instantiate,
* save (to {enrol_ues_semesters}) and return all valid semesters.
* @param int time
* @return ues_semester[] these objects will be later upgraded to ues_semesters
*
*/
public function get_semesters($time) {
$setdays = (int) $this->setting('sub_days');
$subdays = 24 * $setdays * 60 * 60;
$now = ues::format_time($time - $subdays);
$this->log('Pulling Semesters for ' . $now . '...');
try {
$semestersource = $this->provider()->semester_source();
$semesters = $semestersource->semesters($now);
$this->log('Processing ' . count($semesters) . " Semesters...\n");
$psemesters = $this->process_semesters($semesters);
$v = function($s) {
return !empty($s->grades_due);
};
$i = function($s) {
return !empty($s->semester_ignore);
};
list($other, $failures) = $this->partition($psemesters, $v);
// Notify improper semester.
foreach ($failures as $failedsem) {
$this->add_error(ues::_s('failed_sem', $failedsem));
}
list($ignored, $valids) = $this->partition($other, $i);
// Ignored sections with semesters will be unenrolled.
foreach ($ignored as $ignoredsem) {
$wheremanifested = ues::where()->semesterid->equal($ignoredsem->id)->status->equal(ues::MANIFESTED);
$todrop = array('status' => ues::PENDING);
// This will be caught in regular process.
ues_section::update($todrop, $wheremanifested);
}
$semsin = function ($sem) use ($time, $subdays) {
$endcheck = $time < $sem->grades_due;
return ($sem->classes_start - $subdays) < $time && $endcheck;
};
return array_filter($valids, $semsin);
} catch (Exception $e) {
$this->add_error($e->getMessage());
return array();
}
}
public function partition($collection, $func) {
$pass = array();
$fail = array();
foreach ($collection as $key => $single) {
if ($func($single)) {
$pass[$key] = $single;
} else {
$fail[$key] = $single;
}
}
return array($pass, $fail);
}
/**
* Fetch courses from the enrollment provider, and pass them to
* process_courses() for instantiations as ues_course objects and for
* persisting to {enrol_ues(_courses|_sections)}.
*
* @param ues_semester $semester
* @return ues_course[]
*/
public function get_courses($semester) {
$this->log('Pulling Courses / Sections for ' . $semester);
try {
$courses = $this->provider()->course_source()->courses($semester);
$this->log('Processing ' . count($courses) . " Courses...\n");
$processcourses = $this->process_courses($semester, $courses);
return $processcourses;
} catch (Exception $e) {
$this->add_error(sprintf(
'Unable to process courses for %s; Message was: %s',
$semester,
$e->getMessage()
));
// Queue up errors.
ues_error::courses($semester)->save();
return array();
}
}
/**
* Workhorse method that brings enrollment data from the provider together with existing records
* and then dispatches sub processes that operate on the differences between the two.
*
* @param ues_semester $semester semester to process
* @param string $department department to process
* @param ues_section[] $current_sections current UES records for the department/semester combination
*/
public function process_enrollment_by_department($semester, $department, $currentsections) {
try {
$teachersource = $this->provider()->teacher_department_source();
$studentsource = $this->provider()->student_department_source();
$teachers = $teachersource->teachers($semester, $department);
$students = $studentsource->students($semester, $department);
$sectionids = ues_section::ids_by_course_department($semester, $department);
$filter = ues::where('sectionid')->in($sectionids);
$currentteachers = ues_teacher::get_all($filter);
$currentstudents = ues_student::get_all($filter);
$idsparam = ues::where('id')->in($sectionids);
$allsections = ues_section::get_all($idsparam);
$this->process_teachers_by_department($semester, $department, $teachers, $currentteachers);
$this->process_students_by_department($semester, $department, $students, $currentstudents);
unset($currentteachers);
unset($currentstudents);
foreach ($currentsections as $section) {
$course = $section->course();
// Set status to ues::PROCESSED.
$this->post_section_process($semester, $course, $section);
unset($allsections[$section->id]);
}
// Drop remaining sections.
if (!empty($allsections)) {
ues_section::update(
array('status' => ues::PENDING),
ues::where('id')->in(array_keys($allsections))
);
}
} catch (Exception $e) {
$info = "$semester $department";
$message = sprintf(
"Message: %s\nFile: %s\nLine: %s\nTRACE:\n%s\n",
$e->getMessage(),
$e->getFile(),
$e->getLine(),
$e->getTraceAsString()
);
$this->add_error(sprintf('Failed to process %s:\n%s', $info, $message));
ues_error::department($semester, $department)->save();
}
}
/**
*
* @param ues_semester $semester
* @param string $department
* @param object[] $teachers
* @param ues_teacher[] $current_teachers
*/
public function process_teachers_by_department($semester, $department, $teachers, $currentteachers) {
$this->fill_roles_by_department('teacher', $semester, $department, $teachers, $currentteachers);
}
/**
*
* @param ues_semester $semester
* @param string $department
* @param object[] $students
* @param ues_student[] $current_students
*/
public function process_students_by_department($semester, $department, $students, $currentstudents) {
$this->fill_roles_by_department('student', $semester, $department, $students, $currentstudents);
}
/**
*
* @param string $type @see process_teachers_by_department
* and @see process_students_by_department for possible values 'student'
* or 'teacher'
* @param ues_section $semester
* @param string $department
* @param object[] $pulled_users incoming users from the provider
* @param ues_teacher[] | ues_student[] $current_users all UES users for this semester
*/
private function fill_roles_by_department($type, $semester, $department, $pulledusers, $currentusers) {
foreach ($pulledusers as $user) {
$courseparams = array(
'department' => $department,
'cou_number' => $user->cou_number
);
$course = ues_course::get($courseparams);
if (empty($course)) {
continue;
}
$sectionparams = array(
'semesterid' => $semester->id,
'courseid' => $course->id,
'sec_number' => $user->sec_number
);
$section = ues_section::get($sectionparams);
if (empty($section)) {
continue;
}
$this->{'process_'.$type.'s'}($section, array($user), $currentusers);
}
$this->release($type, $currentusers);
}
/**
*
* @param stdClass[] $semesters
* @return ues_semester[]
*/
public function process_semesters($semesters) {
$processed = array();
foreach ($semesters as $semester) {
try {
$params = array(
'year' => $semester->year,
'name' => $semester->name,
'campus' => $semester->campus,
'session_key' => $semester->session_key
);
// Convert the obj to full-fledged ues semester.
$ues = ues_semester::upgrade_and_get($semester, $params);
if (empty($ues->classes_start)) {
continue;
}
// Persist to Database table ues_semesters.
$ues->save();
// Fill in metadata from the table enrol_ues_semestermeta.
$ues->fill_meta();
$processed[] = $ues;
} catch (Exception $e) {
$this->add_error($e->getMessage());
}
}
return $processed;
}
/**
* For each of the courses provided, instantiate as a ues_course
* object; persist to the {enrol_ues_courses} table; then iterate
* through each of its sections, instantiating and persisting each.
* Then, assign the sections to the <code>course->sections</code> attirbute,
* and add the course to the return array.
*
* @param ues_semester $semester
* @param object[] $courses
* @return ues_course[]
*/
public function process_courses($semester, $courses) {
$processed = array();
foreach ($courses as $course) {
try {
$params = array(
'department' => $course->department,
'cou_number' => $course->cou_number
);
$uescourse = ues_course::upgrade_and_get($course, $params);
$uescourse->save();
$processedsections = array();
foreach ($uescourse->sections as $section) {
$params = array(
'courseid' => $uescourse->id,
'semesterid' => $semester->id,
'sec_number' => $section->sec_number
);
$uessection = ues_section::upgrade_and_get($section, $params);
/*
* If the section does not already exist
* in {enrol_ues_sections}, insert it,
* marking its status as PENDING.
*/
if (empty($uessection->id)) {
$uessection->courseid = $uescourse->id;
$uessection->semesterid = $semester->id;
$uessection->status = ues::PENDING;
$uessection->save();
}
$processedsections[] = $uessection;
}
/*
* Replace the sections attribute of the course with
* the fully instantiated, and now persisted,
* ues_section objects.
*/
$uescourse->sections = $processedsections;
$processed[] = $uescourse;
} catch (Exception $e) {
$this->add_error($e->getMessage());
}
}
return $processed;
}
/**
* Could be used to process a single course upon request
*/
public function process_enrollment($semester, $course, $section) {
$teachersource = $this->provider()->teacher_source();
$studentsource = $this->provider()->student_source();
try {
$teachers = $teachersource->teachers($semester, $course, $section);
$students = $studentsource->students($semester, $course, $section);
$filter = array('sectionid' => $section->id);
$currentteachers = ues_teacher::get_all($filter);
$currentstudents = ues_student::get_all($filter);
$this->process_teachers($section, $teachers, $currentteachers);
$this->process_students($section, $students, $currentstudents);
$this->release('teacher', $currentteachers);
$this->release('student', $currentstudents);
$this->post_section_process($semester, $course, $section);
} catch (Exception $e) {
$this->add_error($e->getMessage());
ues_error::section($section)->save();
}
}
private function release($type, $users) {
foreach ($users as $user) {
// No reason to release a second time.
if ($user->status == ues::UNENROLLED) {
continue;
}
// Maybe the course hasn't been created... clear the pending flag.
$status = $user->status == ues::PENDING ? ues::UNENROLLED : ues::PENDING;
$user->status = $status;
$user->save();
global $CFG;
if ($type === 'teacher') {
if (file_exists($CFG->dirroot.'/blocks/cps/events/ues.php')) {
require_once($CFG->dirroot.'/blocks/cps/events/ues.php');
// Specific release for instructor.
$user = cps_ues_handler::ues_teacher_release($user);
}
} else if ($type === 'student') {
if (file_exists($CFG->dirroot.'/blocks/ues_logs/eventslib.php')) {
require_once($CFG->dirroot.'/blocks/ues_logs/eventslib.php');
ues_logs_event_handler::ues_student_release($user);
}
}
// Drop manifested sections for teacher POTENTIAL drops.
if ($user->status == ues::PENDING and $type == 'teacher') {
$existing = ues_teacher::get_all(ues::where()->status->in(ues::PROCESSED, ues::ENROLLED));
// No other primary, so we can safely flip the switch.
if (empty($existing)) {
ues_section::update(
array('status' => ues::PENDING),
array(
'status' => ues::MANIFESTED,
'id' => $user->sectionid
)
);
}
}
}
}
private function post_section_process($semester, $course, $section) {
// Process section only if teachers can be processed.
// Take into consideration outside forces manipulating.
// Processed numbers through event handlers.
$byprocessed = ues::where()->status->in(ues::PROCESSED, ues::ENROLLED)->sectionid->equal($section->id);
$processedteachers = ues_teacher::count($byprocessed);
// A section _can_ be processed only if they have a teacher.
// Further, this has to happen for a section to be queued for enrollment.
if (!empty($processedteachers)) {
// Full section.
$section->semester = $semester;
$section->course = $course;
$previousstatus = $section->status;
$count = function ($type) use ($section) {
$enrollment = ues::where()->sectionid->equal($section->id)->status->in(ues::PROCESSED, ues::PENDING);
$class = 'ues_'.$type;
return $class::count($enrollment);
};
$willenroll = ($count('teacher') or $count('student'));
if ($willenroll) {
// Make sure the teacher will be enrolled.
ues_teacher::reset_status($section, ues::PROCESSED, ues::ENROLLED);
$section->status = ues::PROCESSED;
}
// Allow outside interaction.
global $CFG;
if (file_exists($CFG->dirroot.'/blocks/cps/events/ues.php')) {
require_once($CFG->dirroot.'/blocks/cps/events/ues.php');
$section = cps_ues_handler::ues_section_process($section);
}
if ($previousstatus != $section->status) {
$section->save();
}
}
}
public function process_teachers($section, $users, &$currentusers) {
return $this->fill_role('teacher', $section, $users, $currentusers, function($user) {
return array('primary_flag' => $user->primary_flag);
});
}
/**
* Process students.
*
* This function passes params on to enrol_ues_plugin::fill_role()
* which does not return any value.
*
* @see enrol_ues_plugin::fill_role()
* @param ues_section $section
* @param object[] $users
* @param (ues_student | ues_teacher)[] $current_users
* @return void
*/
public function process_students($section, $users, &$currentusers) {
return $this->fill_role('student', $section, $users, $currentusers);
}
// Allow public API to reset unenrollments.
public function reset_unenrollments($section) {
$course = $section->moodle();