eef9380fcfa4323aac2f15c13e93b5ec653b557d
[moodle.git] / enrol / imsenterprise / lib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * IMS Enterprise file enrolment plugin.
19  *
20  * This plugin lets the user specify an IMS Enterprise file to be processed.
21  * The IMS Enterprise file is mainly parsed on a regular cron,
22  * but can also be imported via the UI (Admin Settings).
23  * @package    enrol
24  * @subpackage imsenterprise
25  * @copyright  2010 Eugene Venter
26  * @author     Eugene Venter - based on code by Dan Stowell
27  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28  */
30 defined('MOODLE_INTERNAL') || die();
32 /*
34 Note for programmers:
36 This class uses regular expressions to mine the data file. The main reason is
37 that XML handling changes from PHP 4 to PHP 5, so this should work on both.
39 One drawback is that the pattern-matching doesn't (currently) handle XML
40 namespaces - it only copes with a <group> tag if it says <group>, and not
41 (for example) <ims:group>.
43 This should also be able to handle VERY LARGE FILES - so the entire IMS file is
44 NOT loaded into memory at once. It's handled line-by-line, 'forgetting' tags as
45 soon as they are processed.
47 N.B. The "sourcedid" ID code is translated to Moodle's "idnumber" field, both
48 for users and for courses.
50 */
52 require_once($CFG->dirroot.'/group/lib.php');
55 class enrol_imsenterprise_plugin extends enrol_plugin {
57 var $log;
60 /**
61 * Read in an IMS Enterprise file.
62 * Originally designed to handle v1.1 files but should be able to handle
63 * earlier types as well, I believe.
64 *
65 */
66 function cron() {
67     global $CFG;
69     // Get configs
70     $imsfilelocation    = $this->get_config('imsfilelocation');
71     $logtolocation      = $this->get_config('logtolocation');
72     $mailadmins         = $this->get_config('mailadmins');
73     $prev_time          = $this->get_config('prev_time');
74     $prev_md5           = $this->get_config('prev_md5');
75     $prev_path          = $this->get_config('prev_path');
77     if (empty($imsfilelocation)) {
78         // $filename = "$CFG->dirroot/enrol/imsenterprise/example.xml";  // Default location
79         $filename = "$CFG->dataroot/1/imsenterprise-enrol.xml";  // Default location
80     } else {
81         $filename = $imsfilelocation;
82     }
84     $this->logfp = false; // File pointer for writing log data to
85     if(!empty($logtolocation)) {
86         $this->logfp = fopen($logtolocation, 'a');
87     }
89     if ( file_exists($filename) ) {
90         @set_time_limit(0);
91         $starttime = time();
93         $this->log_line('----------------------------------------------------------------------');
94         $this->log_line("IMS Enterprise enrol cron process launched at " . userdate(time()));
95         $this->log_line('Found file '.$filename);
96         $this->xmlcache = '';
98         // Make sure we understand how to map the IMS-E roles to Moodle roles
99         $this->load_role_mappings();
100         // Make sure we understand how to map the IMS-E course names to Moodle course names
101         $this->load_course_mappings();
103         $md5 = md5_file($filename); // NB We'll write this value back to the database at the end of the cron
104         $filemtime = filemtime($filename);
106         // Decide if we want to process the file (based on filepath, modification time, and MD5 hash)
107         // This is so we avoid wasting the server's efforts processing a file unnecessarily
108         if(empty($prev_path)  || ($filename != $prev_path)) {
109             $fileisnew = true;
110         } elseif(isset($prev_time) && ($filemtime <= $prev_time)) {
111             $fileisnew = false;
112             $this->log_line('File modification time is not more recent than last update - skipping processing.');
113         } elseif(isset($prev_md5) && ($md5 == $prev_md5)) {
114             $fileisnew = false;
115             $this->log_line('File MD5 hash is same as on last update - skipping processing.');
116         } else {
117             $fileisnew = true; // Let's process it!
118         }
120         if($fileisnew) {
122             $listoftags = array('group', 'person', 'member', 'membership', 'comments', 'properties'); // The list of tags which should trigger action (even if only cache trimming)
123             $this->continueprocessing = true; // The <properties> tag is allowed to halt processing if we're demanding a matching target
125             // FIRST PASS: Run through the file and process the group/person entries
126             if (($fh = fopen($filename, "r")) != false) {
128                 $line = 0;
129                 while ((!feof($fh)) && $this->continueprocessing) {
131                     $line++;
132                     $curline = fgets($fh);
133                     $this->xmlcache .= $curline; // Add a line onto the XML cache
135                     while (true) {
136                       // If we've got a full tag (i.e. the most recent line has closed the tag) then process-it-and-forget-it.
137                       // Must always make sure to remove tags from cache so they don't clog up our memory
138                       if($tagcontents = $this->full_tag_found_in_cache('group', $curline)) {
139                           $this->process_group_tag($tagcontents);
140                           $this->remove_tag_from_cache('group');
141                       } elseif($tagcontents = $this->full_tag_found_in_cache('person', $curline)) {
142                           $this->process_person_tag($tagcontents);
143                           $this->remove_tag_from_cache('person');
144                       } elseif($tagcontents = $this->full_tag_found_in_cache('membership', $curline)) {
145                           $this->process_membership_tag($tagcontents);
146                           $this->remove_tag_from_cache('membership');
147                       } elseif($tagcontents = $this->full_tag_found_in_cache('comments', $curline)) {
148                           $this->remove_tag_from_cache('comments');
149                       } elseif($tagcontents = $this->full_tag_found_in_cache('properties', $curline)) {
150                           $this->process_properties_tag($tagcontents);
151                           $this->remove_tag_from_cache('properties');
152                       } else {
153                           break;
154                       }
155                     } // End of while-tags-are-detected
156                 } // end of while loop
157                 fclose($fh);
158                 fix_course_sortorder();
159             } // end of if(file_open) for first pass
161             /*
164             SECOND PASS REMOVED
165             Since the IMS specification v1.1 insists that "memberships" should come last,
166             and since vendors seem to have done this anyway (even with 1.0),
167             we can sensibly perform the import in one fell swoop.
170             // SECOND PASS: Now go through the file and process the membership entries
171             $this->xmlcache = '';
172             if (($fh = fopen($filename, "r")) != false) {
173                 $line = 0;
174                 while ((!feof($fh)) && $this->continueprocessing) {
175                     $line++;
176                     $curline = fgets($fh);
177                     $this->xmlcache .= $curline; // Add a line onto the XML cache
179                     while(true){
180                   // Must always make sure to remove tags from cache so they don't clog up our memory
181                   if($tagcontents = $this->full_tag_found_in_cache('group', $curline)){
182                           $this->remove_tag_from_cache('group');
183                       }elseif($tagcontents = $this->full_tag_found_in_cache('person', $curline)){
184                           $this->remove_tag_from_cache('person');
185                       }elseif($tagcontents = $this->full_tag_found_in_cache('membership', $curline)){
186                           $this->process_membership_tag($tagcontents);
187                           $this->remove_tag_from_cache('membership');
188                       }elseif($tagcontents = $this->full_tag_found_in_cache('comments', $curline)){
189                           $this->remove_tag_from_cache('comments');
190                       }elseif($tagcontents = $this->full_tag_found_in_cache('properties', $curline)){
191                           $this->remove_tag_from_cache('properties');
192                       }else{
193                     break;
194                   }
195                 }
196                 } // end of while loop
197                 fclose($fh);
198             } // end of if(file_open) for second pass
201            */
203             $timeelapsed = time() - $starttime;
204             $this->log_line('Process has completed. Time taken: '.$timeelapsed.' seconds.');
207         } // END of "if file is new"
210         // These variables are stored so we can compare them against the IMS file, next time round.
211         $this->set_config('prev_time', $filemtime);
212         $this->set_config('prev_md5',  $md5);
213         $this->set_config('prev_path', $filename);
217     }else{ // end of if(file_exists)
218         $this->log_line('File not found: '.$filename);
219     }
221     if (!empty($mailadmins)) {
222         $msg = "An IMS enrolment has been carried out within Moodle.\nTime taken: $timeelapsed seconds.\n\n";
223         if(!empty($logtolocation)){
224             if($this->logfp){
225                 $msg .= "Log data has been written to:\n";
226                 $msg .= "$logtolocation\n";
227                 $msg .= "(Log file size: ".ceil(filesize($logtolocation)/1024)."Kb)\n\n";
228             }else{
229                 $msg .= "The log file appears not to have been successfully written.\nCheck that the file is writeable by the server:\n";
230                 $msg .= "$logtolocation\n\n";
231             }
232         }else{
233             $msg .= "Logging is currently not active.";
234         }
236         $eventdata = new stdClass();
237         $eventdata->modulename        = 'moodle';
238         $eventdata->component         = 'imsenterprise';
239         $eventdata->name              = 'imsenterprise_enrolment';
240         $eventdata->userfrom          = get_admin();
241         $eventdata->userto            = get_admin();
242         $eventdata->subject           = "Moodle IMS Enterprise enrolment notification";
243         $eventdata->fullmessage       = $msg;
244         $eventdata->fullmessageformat = FORMAT_PLAIN;
245         $eventdata->fullmessagehtml   = '';
246         $eventdata->smallmessage      = '';
247         message_send($eventdata);
249         $this->log_line('Notification email sent to administrator.');
251     }
253     if($this->logfp){
254       fclose($this->logfp);
255     }
258 } // end of cron() function
260 /**
261 * Check if a complete tag is found in the cached data, which usually happens
262 * when the end of the tag has only just been loaded into the cache.
263 * Returns either false, or the contents of the tag (including start and end).
264 * @param string $tagname Name of tag to look for
265 * @param string $latestline The very last line in the cache (used for speeding up the match)
266 */
267 function full_tag_found_in_cache($tagname, $latestline){ // Return entire element if found. Otherwise return false.
268     if(strpos(strtolower($latestline), '</'.strtolower($tagname).'>')===false){
269         return false;
270     }elseif(preg_match('{(<'.$tagname.'\b.*?>.*?</'.$tagname.'>)}is', $this->xmlcache, $matches)){
271         return $matches[1];
272     }else return false;
275 /**
276 * Remove complete tag from the cached data (including all its contents) - so
277 * that the cache doesn't grow to unmanageable size
278 * @param string $tagname Name of tag to look for
279 */
280 function remove_tag_from_cache($tagname){ // Trim the cache so we're not in danger of running out of memory.
281     ///echo "<p>remove_tag_from_cache: $tagname</p>";  flush();  ob_flush();
282     //  echo "<p>remove_tag_from_cache:<br />".htmlspecialchars($this->xmlcache);
283     $this->xmlcache = trim(preg_replace('{<'.$tagname.'\b.*?>.*?</'.$tagname.'>}is', '', $this->xmlcache, 1)); // "1" so that we replace only the FIRST instance
284     //  echo "<br />".htmlspecialchars($this->xmlcache)."</p>";
287 /**
288 * Very simple convenience function to return the "recstatus" found in person/group/role tags.
289 * 1=Add, 2=Update, 3=Delete, as specified by IMS, and we also use 0 to indicate "unspecified".
290 * @param string $tagdata the tag XML data
291 * @param string $tagname the name of the tag we're interested in
292 */
293 function get_recstatus($tagdata, $tagname){
294     if(preg_match('{<'.$tagname.'\b[^>]*recstatus\s*=\s*["\'](\d)["\']}is', $tagdata, $matches)){
295         // echo "<p>get_recstatus($tagname) found status of $matches[1]</p>";
296         return intval($matches[1]);
297     }else{
298         // echo "<p>get_recstatus($tagname) found nothing</p>";
299         return 0; // Unspecified
300     }
303 /**
304 * Process the group tag. This defines a Moodle course.
305 * @param string $tagconents The raw contents of the XML element
306 */
307 function process_group_tag($tagcontents) {
308     global $DB;
310     // Get configs
311     $truncatecoursecodes    = $this->get_config('truncatecoursecodes');
312     $createnewcourses       = $this->get_config('createnewcourses');
313     $createnewcategories    = $this->get_config('createnewcategories');
315     // Process tag contents
316     $group = new stdClass();
317     if (preg_match('{<sourcedid>.*?<id>(.+?)</id>.*?</sourcedid>}is', $tagcontents, $matches)) {
318         $group->coursecode = trim($matches[1]);
319     }
321     if (preg_match('{<description>.*?<long>(.*?)</long>.*?</description>}is', $tagcontents, $matches)) {
322         $group->longname = trim($matches[1]);
323     }
324     if (preg_match('{<description>.*?<short>(.*?)</short>.*?</description>}is', $tagcontents, $matches)) {
325         $group->shortname = trim($matches[1]);
326     }
327     if (preg_match('{<description>.*?<full>(.*?)</full>.*?</description>}is', $tagcontents, $matches)) {
328         $group->full = trim($matches[1]);
329     }
331     if (preg_match('{<org>.*?<orgunit>(.*?)</orgunit>.*?</org>}is', $tagcontents, $matches)) {
332         $group->category = trim($matches[1]);
333     }
335     $recstatus = ($this->get_recstatus($tagcontents, 'group'));
336     //echo "<p>get_recstatus for this group returned $recstatus</p>";
338     if (!(strlen($group->coursecode)>0)) {
339         $this->log_line('Error at line '.$line.': Unable to find course code in \'group\' element.');
340     } else {
341         // First, truncate the course code if desired
342         if (intval($truncatecoursecodes)>0) {
343             $group->coursecode = ($truncatecoursecodes > 0)
344                      ? substr($group->coursecode, 0, intval($truncatecoursecodes))
345                      : $group->coursecode;
346         }
348         /* -----------Course aliasing is DEACTIVATED until a more general method is in place---------------
350        // Second, look in the course alias table to see if the code should be translated to something else
351         if($aliases = $DB->get_field('enrol_coursealias', 'toids', array('fromid'=>$group->coursecode))){
352             $this->log_line("Found alias of course code: Translated $group->coursecode to $aliases");
353             // Alias is allowed to be a comma-separated list, so let's split it
354             $group->coursecode = explode(',', $aliases);
355         }
356        */
358         // For compatibility with the (currently inactive) course aliasing, we need this to be an array
359         $group->coursecode = array($group->coursecode);
361         // Third, check if the course(s) exist
362         foreach ($group->coursecode as $coursecode) {
363             $coursecode = trim($coursecode);
364             if (!$DB->get_field('course', 'id', array('idnumber'=>$coursecode))) {
365                 if (!$createnewcourses) {
366                     $this->log_line("Course $coursecode not found in Moodle's course idnumbers.");
367                 } else {
368                     // Set shortname to description or description to shortname if one is set but not the other.
369                     $nodescription = !isset($group->longname);
370                     $noshortname = !isset($group->shortname);
371                     if ( $nodescription && $noshortname) {
372                         // If neither short nor long description are set let if fail
373                         $this->log_line("Neither long nor short name are set for $coursecode");
374                     } else if ($nodescription) {
375                         // If short and ID exist, then give the long short's value, then give short the ID's value
376                         $group->longname = $group->shortname;
377                         $group->shortname = $coursecode;
378                     } else if ($noshortname) {
379                         // If long and ID exist, then map long to long, then give short the ID's value.
380                         $group->shortname = $coursecode;
381                     }
382                     $group->full = format_text($group->full, FORMAT_HTML);
384                     // Create the (hidden) course(s) if not found
385                     $courseconfig = get_config('moodlecourse'); // Load Moodle Course shell defaults
386                     $course = new stdClass();
387                     foreach ($this->coursemappings as $coursename => $imsname) {
388                         $course->$coursename = $group->$imsname;
389                     }
390                     $course->idnumber = $coursecode;
391                     $course->format = $courseconfig->format;
392                     $course->visible = $courseconfig->visible;
393                     $course->newsitems = $courseconfig->newsitems;
394                     $course->showgrades = $courseconfig->showgrades;
395                     $course->showreports = $courseconfig->showreports;
396                     $course->maxbytes = $courseconfig->maxbytes;
397                     $course->groupmode = $courseconfig->groupmode;
398                     $course->groupmodeforce = $courseconfig->groupmodeforce;
399                     $course->enablecompletion = $courseconfig->enablecompletion;
400                     $course->completionstartonenrol = $courseconfig->completionstartonenrol;
401                     // Insert default names for teachers/students, from the current language
403                     // Handle course categorisation (taken from the group.org.orgunit field if present)
404                     if (strlen($group->category)>0) {
405                         // If the category is defined and exists in Moodle, we want to store it in that one
406                         if ($catid = $DB->get_field('course_categories', 'id', array('name'=>$group->category))) {
407                             $course->category = $catid;
408                         } else if ($createnewcategories) {
409                             // Else if we're allowed to create new categories, let's create this one
410                             $newcat = new stdClass();
411                             $newcat->name = $group->category;
412                             $newcat->visible = 0;
413                             $catid = $DB->insert_record('course_categories', $newcat);
414                             $course->category = $catid;
415                             $this->log_line("Created new (hidden) category, #$catid: $newcat->name");
416                         } else {
417                             // If not found and not allowed to create, stick with default
418                             $this->log_line('Category '.$group->category.' not found in Moodle database, so using default category instead.');
419                             $course->category = 1;
420                         }
421                     } else {
422                         $course->category = 1;
423                     }
424                     $course->timecreated = time();
425                     $course->startdate = time();
426                     // Choose a sort order that puts us at the start of the list!
427                     $course->sortorder = 0;
429                     $courseid = $DB->insert_record('course', $course);
431                     // Setup default enrolment plugins
432                     $course->id = $courseid;
433                     enrol_course_updated(true, $course, null);
435                     // Setup the blocks
436                     $course = $DB->get_record('course', array('id' => $courseid));
437                     blocks_add_default_course_blocks($course);
439                     // Create default 0-section
440                     course_create_sections_if_missing($course, 0);
442                     add_to_log(SITEID, "course", "new", "view.php?id=$course->id", "$course->fullname (ID $course->id)");
444                     $this->log_line("Created course $coursecode in Moodle (Moodle ID is $course->id)");
445                 }
446             } else if ($recstatus==3 && ($courseid = $DB->get_field('course', 'id', array('idnumber'=>$coursecode)))) {
447                 // If course does exist, but recstatus==3 (delete), then set the course as hidden
448                 $DB->set_field('course', 'visible', '0', array('id'=>$courseid));
449             }
450         } // End of foreach(coursecode)
451     }
452 } // End process_group_tag()
454 /**
455 * Process the person tag. This defines a Moodle user.
456 * @param string $tagconents The raw contents of the XML element
457 */
458 function process_person_tag($tagcontents){
459     global $CFG, $DB;
461     // Get plugin configs
462     $imssourcedidfallback   = $this->get_config('imssourcedidfallback');
463     $fixcaseusernames       = $this->get_config('fixcaseusernames');
464     $fixcasepersonalnames   = $this->get_config('fixcasepersonalnames');
465     $imsdeleteusers         = $this->get_config('imsdeleteusers');
466     $createnewusers         = $this->get_config('createnewusers');
468     $person = new stdClass();
469     if(preg_match('{<sourcedid>.*?<id>(.+?)</id>.*?</sourcedid>}is', $tagcontents, $matches)){
470         $person->idnumber = trim($matches[1]);
471     }
472     if(preg_match('{<name>.*?<n>.*?<given>(.+?)</given>.*?</n>.*?</name>}is', $tagcontents, $matches)){
473         $person->firstname = trim($matches[1]);
474     }
475     if(preg_match('{<name>.*?<n>.*?<family>(.+?)</family>.*?</n>.*?</name>}is', $tagcontents, $matches)){
476         $person->lastname = trim($matches[1]);
477     }
478     if(preg_match('{<userid>(.*?)</userid>}is', $tagcontents, $matches)){
479         $person->username = trim($matches[1]);
480     }
481     if($imssourcedidfallback && trim($person->username)==''){
482       // This is the point where we can fall back to useing the "sourcedid" if "userid" is not supplied
483       // NB We don't use an "elseif" because the tag may be supplied-but-empty
484         $person->username = $person->idnumber;
485     }
486     if(preg_match('{<email>(.*?)</email>}is', $tagcontents, $matches)){
487         $person->email = trim($matches[1]);
488     }
489     if(preg_match('{<url>(.*?)</url>}is', $tagcontents, $matches)){
490         $person->url = trim($matches[1]);
491     }
492     if(preg_match('{<adr>.*?<locality>(.+?)</locality>.*?</adr>}is', $tagcontents, $matches)){
493         $person->city = trim($matches[1]);
494     }
495     if(preg_match('{<adr>.*?<country>(.+?)</country>.*?</adr>}is', $tagcontents, $matches)){
496         $person->country = trim($matches[1]);
497     }
499     // Fix case of some of the fields if required
500     if($fixcaseusernames && isset($person->username)){
501         $person->username = strtolower($person->username);
502     }
503     if($fixcasepersonalnames){
504         if(isset($person->firstname)){
505             $person->firstname = ucwords(strtolower($person->firstname));
506         }
507         if(isset($person->lastname)){
508             $person->lastname = ucwords(strtolower($person->lastname));
509         }
510     }
512     $recstatus = ($this->get_recstatus($tagcontents, 'person'));
515     // Now if the recstatus is 3, we should delete the user if-and-only-if the setting for delete users is turned on
516     // In the "users" table we can do this by setting deleted=1
517     if($recstatus==3){
519         if($imsdeleteusers){ // If we're allowed to delete user records
520             // Make sure their "deleted" field is set to one
521             $DB->set_field('user', 'deleted', 1, array('username'=>$person->username));
522             $this->log_line("Marked user record for user '$person->username' (ID number $person->idnumber) as deleted.");
523         }else{
524             $this->log_line("Ignoring deletion request for user '$person->username' (ID number $person->idnumber).");
525         }
527     }else{ // Add or update record
530         // If the user exists (matching sourcedid) then we don't need to do anything.
531         if(!$DB->get_field('user', 'id', array('idnumber'=>$person->idnumber)) && $createnewusers){
532             // If they don't exist and haven't a defined username, we log this as a potential problem.
533             if((!isset($person->username)) || (strlen($person->username)==0)){
534                 $this->log_line("Cannot create new user for ID # $person->idnumber - no username listed in IMS data for this person.");
535             } else if ($DB->get_field('user', 'id', array('username'=>$person->username))){
536                 // If their idnumber is not registered but their user ID is, then add their idnumber to their record
537                 $DB->set_field('user', 'idnumber', $person->idnumber, array('username'=>$person->username));
538             } else {
540             // If they don't exist and they have a defined username, and $createnewusers == true, we create them.
541             $person->lang = 'manual'; //TODO: this needs more work due tu multiauth changes
542             $person->auth = $CFG->auth;
543             $person->confirmed = 1;
544             $person->timemodified = time();
545             $person->mnethostid = $CFG->mnet_localhost_id;
546             $id = $DB->insert_record('user', $person);
547     /*
548     Photo processing is deactivated until we hear from Moodle dev forum about modification to gdlib.
550                                  //Antoni Mas. 07/12/2005. If a photo URL is specified then we might want to load
551                                  // it into the user's profile. Beware that this may cause a heavy overhead on the server.
552                                  if($CFG->enrol_processphoto){
553                                    if(preg_match('{<photo>.*?<extref>(.*?)</extref>.*?</photo>}is', $tagcontents, $matches)){
554                                      $person->urlphoto = trim($matches[1]);
555                                    }
556                                    //Habilitam el flag que ens indica que el personatge t foto prpia.
557                                    $person->picture = 1;
558                                    //Llibreria creada per nosaltres mateixos.
559                                    require_once($CFG->dirroot.'/lib/gdlib.php');
560                                    if ($usernew->picture = save_profile_image($id, $person->urlphoto,'user')) { TODO: use process_new_icon() instead
561                                      $DB->set_field('user', 'picture', $usernew->picture, array('id'=>$id));  /// Note picture in DB
562                                    }
563                                  }
564     */
565                 $this->log_line("Created user record for user '$person->username' (ID number $person->idnumber).");
566             }
567         } elseif ($createnewusers) {
568             $this->log_line("User record already exists for user '$person->username' (ID number $person->idnumber).");
570             // Make sure their "deleted" field is set to zero.
571             $DB->set_field('user', 'deleted', 0, array('idnumber'=>$person->idnumber));
572         }else{
573             $this->log_line("No user record found for '$person->username' (ID number $person->idnumber).");
574         }
576     } // End of are-we-deleting-or-adding
578 } // End process_person_tag()
580 /**
581 * Process the membership tag. This defines whether the specified Moodle users
582 * should be added/removed as teachers/students.
583 * @param string $tagconents The raw contents of the XML element
584 */
585 function process_membership_tag($tagcontents){
586     global $DB;
588     // Get plugin configs
589     $truncatecoursecodes = $this->get_config('truncatecoursecodes');
590     $imscapitafix = $this->get_config('imscapitafix');
592     $memberstally = 0;
593     $membersuntally = 0;
595     // In order to reduce the number of db queries required, group name/id associations are cached in this array:
596     $groupids = array();
598     $ship = new stdClass();
600     if(preg_match('{<sourcedid>.*?<id>(.+?)</id>.*?</sourcedid>}is', $tagcontents, $matches)){
601         $ship->coursecode = ($truncatecoursecodes > 0)
602                                  ? substr(trim($matches[1]), 0, intval($truncatecoursecodes))
603                                  : trim($matches[1]);
604         $ship->courseid = $DB->get_field('course', 'id', array('idnumber'=>$ship->coursecode));
605     }
606     if($ship->courseid && preg_match_all('{<member>(.*?)</member>}is', $tagcontents, $membermatches, PREG_SET_ORDER)){
607         $courseobj = new stdClass();
608         $courseobj->id = $ship->courseid;
610         foreach($membermatches as $mmatch){
611             $member = new stdClass();
612             $memberstoreobj = new stdClass();
613             if(preg_match('{<sourcedid>.*?<id>(.+?)</id>.*?</sourcedid>}is', $mmatch[1], $matches)){
614                 $member->idnumber = trim($matches[1]);
615             }
616             if(preg_match('{<role\s+roletype=["\'](.+?)["\'].*?>}is', $mmatch[1], $matches)){
617                 $member->roletype = trim($matches[1]); // 01 means Student, 02 means Instructor, 3 means ContentDeveloper, and there are more besides
618             } elseif($imscapitafix && preg_match('{<roletype>(.+?)</roletype>}is', $mmatch[1], $matches)){
619                 // The XML that comes out of Capita Student Records seems to contain a misinterpretation of the IMS specification!
620                 $member->roletype = trim($matches[1]); // 01 means Student, 02 means Instructor, 3 means ContentDeveloper, and there are more besides
621             }
622             if(preg_match('{<role\b.*?<status>(.+?)</status>.*?</role>}is', $mmatch[1], $matches)){
623                 $member->status = trim($matches[1]); // 1 means active, 0 means inactive - treat this as enrol vs unenrol
624             }
626             $recstatus = ($this->get_recstatus($mmatch[1], 'role'));
627             if($recstatus==3){
628               $member->status = 0; // See above - recstatus of 3 (==delete) is treated the same as status of 0
629               //echo "<p>process_membership_tag: unenrolling member due to recstatus of 3</p>";
630             }
632             $timeframe = new stdClass();
633             $timeframe->begin = 0;
634             $timeframe->end = 0;
635             if(preg_match('{<role\b.*?<timeframe>(.+?)</timeframe>.*?</role>}is', $mmatch[1], $matches)){
636                 $timeframe = $this->decode_timeframe($matches[1]);
637             }
638             if(preg_match('{<role\b.*?<extension>.*?<cohort>(.+?)</cohort>.*?</extension>.*?</role>}is', $mmatch[1], $matches)){
639                 $member->groupname = trim($matches[1]);
640                 // The actual processing (ensuring a group record exists, etc) occurs below, in the enrol-a-student clause
641             }
643             $rolecontext = context_course::instance($ship->courseid);
644             $rolecontext = $rolecontext->id; // All we really want is the ID
645 //$this->log_line("Context instance for course $ship->courseid is...");
646 //print_r($rolecontext);
648             // Add or remove this student or teacher to the course...
649             $memberstoreobj->userid = $DB->get_field('user', 'id', array('idnumber'=>$member->idnumber));
650             $memberstoreobj->enrol = 'imsenterprise';
651             $memberstoreobj->course = $ship->courseid;
652             $memberstoreobj->time = time();
653             $memberstoreobj->timemodified = time();
654             if($memberstoreobj->userid){
656                 // Decide the "real" role (i.e. the Moodle role) that this user should be assigned to.
657                 // Zero means this roletype is supposed to be skipped.
658                 $moodleroleid = $this->rolemappings[$member->roletype];
659                 if(!$moodleroleid) {
660                     $this->log_line("SKIPPING role $member->roletype for $memberstoreobj->userid ($member->idnumber) in course $memberstoreobj->course");
661                     continue;
662                 }
664                 if(intval($member->status) == 1) {
665                     // Enrol the member
667                     $einstance = $DB->get_record('enrol',
668                                     array('courseid' => $courseobj->id, 'enrol' => $memberstoreobj->enrol));
669                     if (empty($einstance)) {
670                         // Only add an enrol instance to the course if non-existent
671                         $enrolid = $this->add_instance($courseobj);
672                         $einstance = $DB->get_record('enrol', array('id' => $enrolid));
673                     }
675                     $this->enrol_user($einstance, $memberstoreobj->userid, $moodleroleid, $timeframe->begin, $timeframe->end);
677                     $this->log_line("Enrolled user #$memberstoreobj->userid ($member->idnumber) to role $member->roletype in course $memberstoreobj->course");
678                     $memberstally++;
680                     // At this point we can also ensure the group membership is recorded if present
681                     if(isset($member->groupname)){
682                         // Create the group if it doesn't exist - either way, make sure we know the group ID
683                         if(isset($groupids[$member->groupname])) {
684                             $member->groupid = $groupids[$member->groupname]; // Recall the group ID from cache if available
685                         } else {
686                             if($groupid = $DB->get_field('groups', 'id', array('courseid'=>$ship->courseid, 'name'=>$member->groupname))){
687                                 $member->groupid = $groupid;
688                                 $groupids[$member->groupname] = $groupid; // Store ID in cache
689                             } else {
690                                 // Attempt to create the group
691                                 $group = new stdClass();
692                                 $group->name = $member->groupname;
693                                 $group->courseid = $ship->courseid;
694                                 $group->timecreated = time();
695                                 $group->timemodified = time();
696                                 $groupid = $DB->insert_record('groups', $group);
697                                 $this->log_line('Added a new group for this course: '.$group->name);
698                                 $groupids[$member->groupname] = $groupid; // Store ID in cache
699                                 $member->groupid = $groupid;
700                             }
701                         }
702                         // Add the user-to-group association if it doesn't already exist
703                         if($member->groupid) {
704                             groups_add_member($member->groupid, $memberstoreobj->userid,
705                                     'enrol_imsenterprise', $einstance->id);
706                         }
707                     } // End of group-enrolment (from member.role.extension.cohort tag)
709                 } elseif ($this->get_config('imsunenrol')) {
710                     // Unenrol member
712                     $einstances = $DB->get_records('enrol',
713                                     array('enrol' => $memberstoreobj->enrol, 'courseid' => $courseobj->id));
714                     foreach ($einstances as $einstance) {
715                         // Unenrol the user from all imsenterprise enrolment instances
716                         $this->unenrol_user($einstance, $memberstoreobj->userid);
717                     }
719                     $membersuntally++;
720                     $this->log_line("Unenrolled $member->idnumber from role $moodleroleid in course");
721                 }
723             }
724         }
725         $this->log_line("Added $memberstally users to course $ship->coursecode");
726         if($membersuntally > 0){
727             $this->log_line("Removed $membersuntally users from course $ship->coursecode");
728         }
729     }
730 } // End process_membership_tag()
732 /**
733 * Process the properties tag. The only data from this element
734 * that is relevant is whether a <target> is specified.
735 * @param string $tagconents The raw contents of the XML element
736 */
737 function process_properties_tag($tagcontents){
738     $imsrestricttarget = $this->get_config('imsrestricttarget');
740     if ($imsrestricttarget) {
741         if(!(preg_match('{<target>'.preg_quote($imsrestricttarget).'</target>}is', $tagcontents, $matches))){
742             $this->log_line("Skipping processing: required target \"$imsrestricttarget\" not specified in this data.");
743             $this->continueprocessing = false;
744         }
745     }
748 /**
749 * Store logging information. This does two things: uses the {@link mtrace()}
750 * function to print info to screen/STDOUT, and also writes log to a text file
751 * if a path has been specified.
752 * @param string $string Text to write (newline will be added automatically)
753 */
754 function log_line($string){
755     mtrace($string);
756     if($this->logfp) {
757         fwrite($this->logfp, $string . "\n");
758     }
761 /**
762 * Process the INNER contents of a <timeframe> tag, to return beginning/ending dates.
763 */
764 function decode_timeframe($string){ // Pass me the INNER CONTENTS of a <timeframe> tag - beginning and/or ending is returned, in unix time, zero indicating not specified
765     $ret = new stdClass();
766     $ret->begin = $ret->end = 0;
767     // Explanatory note: The matching will ONLY match if the attribute restrict="1"
768     // because otherwise the time markers should be ignored (participation should be
769     // allowed outside the period)
770     if(preg_match('{<begin\s+restrict="1">(\d\d\d\d)-(\d\d)-(\d\d)</begin>}is', $string, $matches)){
771         $ret->begin = mktime(0,0,0, $matches[2], $matches[3], $matches[1]);
772     }
773     if(preg_match('{<end\s+restrict="1">(\d\d\d\d)-(\d\d)-(\d\d)</end>}is', $string, $matches)){
774         $ret->end = mktime(0,0,0, $matches[2], $matches[3], $matches[1]);
775     }
776     return $ret;
777 } // End decode_timeframe
779 /**
780 * Load the role mappings (from the config), so we can easily refer to
781 * how an IMS-E role corresponds to a Moodle role
782 */
783 function load_role_mappings() {
784     require_once('locallib.php');
785     global $DB;
787     $imsroles = new imsenterprise_roles();
788     $imsroles = $imsroles->get_imsroles();
790     $this->rolemappings = array();
791     foreach($imsroles as $imsrolenum=>$imsrolename) {
792         $this->rolemappings[$imsrolenum] = $this->rolemappings[$imsrolename] = $this->get_config('imsrolemap' . $imsrolenum);
793     }
796     /**
797      * Load the name mappings (from the config), so we can easily refer to
798      * how an IMS-E course properties corresponds to a Moodle course properties 
799      */
800     function load_course_mappings() {
801         require_once('locallib.php');
803         $imsnames = new imsenterprise_names();
804         $coursenames = $imsnames->get_coursenames();
805         $imsnames = $imsnames->get_imsnames();
807         $this->coursemappings = array();
808         foreach($coursenames as $coursename) {
809             $this->coursemappings[$coursename] = $this->get_config('imsrolemap' . $coursename);
810         }
811     }
813     /**
814      * Called whenever anybody tries (from the normal interface) to remove a group
815      * member which is registered as being created by this component. (Not called
816      * when deleting an entire group or course at once.)
817      * @param int $itemid Item ID that was stored in the group_members entry
818      * @param int $groupid Group ID
819      * @param int $userid User ID being removed from group
820      * @return bool True if the remove is permitted, false to give an error
821      */
822     function enrol_imsenterprise_allow_group_member_remove($itemid, $groupid, $userid) {
823         return false;
824     }
827 } // end of class