-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlocallib.php
2769 lines (2265 loc) · 115 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
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
/**
* SHEBanG enrolment plugin/module for SunGard HE Banner(r) data import
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
* @author Fred Woolard <[email protected]>
* @copyright (c) 2010 Appalachian State Universtiy, Boone, NC
* @license GNU General Public License version 3
* @package enrol
* @subpackage shebang
*/
defined('MOODLE_INTERNAL') || die();
require_once("$CFG->dirroot/course/lib.php");
require_once("$CFG->dirroot/group/lib.php");
require_once("$CFG->dirroot/lib/weblib.php");
/**
* Utility class to process LMB messages
*/
class enrol_shebang_processor
{
/* -------------------------------------------------------------------
* Class constants
*/
const PLUGIN_NAME = 'enrol_shebang';
const PLUGIN_PATH = '/enrol/shebang';
const ROLETYPE_LEARNER = '01';
const ROLETYPE_INSTRUCTOR = '02';
const ROLETYPE_CONTENTDEV = '03';
const ROLETYPE_MEMBER = '04';
const ROLETYPE_MANAGER = '05';
const ROLETYPE_MENTOR = '06';
const ROLETYPE_ADMINISTRATOR = '07';
const ROLETYPE_TEACHINGASST = '08';
const IDTYPE_PERSON = '1';
const IDTYPE_GROUP = '2';
const RECSTATUS_ADD = '1';
const RECSTATUS_UPDATE = '2';
const RECSTATUS_DELETE = '3';
const STATUS_INACTIVE = '0';
const STATUS_ACTIVE = '1';
const MKDIR_MODE = 02770;
const INFILE_BLOCK_SIZE = 32768;
const LOGFILE_BASENAME_PROCESS = 'process_log.';
const LOGFILE_BASENAME_MESSAGE = 'message_log.';
const DATEFMT_LOG_FILEX = 'Ymd';
const DATEFMT_LOG_ENTRY = 'Y-m-d\TH:i:s O';
const DATEFMT_SQL_VALUE = 'Y-m-d H:i:s';
const LMBTAG_PROPERTIES = 'PROPERTIES';
const LMBTAG_GROUP = 'GROUP';
const LMBTAG_PERSON = 'PERSON';
const LMBTAG_MEMBERSHIP = 'MEMBERSHIP';
const LMBTAG_TYPEVALUE_COLLEGE = 'COLLEGE';
const LMBTAG_TYPEVALUE_DEPT = 'DEPARTMENT';
const LMBTAG_TYPEVALUE_TERM = 'TERM';
const LMBTAG_TYPEVALUE_COURSE = 'COURSE';
const LMBTAG_TYPEVALUE_SECTION = 'COURSESECTION';
const LMBTAG_TYPEVALUE_CROSSLIST = 'CROSSLISTEDSECTION';
const LMBTAG_TYPEVALUE_SEGMENT = 'SEGMENT';
/*
* Moodle database entity (table) names
*/
const MOODLENT_USER = 'user';
const MOODLENT_COURSE = 'course';
const MOODLENT_COURSE_CATEGORY = 'course_categories';
const MOODLENT_COURSE_SECTION = 'course_sections';
const MOODLENT_ROLE_ASSIGNMENT = 'role_assignments';
const MOODLENT_GROUP = 'groups';
const MOODLENT_ENROL = 'enrol';
const MOODLENT_USER_ENROL = 'user_enrolments';
/*
* Plugin database entity (table) names
*/
const SHEBANGENT_TERM = 'enrol_shebang_term';
const SHEBANGENT_PERSON = 'enrol_shebang_person';
const SHEBANGENT_SECTION = 'enrol_shebang_section';
const SHEBANGENT_MEMBER = 'enrol_shebang_member';
const SHEBANGENT_CROSSLIST = 'enrol_shebang_crosslist';
/*
* Config value options
*/
const OPT_PERSON_DELETE_DELETE = 'delete';
const OPT_PERSON_DELETE_UNENROL = 'unenrol';
const OPT_PERSON_USERNAME_EMAIL = 'email';
const OPT_PERSON_USERNAME_USERID_EMAIL = 'userid_email';
const OPT_PERSON_USERNAME_USERID_LOGON = 'userid_logon';
const OPT_PERSON_USERNAME_USERID_SCTID = 'userid_sctid';
const OPT_PERSON_PASSWORD_USERID_LOGON = 'userid_logon';
const OPT_PERSON_PASSWORD_USERID_SCTID = 'userid_sctid';
const OPT_PERSON_LOCALITY_DEF = 'def';
const OPT_PERSON_LOCALITY_MSG = 'msg';
const OPT_PERSON_LOCALITY_IFF = 'iff';
const OPT_AUTH_SHIBBOLETH = 'shibboleth';
const OPT_AUTH_SHIBBUNCIF = 'shibbuncif';
const OPT_AUTH_MANUAL = 'manual';
const OPT_AUTH_NOLOGIN = 'nologin';
const OPT_COURSE_CATEGORY_TERM = 'term';
const OPT_COURSE_CATEGORY_DEPT = 'dept';
const OPT_COURSE_CATEGORY_NEST = 'nest';
const OPT_COURSE_CATEGORY_PICK = 'pick';
const OPT_SECURE_METHOD_BASIC = 'basic';
const OPT_SECURE_METHOD_DIGEST = 'digest';
/*
* Config value defaults
*/
const DEF_PERSON_COUNTRY = 'US';
const DEF_PERSON_AUTH_METHOD = 'nologin';
const DEF_MONITOR_START_HOUR = '9';
const DEF_MONITOR_START_MIN = '00';
const DEF_MONITOR_STOP_HOUR = '17';
const DEF_MONITOR_STOP_MIN = '00';
const DEF_MONITOR_THRESHOLD = '30';
const MAX_MONITOR_THRESHOLD = 1440;
const MIN_MONITOR_THRESHOLD = 5;
const MONITOR_NOTICES_INTERVAL = 30;
const MAX_COURSE_PARENT_STRIPLEAD = 10;
const MAX_LEN_PERSON_STREET = 70;
/* -------------------------------------------------------------------
* Class member vars
*/
/**
* Plugin config values
*
* @var stdClass
* @access private
*/
private $config = null;
/**
* Reference var to Moodle's global $CFG
*
* @var stdClass
* @access private
*/
private $moodleConfigs = null;
/**
* Reference var to Moodle's global $DB
*
* @var moodle_database
* @access private
*/
private $moodleDB = null;
/**
* Where to log the LMB messages received
*
* @var string
* @access private
*/
private $messageLogPath = '';
/**
* Resource for the LMB message log file
*
* @var resource
* @access private
*/
private $messageLogRes = null;
/**
* Where to log the processing info messages
*
* @var string
* @access private
*/
private $processLogPath = '';
/**
* Boolean to tell the parser_character_data() callback routine
* whether to append to the $parseDataBuffer or not
*
* @var boolean
* @access private
*/
private $buffering = false;
/**
* Buffers up the parsed XML
*
* @var string
* @access private
*/
private $parseDataBuffer = '';
/**
* Return code from last message processing
*
* @var boolean
* @access private
*/
private $lastRetCode = false;
/**
* When importing a Banner extract file, holds the <datetime> value
*
* @var int
* @access private
*/
private $importFileDatetime = null;
/**
* Cache of roles, keyed by id
*
* @var array
* @access private
*/
private $roleCache = array();
/**
* Did a course insert take place
*
* @var boolean
* @access private
*/
private $courseInserted = false;
/**
* Array of recognized tokens used for fashioning course names
*
* @var array
* @access public
* @static
*/
public static $courseNameTokens = array('/%termcode%/i', '/%termdesc%/i',
'/%fullname%/i', '/%longname%/i', '/%shortname%/i', '/%sourceid%/i',
'/%deptcode%/i', '/%deptname%/i',
'/%parentcode%/i',
'/%coursenum%/i', '/%sectionnum%/i');
/**
* Where do the process, message logs go
*
* @var string
* @access private
*/
private $logging_dirpath = '';
/**
* Instance of the enrol plugin
*
* @var enrol_shebang_plugin
* @access private
*/
private $enrol_plugin = null;
/* -------------------------------------------------------------------
* Class methods
*/
/**
* Constructor
*
* @uses $CFG, $DB
*/
function __construct()
{
global $CFG, $DB;
// Make a reference to the global configs
$this->moodleConfigs = $CFG;
// Make a reference to the global database connection
$this->moodleDB = $DB;
$this->config = get_config(self::PLUGIN_NAME);
$this->enrol_plugin = enrol_get_plugin('shebang');
// Parse the course term filter
$this->config->term_filters = array();
if (!empty($this->config->course_term_filter)) {
$this->config->term_filters = array_map('trim', explode(',', $this->config->course_term_filter));
}
} // __construct
/**
* Get plugin config value
*
* @access public
* @param string $name
* @param mixed $default
* @return mixed
*/
public function get_config($name, $default = null)
{
return isset($this->config->$name) ? $this->config->$name : $default;
}
/**
* Accessor for security config - username
*
* @access public
* @return string
*/
public function getSecureUsername()
{
return $this->config->secure_username;
}
/**
* Accessor for security config - password
*
* @access public
* @return string
*/
public function getSecurePassword()
{
return $this->config->secure_passwd;
}
/**
* Accessor for security config - method
*
* @access public
* @return string
*/
public function getSecureMethod()
{
return $this->config->secure_method;
}
/**
* Make sure process and message log files are present and writable
*
* @access private
* @return void
*/
private function prepare_logfiles()
{
// If alternate directory configured then
// verify it exists and is writable
if (!empty($this->config->logging_dirpath)) {
$this->logging_dirpath = make_writable_directory(preg_replace('/\/+$/', '', trim($this->config->logging_dirpath)), false);
}
// If alternate directory not set or did not
// verify as writable dir, then use default
if (empty($this->logging_dirpath)) {
$this->logging_dirpath = make_writable_directory($this->moodleConfigs->dataroot . "/" . self::PLUGIN_NAME, false);
}
// If directory still not set at this point
// then neither alternate nor default verified
if (empty($this->logging_dirpath)) {
error_log(get_string('ERR_DATADIR_CREATE', self::PLUGIN_NAME));
throw new moodle_exception('ERR_DATADIR_CREATE', self::PLUGIN_NAME);
}
$log_date_suffix = date(self::DATEFMT_LOG_FILEX);
$this->messageLogPath = $this->logging_dirpath . "/" . self::LOGFILE_BASENAME_MESSAGE . $log_date_suffix;
$this->processLogPath = $this->logging_dirpath . "/" . self::LOGFILE_BASENAME_PROCESS . $log_date_suffix;
// Touch the message log before we need it, so we can die if no joy
if (!file_exists($this->messageLogPath) && !touch($this->messageLogPath)) {
error_log(get_string('ERR_MESGLOG_NOOPEN', self::PLUGIN_NAME));
throw new moodle_exception('ERR_MESGLOG_NOOPEN', self::PLUGIN_NAME);
}
// Touch the process log before we need it, so we can die if no joy
if (!file_exists($this->processLogPath) && !touch($this->processLogPath)) {
error_log(get_string('ERR_PROCLOG_NOOPEN', self::PLUGIN_NAME));
throw new moodle_exception('ERR_PROCLOG_NOOPEN', self::PLUGIN_NAME);
}
} // prepare_logfiles
/**
* Write the LMB posted message contents to a text file in the Moodle
* data directory.
*
* @access private
* @param string $msg_id LMB message id from HTTP headers
* @param string $data XML that was *POST*ed by LMB
* @param boolean $keep_lock Whether or not to keep file lock
* @param boolean $result Success or failure
* @return void
*/
private function log_lmb_message($msg_id, $data, $keep_lock = false, $result = null)
{
/* We run the risk of bogging down the message processing, but
* it will help to serialize the processing of the messages
* coming in from the LMB. No logic is being done here, just
* lock-write-release. The log file name is a canonical form
* using the date, e.g. 'message_log.YYYYMMDD' and is in our
* log directory in the Moodle data directory.
*/
if (isset($this->config->logging_nologlock) && !empty($this->config->logging_nologlock)) {
// Defeat the locking if told to do so
$keep_lock = false;
}
if ((null == $this->messageLogRes) && (!($this->messageLogRes = fopen($this->messageLogPath, 'a')) || !flock($this->messageLogRes, LOCK_EX))) {
throw new Exception(get_string('ERR_MESGLOG_NOOPEN', self::PLUGIN_NAME));
}
$log_time = date(self::DATEFMT_LOG_ENTRY);
$log_mesg = "#{$log_time}#{$msg_id}";
if ($result !== null) {
$log_mesg .= "#" . ($result ? 'success' : 'failure');
}
$log_mesg .= "\n";
fwrite($this->messageLogRes, $log_mesg);
if ($this->config->logging_logxml && $data !== null) {
fwrite($this->messageLogRes, $data);
fwrite($this->messageLogRes, "\n");
}
// Tickle the modified file for this server for monitor_activity scheduled task.
global $CFG;
$hostname = gethostname();
$monitoring_dirpath = $CFG->dataroot . "/" . self::PLUGIN_NAME;
if (!file_exists($monitoring_dirpath)) {
$monitoring_dirpath = make_writable_directory($CFG->dataroot . "/" . self::PLUGIN_NAME, false);
}
$last_modified_file = "{$monitoring_dirpath}/.shebang-last-modified-{$hostname}";
touch($last_modified_file);
// If unlock fails (can it?) we got big problems,
// so handle that here and die quickly
if (!$keep_lock) {
if (flock($this->messageLogRes, LOCK_UN) && fclose($this->messageLogRes)) {
$this->messageLogRes = null;
} else {
error_log(get_string('ERR_MESGLOG_CLOSE', self::PLUGIN_NAME));
die();
}
}
} // log_lmb_message
/**
* Write the exception information to a log file in the Moodle data directory
*
* @access private
* @param Exception $exc Exception to log
* @param unknown_type $rc
* @return void
*/
private function log_process_exception(Exception $exc)
{
if (!($fp = fopen($this->processLogPath, 'a'))) {
die(get_string('ERR_PROCLOG_NOOPEN', self::PLUGIN_NAME));
}
fwrite($fp, date(self::DATEFMT_LOG_ENTRY)
. "|Exception Code: " . $exc->getCode() . "\n"
. "In File: " . $exc->getFile() . ":" . $exc->getLine() . "\n"
. "Message: " . $exc->getMessage() . (property_exists($exc, 'error') ? ", " . $exc->error : "") . "\n"
. $exc->getTraceAsString() . "\n");
if (!fclose($fp)) {
die(get_string('ERR_PROCLOG_CLOSE', self::PLUGIN_NAME));
}
} // log_process_exception
/**
* Write the processing information to a log file in the Moodle data directory
*
* @access private
* @param string $entity Entity name
* @param string $id Id value of entity
* @param string $op Operation performed
* @param mixed $rc Success indicator (boolean) or information string
* @return void
*/
private function log_process_message($entity, $id, $op, $rc)
{
if ($this->config->logging_onlyerrors && $rc === true) {
return;
}
if (!($fp = fopen($this->processLogPath, 'a'))) {
die(get_string('ERR_PROCLOG_NOOPEN', self::PLUGIN_NAME));
}
if ($rc === true)
$info = 'success';
elseif ($rc === false)
$info = 'failure';
else
$info = $rc;
fwrite($fp, date(self::DATEFMT_LOG_ENTRY) . "|{$entity}|{$op}|{$id}|$info\n");
if (!fclose($fp)) {
die(get_string('ERR_PROCLOG_CLOSE', self::PLUGIN_NAME));
}
} // log_process_message
/**
* Import the LMB (IMS) messages in the file specified.
*
* @access public
* @param string $infile Path to the input file
* @param progress_trace $progress Name of the callback routine to which to report progress
* @return boolean
*/
public function import_lmb_file(stored_file $stored_file, progress_bar $progress = null)
{
$fh =
$xml_parser = null;
$progress_counter = new stdClass();
// Regardless of PHP version certain modules and classes have
// to be present
if (!function_exists('xml_parser_create') || !class_exists('DOMDocument') || !class_exists('DOMXPath')) {
error_log(get_string('ERR_XMLLIBS_NOTFOUND', self::PLUGIN_NAME));
throw new moodle_exception('ERR_XMLLIBS_NOTFOUND', self::PLUGIN_NAME);
}
if (!$this->config) {
// No configs found
error_log(get_string('ERR_CONFIGS_NOTSET', self::PLUGIN_NAME));
throw new moodle_exception('ERR_CONFIGS_NOTSET', self::PLUGIN_NAME);
}
// Set up process and message log files
try { $this->prepare_logfiles(); }
catch (moodle_exception $exc) {
$exc->link = $this->moodleConfigs->wwwroot . self::PLUGIN_PATH . '/tools.php?task=import';
throw $exc;
}
// Fetch the roles and keep them for the duration
$roles_array = get_all_roles();
foreach ($roles_array as $role) {
$this->roleCache[$role->id] = $role;
}
unset($roles_array);
// Need to know some global configs in case of new Moodle recs
// being inserted
if (!isset($this->moodleConfigs->mnet_localhost_id)) {
include_once("{$this->moodleConfigs->dirroot}/mnet/lib.php");
$env = new mnet_environment();
$env->init(); unset($env);
}
set_time_limit(0);
$progress_counter->block_size = self::INFILE_BLOCK_SIZE;
$progress_counter->blocks_total = ceil($stored_file->get_filesize() / self::INFILE_BLOCK_SIZE);
$progress_counter->blocks_read = 0;
try
{
// No file, no joy
if (false == ($fh = $stored_file->get_content_file_handle())) {
throw new Exception(get_string('ERR_DATAFILE_NOOPEN', self::PLUGIN_NAME));
}
if (!($xml_parser = xml_parser_create())) {
throw new Exception(get_string('ERR_XMLPARSER_CREATE', self::PLUGIN_NAME));
}
// Do the case folding so all string matches and xqueries can
// be consistently uppercase. Skip white space (if possible)
// and don't skip start tags
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, true);
xml_parser_set_option($xml_parser, XML_OPTION_SKIP_TAGSTART, 0);
xml_set_element_handler($xml_parser, array($this, 'parser_start_element'), array($this, 'parser_end_element'));
xml_set_character_data_handler($xml_parser, array($this, 'parser_character_data'));
while (true == ($data = fread($fh, self::INFILE_BLOCK_SIZE))) {
$progress_counter->blocks_read++;
if (!xml_parse($xml_parser, $data, feof($fh))) {
throw new Exception(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)));
}
unset($data);
if ($progress != null) {
$progress->update($progress_counter->blocks_read, $progress_counter->blocks_total, get_string('INF_TOOLS_IMPORT_PROGRESS', self::PLUGIN_NAME, $progress_counter));
}
} // while (true == ($data = fread...
// If any courses inserted in this
// import, fix up the sort order
if ($this->courseInserted) {
$this->courseInserted = false;
fix_course_sortorder();
cache_helper::purge_by_event('changesincourse');
}
// Clean up before leaving
xml_parser_free($xml_parser);
fclose($fh);
return true;
}
catch (Exception $exc)
{
$this->log_process_exception($exc);
if ($fh != null) {
fclose($fh);
}
if ($xml_parser != null) {
xml_parser_free($xml_parser);
}
if ($progress != null) {
$progress->update($progress_counter->blocks_read, $progress_counter->blocks_total, get_string('error'));
}
return false;
}
} // import_lmb_file
/**
* Import an LMB (IMS) message into Moodle
*
* @access public
* @param string $data XML that was *POST*ed by LMB
* @param string $msg_id LMB message id from HTTP headers
* @return boolean
*/
public function import_lmb_message($data = '', $msg_id = '')
{
// Regardless of PHP version certain modules and classes have
// to be present
if (!function_exists('xml_parser_create') || !class_exists('DOMDocument') || !class_exists('DOMXPath')) {
error_log(get_string('ERR_XMLLIBS_NOTFOUND', self::PLUGIN_NAME));
return false;
}
if (!$this->config) {
// No configs found
error_log(get_string('ERR_CONFIGS_NOTSET', self::PLUGIN_NAME));
return false;
}
// Set up process and message log files
try { $this->prepare_logfiles(); }
catch (moodle_exception $exc) {
return false;
}
// Fetch the roles and keep them for the duration
$roles_array = get_all_roles();
foreach ($roles_array as $role) {
$this->roleCache[$role->id] = $role;
}
unset($roles_array);
// Need to know some global configs in case of new Moodle recs
// being inserted
if (!isset($this->moodleConfigs->mnet_localhost_id)) {
include_once("{$this->moodleConfigs->dirroot}/mnet/lib.php");
$env = new mnet_environment();
$env->init(); unset($env);
}
// No payload, no joy
if (empty($data)) {
return false;
}
// Reset this value from any previously received msg
$this->importFileDatetime = '';
$xml_parser = null;
try
{
$this->log_lmb_message($msg_id, $data, true, null);
if (!($xml_parser = xml_parser_create())) {
throw new Exception(get_string('ERR_XMLPARSER_CREATE', self::PLUGIN_NAME));
}
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, false);
xml_parser_set_option($xml_parser, XML_OPTION_SKIP_TAGSTART, 0);
xml_set_element_handler($xml_parser, array($this, 'parser_start_element'), array($this, 'parser_end_element'));
xml_set_character_data_handler($xml_parser, array($this, 'parser_character_data'));
if (!xml_parse($xml_parser, $data, true)) {
throw new Exception(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)));
}
// If any courses inserted in this
// message, fix up the sort order
if ($this->courseInserted) {
$this->courseInserted = false;
fix_course_sortorder();
// The call to cache_helper::purge_by_event() is called after a call
// to fix_course_sortorder(), but this would risk the cache getting
// purged too frequently as messages are sent, so will leave commented
//cache_helper::purge_by_event('changesincourse');
}
$this->log_lmb_message($msg_id, null, false, $this->lastRetCode);
xml_parser_free($xml_parser);
if (!$this->lastRetCode) {
$this->notify_message_error($msg_id);
}
return $this->lastRetCode;
}
catch (Exception $exc)
{
$this->log_process_exception($exc);
if ($this->messageLogRes != null) {
$this->log_lmb_message($msg_id, 'failure', false);
}
if ($xml_parser != null) {
xml_parser_free($xml_parser);
}
$this->notify_message_error($msg_id);
return false;
}
} // import_lmb_message
/**
* Callback routine to handle an opening element tag
*
* @access private
* @param resource $parser The xml resource type returned from xml_create_parser()
* @param string $name Element name
* @param array $attrs Array of attributes (strings) for this element
* @return void
*/
private function parser_start_element($parser, $name, $attrs)
{
/* We expect to see, in order, the ENTERPRISE (root) element, then
* PROPERTIES (first child), and so on. We want to start buffering
* when we encounter a GROUP, PERSON, or MEMBERSHIP opening tag.
* All we do is continue to buffer up the xml that makes up one of
* the desired elements, and when the close tag is encountered, a
* call to the corresponding import_[name]_element routine handles
* the import.
*/
switch ($name) {
case self::LMBTAG_PROPERTIES:
case self::LMBTAG_GROUP:
case self::LMBTAG_PERSON:
case self::LMBTAG_MEMBERSHIP:
$this->parseDataBuffer = '';
$this->buffering = true;
break;
//default: Don't care about this one
}
// Not buffering, no more to do
if (!$this->buffering) {
return;
}
$attr_list = '';
foreach ($attrs as $key => $val) {
// Revert any '&' back to '&' so the
// text can be put into an XMLDocument
$attr_list .= " {$key}=\"" . preg_replace(array('/</', '/>/', '/&/'), array('<', '>', '&'), $val) . "\"";
}
$this->parseDataBuffer .= "<{$name}{$attr_list}>";
} // parser_start_element
/**
* Callback routine to handle a closing element tag
*
* @access private
* @param resource $parser The xml resource type returned from xml_create_parser()
* @param string $name Element name
* @return void
*/
private function parser_end_element($parser, $name)
{
/* We expect to see, in order, the ENTERPRISE (root) element, then
* PROPERTIES (first child), and so on. We want to start buffering
* when we encounter a GROUP, PERSON, or MEMBERSHIP opening tag.
* All we do is continue to buffer up the xml that makes up one of
* the desired elements, and when the close tag is encountered, a
* call to the corresponding import_[name]_element routine handles
* the import.
*/
// Not buffering, don't care
if (!$this->buffering) {
return;
}
// Stick it on the end of the buffer
$this->parseDataBuffer .= "</{$name}>";
// See if it's one for which an action takes place
switch($name)
{
case self::LMBTAG_PROPERTIES:
case self::LMBTAG_GROUP:
case self::LMBTAG_PERSON:
case self::LMBTAG_MEMBERSHIP:
$doc = new DOMDocument();
try
{
$doc->loadXML($this->parseDataBuffer);
$method = "import_" . strtolower($name) . "_element";
$this->lastRetCode = $this->$method($doc);
}
catch (Exception $exc)
{
$this->log_process_exception($exc);
$this->log_process_message($name, "", "", $this->parseDataBuffer);
$this->lastRetCode = false;
}
unset($doc);
$this->buffering = false;
$this->parseDataBuffer = '';
break;
//default: Nothing more to do otherwise
}
} // parser_end_element
/**
* Callback routine to handle the character data collection
* for text that falls between an opening tag, and either its
* corresponding closing tag, or the opening tag of the first
* child element (usually whitespace chars in the latter case)
*
* @access private
* @param resource $parser The xml resource type returned from xml_create_parser()
* @param string $data Character data
* @return void
*/
private function parser_character_data($parser, $data)
{
if ($this->buffering) {
// Want to strip out the extra \n and space chars that
// appear between a closing element tag and the next
// element's opening tag. Also, because the xml_parser
// is translating '&' into '&', we need to revert
// all of them before putting into an XMLDocument
$this->parseDataBuffer .= preg_replace(array('/\A\s+\z/', '/</', '/>/', '/&/'), array('', '<', '>', '&'), $data);
}
} // parser_character_data
/**
* Fetches the datetime sub-element value and assigns that to the $importFileDatetime member var
*
* @access private
* @param DOMDocument $doc The XML document containing the <properties> element
* @return boolean Success or failure
*/
private function import_properties_element(DOMDocument $doc)
{
$xpath = new DOMXPath($doc);
$this->importFileDatetime = strtotime($xpath->evaluate("string(/PROPERTIES/DATETIME)"));
return true;
} // import_properties_element
/**
* Import a <group> element
*
* @access private
* @param DOMDocument $doc The XML document containing the <group> element
* @return boolean Success or failure
*/
private function import_group_element(DOMDocument $doc)
{
/* Still need to determine the type of <group> encountered,
* whether a term, course, course section, etc., so look
* at the first <grouptype>/<typevalue> that has a level
* value of 1.
*/
$rc = false;
$xpath = new DOMXPath($doc);
$type_value = strtoupper($xpath->evaluate("string(/GROUP/GROUPTYPE[TYPEVALUE[@LEVEL = \"1\"]][1]/TYPEVALUE)"));
switch($type_value)
{
case self::LMBTAG_TYPEVALUE_TERM:
case self::LMBTAG_TYPEVALUE_SECTION:
$method = "import_group_" . strtolower($type_value);
$rc = $this->$method($doc);
break;
/*
We do not care too much about the cross-listed section group
element because it does not provide any useful information,
other than that somewhere later on we will receive membership
elements that specify which course sections belong--and that
is where we can get useful information.
case self::LMBTAG_TYPEVALUE_CROSSLIST:
Not receiving these message elements in our implementation of
Banner...
case self::LMBTAG_TYPEVALUE_COLLEGE:
case self::LMBTAG_TYPEVALUE_DEPT: