2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * Flatfile enrolment plugin.
20 * This plugin lets the user specify a "flatfile" (CSV) containing enrolment information.
21 * On a regular cron cycle, the specified file is parsed and then deleted.
23 * @package enrol_flatfile
24 * @copyright 2010 Eugene Venter
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
32 * Flatfile enrolment plugin implementation.
34 * Comma separated file assumed to have four or six fields per line:
35 * operation, role, idnumber(user), idnumber(course) [, starttime [, endtime]]
37 * operation = add | del
38 * role = student | teacher | teacheredit
39 * idnumber(user) = idnumber in the user table NB not id
40 * idnumber(course) = idnumber in the course table NB not id
41 * starttime = start time (in seconds since epoch) - optional
42 * endtime = end time (in seconds since epoch) - optional
44 * @author Eugene Venter - based on code by Petr Skoda, Martin Dougiamas, Martin Langhoff and others
45 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47 class enrol_flatfile_plugin extends enrol_plugin {
48 protected $lasternoller = null;
49 protected $lasternollercourseid = 0;
52 * Does this plugin assign protected roles are can they be manually removed?
53 * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
55 public function roles_protected() {
60 * Does this plugin allow manual unenrolment of all users?
61 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
63 * @param stdClass $instance course enrol instance
64 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
66 public function allow_unenrol(stdClass $instance) {
71 * Does this plugin allow manual unenrolment of a specific user?
72 * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
74 * This is useful especially for synchronisation plugins that
75 * do suspend instead of full unenrolment.
77 * @param stdClass $instance course enrol instance
78 * @param stdClass $ue record from user_enrolments table, specifies user
80 * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
82 public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
87 * Does this plugin allow manual changes in user_enrolments table?
89 * All plugins allowing this must implement 'enrol/xxx:manage' capability
91 * @param stdClass $instance course enrol instance
92 * @return bool - true means it is possible to change enrol period and status in user_enrolments table
94 public function allow_manage(stdClass $instance) {
99 * Is it possible to delete enrol instance via standard UI?
101 * @param object $instance
104 public function can_delete_instance($instance) {
105 $context = context_course::instance($instance->courseid);
106 return has_capability('enrol/flatfile:manage', $context);
110 * Is it possible to hide/show enrol instance via standard UI?
112 * @param stdClass $instance
115 public function can_hide_show_instance($instance) {
116 $context = context_course::instance($instance->courseid);
117 return has_capability('enrol/flatfile:manage', $context);
121 * Gets an array of the user enrolment actions.
123 * @param course_enrolment_manager $manager
124 * @param stdClass $ue A user enrolment object
125 * @return array An array of user_enrolment_actions
127 public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
129 $context = $manager->get_context();
130 $instance = $ue->enrolmentinstance;
131 $params = $manager->get_moodlepage()->url->params();
132 $params['ue'] = $ue->id;
133 if ($this->allow_unenrol_user($instance, $ue) && has_capability("enrol/flatfile:unenrol", $context)) {
134 $url = new moodle_url('/enrol/unenroluser.php', $params);
135 $actionparams = array('class' => 'unenrollink', 'rel' => $ue->id, 'data-action' => ENROL_ACTION_UNENROL);
136 $actions[] = new user_enrolment_action(new pix_icon('t/delete', ''), get_string('unenrol', 'enrol'), $url,
139 if ($this->allow_manage($instance) && has_capability("enrol/flatfile:manage", $context)) {
140 $url = new moodle_url('/enrol/editenrolment.php', $params);
141 $actionparams = array('class' => 'editenrollink', 'rel' => $ue->id, 'data-action' => ENROL_ACTION_EDIT);
142 $actions[] = new user_enrolment_action(new pix_icon('t/edit', ''), get_string('edit'), $url, $actionparams);
148 * Enrol user into course via enrol instance.
150 * @param stdClass $instance
152 * @param int $roleid optional role id
153 * @param int $timestart 0 means unknown
154 * @param int $timeend 0 means forever
155 * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
156 * @param bool $recovergrades restore grade history
159 public function enrol_user(stdClass $instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
160 parent::enrol_user($instance, $userid, null, $timestart, $timeend, $status, $recovergrades);
162 $context = context_course::instance($instance->courseid, MUST_EXIST);
163 role_assign($roleid, $userid, $context->id, 'enrol_'.$this->get_name(), $instance->id);
168 * Execute synchronisation.
169 * @param progress_trace
170 * @return int exit code, 0 means ok, 2 means plugin disabled
172 public function sync(progress_trace $trace) {
173 if (!enrol_is_enabled('flatfile')) {
177 $mailadmins = $this->get_config('mailadmins', 0);
180 $buffer = new progress_trace_buffer(new text_progress_trace(), false);
181 $trace = new combined_progress_trace(array($trace, $buffer));
186 $processed = $this->process_file($trace) || $processed;
187 $processed = $this->process_buffer($trace) || $processed;
188 $processed = $this->process_expirations($trace) || $processed;
190 if ($processed and $mailadmins) {
191 if ($log = $buffer->get_buffer()) {
192 $eventdata = new \core\message\message();
193 $eventdata->courseid = SITEID;
194 $eventdata->modulename = 'moodle';
195 $eventdata->component = 'enrol_flatfile';
196 $eventdata->name = 'flatfile_enrolment';
197 $eventdata->userfrom = get_admin();
198 $eventdata->userto = get_admin();
199 $eventdata->subject = 'Flatfile Enrolment Log';
200 $eventdata->fullmessage = $log;
201 $eventdata->fullmessageformat = FORMAT_PLAIN;
202 $eventdata->fullmessagehtml = '';
203 $eventdata->smallmessage = '';
204 message_send($eventdata);
206 $buffer->reset_buffer();
213 * Sorry, we do not want to show paths in cron output.
215 * @param string $filepath
218 protected function obfuscate_filepath($filepath) {
221 if (strpos($filepath, $CFG->dataroot.'/') === 0 or strpos($filepath, $CFG->dataroot.'\\') === 0) {
222 $disclosefile = '$CFG->dataroot'.substr($filepath, strlen($CFG->dataroot));
224 } else if (strpos($filepath, $CFG->dirroot.'/') === 0 or strpos($filepath, $CFG->dirroot.'\\') === 0) {
225 $disclosefile = '$CFG->dirroot'.substr($filepath, strlen($CFG->dirroot));
228 $disclosefile = basename($filepath);
231 return $disclosefile;
236 * @param progress_trace $trace
237 * @return bool true if any data processed, false if not
239 protected function process_file(progress_trace $trace) {
242 // We may need more memory here.
243 core_php_time_limit::raise();
244 raise_memory_limit(MEMORY_HUGE);
246 $filelocation = $this->get_config('location');
247 if (empty($filelocation)) {
248 // Default legacy location.
249 $filelocation = "$CFG->dataroot/1/enrolments.txt";
251 $disclosefile = $this->obfuscate_filepath($filelocation);
253 if (!file_exists($filelocation)) {
254 $trace->output("Flatfile enrolments file not found: $disclosefile");
258 $trace->output("Processing flat file enrolments from: $disclosefile ...");
260 $content = file_get_contents($filelocation);
262 if ($content !== false) {
264 $rolemap = $this->get_role_map($trace);
266 $content = core_text::convert($content, $this->get_config('encoding', 'utf-8'), 'utf-8');
267 $content = str_replace("\r", '', $content);
268 $content = explode("\n", $content);
271 foreach($content as $fields) {
274 if (trim($fields) === '') {
275 // Empty lines are ignored.
279 // Deal with different separators.
280 if (strpos($fields, ',') !== false) {
281 $fields = explode(',', $fields);
283 $fields = explode(';', $fields);
286 // If a line is incorrectly formatted ie does not have 4 comma separated fields then ignore it.
287 if (count($fields) < 4 or count($fields) > 6) {
288 $trace->output("Line incorrectly formatted - ignoring $line", 1);
292 $fields[0] = trim(core_text::strtolower($fields[0]));
293 $fields[1] = trim(core_text::strtolower($fields[1]));
294 $fields[2] = trim($fields[2]);
295 $fields[3] = trim($fields[3]);
296 $fields[4] = isset($fields[4]) ? (int)trim($fields[4]) : 0;
297 $fields[5] = isset($fields[5]) ? (int)trim($fields[5]) : 0;
299 // Deal with quoted values - all or nothing, we need to support "' in idnumbers, sorry.
300 if (strpos($fields[0], "'") === 0) {
301 foreach ($fields as $k=>$v) {
302 $fields[$k] = trim($v, "'");
304 } else if (strpos($fields[0], '"') === 0) {
305 foreach ($fields as $k=>$v) {
306 $fields[$k] = trim($v, '"');
310 $trace->output("$line: $fields[0], $fields[1], $fields[2], $fields[3], $fields[4], $fields[5]", 1);
312 // Check correct formatting of operation field.
313 if ($fields[0] !== "add" and $fields[0] !== "del") {
314 $trace->output("Unknown operation in field 1 - ignoring line $line", 1);
318 // Check correct formatting of role field.
319 if (!isset($rolemap[$fields[1]])) {
320 $trace->output("Unknown role in field2 - ignoring line $line", 1);
323 $roleid = $rolemap[$fields[1]];
325 if (empty($fields[2]) or !$user = $DB->get_record("user", array("idnumber"=>$fields[2], 'deleted'=>0))) {
326 $trace->output("Unknown user idnumber or deleted user in field 3 - ignoring line $line", 1);
330 if (!$course = $DB->get_record("course", array("idnumber"=>$fields[3]))) {
331 $trace->output("Unknown course idnumber in field 4 - ignoring line $line", 1);
335 if ($fields[4] > $fields[5] and $fields[5] != 0) {
336 $trace->output("Start time was later than end time - ignoring line $line", 1);
340 $this->process_records($trace, $fields[0], $roleid, $user, $course, $fields[4], $fields[5]);
346 if (!unlink($filelocation)) {
347 $eventdata = new \core\message\message();
348 $eventdata->courseid = SITEID;
349 $eventdata->modulename = 'moodle';
350 $eventdata->component = 'enrol_flatfile';
351 $eventdata->name = 'flatfile_enrolment';
352 $eventdata->userfrom = get_admin();
353 $eventdata->userto = get_admin();
354 $eventdata->subject = get_string('filelockedmailsubject', 'enrol_flatfile');
355 $eventdata->fullmessage = get_string('filelockedmail', 'enrol_flatfile', $filelocation);
356 $eventdata->fullmessageformat = FORMAT_PLAIN;
357 $eventdata->fullmessagehtml = '';
358 $eventdata->smallmessage = '';
359 message_send($eventdata);
360 $trace->output("Error deleting enrolment file: $disclosefile", 1);
362 $trace->output("Deleted enrolment file", 1);
365 $trace->output("...finished enrolment file processing.");
372 * Process any future enrollments stored in the buffer.
373 * @param progress_trace $trace
374 * @return bool true if any data processed, false if not
376 protected function process_buffer(progress_trace $trace) {
379 if (!$future_enrols = $DB->get_records_select('enrol_flatfile', "timestart < ?", array(time()))) {
380 $trace->output("No enrolments to be processed in flatfile buffer");
385 $trace->output("Starting processing of flatfile buffer");
386 foreach($future_enrols as $en) {
387 $user = $DB->get_record('user', array('id'=>$en->userid));
388 $course = $DB->get_record('course', array('id'=>$en->courseid));
389 if ($user and $course) {
390 $trace->output("buffer: $en->action $en->roleid $user->id $course->id $en->timestart $en->timeend", 1);
391 $this->process_records($trace, $en->action, $en->roleid, $user, $course, $en->timestart, $en->timeend, false);
393 $DB->delete_records('enrol_flatfile', array('id'=>$en->id));
395 $trace->output("Finished processing of flatfile buffer");
402 * Process user enrolment line.
404 * @param progress_trace $trace
405 * @param string $action
407 * @param stdClass $user
408 * @param stdClass $course
409 * @param int $timestart
410 * @param int $timeend
411 * @param bool $buffer_if_future
413 protected function process_records(progress_trace $trace, $action, $roleid, $user, $course, $timestart, $timeend, $buffer_if_future = true) {
416 // Check if timestart is for future processing.
417 if ($timestart > time() and $buffer_if_future) {
418 // Populate into enrol_flatfile table as a future role to be assigned by cron.
419 // Note: since 2.0 future enrolments do not cause problems if you disable guest access.
420 $future_en = new stdClass();
421 $future_en->action = $action;
422 $future_en->roleid = $roleid;
423 $future_en->userid = $user->id;
424 $future_en->courseid = $course->id;
425 $future_en->timestart = $timestart;
426 $future_en->timeend = $timeend;
427 $future_en->timemodified = time();
428 $DB->insert_record('enrol_flatfile', $future_en);
429 $trace->output("User $user->id will be enrolled later into course $course->id using role $roleid ($timestart, $timeend)", 1);
433 $context = context_course::instance($course->id);
435 if ($action === 'add') {
436 // Clear the buffer just in case there were some future enrolments.
437 $DB->delete_records('enrol_flatfile', array('userid'=>$user->id, 'courseid'=>$course->id, 'roleid'=>$roleid));
439 $instance = $DB->get_record('enrol', array('courseid' => $course->id, 'enrol' => 'flatfile'));
440 if (empty($instance)) {
441 // Only add an enrol instance to the course if non-existent.
442 $enrolid = $this->add_instance($course);
443 $instance = $DB->get_record('enrol', array('id' => $enrolid));
447 if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$user->id))) {
449 $this->update_user_enrol($instance, $user->id, ENROL_USER_ACTIVE, $timestart, $timeend);
450 if (!$DB->record_exists('role_assignments', array('contextid'=>$context->id, 'roleid'=>$roleid, 'userid'=>$user->id, 'component'=>'enrol_flatfile', 'itemid'=>$instance->id))) {
451 role_assign($roleid, $user->id, $context->id, 'enrol_flatfile', $instance->id);
453 $trace->output("User $user->id enrolment updated in course $course->id using role $roleid ($timestart, $timeend)", 1);
456 // Enrol the user with this plugin instance.
457 $this->enrol_user($instance, $user->id, $roleid, $timestart, $timeend);
458 $trace->output("User $user->id enrolled in course $course->id using role $roleid ($timestart, $timeend)", 1);
462 if ($notify and $this->get_config('mailstudents')) {
463 $oldforcelang = force_current_language($user->lang);
465 // Send welcome notification to enrolled users.
467 $a->coursename = format_string($course->fullname, true, array('context' => $context));
468 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id";
469 $subject = get_string('enrolmentnew', 'enrol', format_string($course->shortname, true, array('context' => $context)));
471 $eventdata = new \core\message\message();
472 $eventdata->courseid = $course->id;
473 $eventdata->modulename = 'moodle';
474 $eventdata->component = 'enrol_flatfile';
475 $eventdata->name = 'flatfile_enrolment';
476 $eventdata->userfrom = $this->get_enroller($course->id);
477 $eventdata->userto = $user;
478 $eventdata->subject = $subject;
479 $eventdata->fullmessage = get_string('welcometocoursetext', '', $a);
480 $eventdata->fullmessageformat = FORMAT_PLAIN;
481 $eventdata->fullmessagehtml = '';
482 $eventdata->smallmessage = '';
483 if (message_send($eventdata)) {
484 $trace->output("Notified enrolled user", 1);
486 $trace->output("Failed to notify enrolled user", 1);
489 force_current_language($oldforcelang);
492 if ($notify and $this->get_config('mailteachers', 0)) {
493 // Notify person responsible for enrolments.
494 $enroller = $this->get_enroller($course->id);
496 $oldforcelang = force_current_language($enroller->lang);
499 $a->course = format_string($course->fullname, true, array('context' => $context));
500 $a->user = fullname($user);
501 $subject = get_string('enrolmentnew', 'enrol', format_string($course->shortname, true, array('context' => $context)));
503 $eventdata = new \core\message\message();
504 $eventdata->courseid = $course->id;
505 $eventdata->modulename = 'moodle';
506 $eventdata->component = 'enrol_flatfile';
507 $eventdata->name = 'flatfile_enrolment';
508 $eventdata->userfrom = get_admin();
509 $eventdata->userto = $enroller;
510 $eventdata->subject = $subject;
511 $eventdata->fullmessage = get_string('enrolmentnewuser', 'enrol', $a);
512 $eventdata->fullmessageformat = FORMAT_PLAIN;
513 $eventdata->fullmessagehtml = '';
514 $eventdata->smallmessage = '';
515 if (message_send($eventdata)) {
516 $trace->output("Notified enroller {$eventdata->userto->id}", 1);
518 $trace->output("Failed to notify enroller {$eventdata->userto->id}", 1);
521 force_current_language($oldforcelang);
525 } else if ($action === 'del') {
526 // Clear the buffer just in case there were some future enrolments.
527 $DB->delete_records('enrol_flatfile', array('userid'=>$user->id, 'courseid'=>$course->id, 'roleid'=>$roleid));
529 $action = $this->get_config('unenrolaction');
530 if ($action == ENROL_EXT_REMOVED_KEEP) {
531 $trace->output("del action is ignored", 1);
535 // Loops through all enrolment methods, try to unenrol if roleid somehow matches.
536 $instances = $DB->get_records('enrol', array('courseid' => $course->id));
538 foreach ($instances as $instance) {
539 if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$user->id))) {
542 if ($instance->enrol === 'flatfile') {
545 if (!enrol_is_enabled($instance->enrol)) {
548 if (!$plugin = enrol_get_plugin($instance->enrol)) {
551 if (!$plugin->allow_unenrol_user($instance, $ue)) {
556 // For some reason the del action includes a role name, this complicates everything.
557 $componentroles = array();
558 $manualroles = array();
559 $ras = $DB->get_records('role_assignments', array('userid'=>$user->id, 'contextid'=>$context->id));
560 foreach ($ras as $ra) {
561 if ($ra->component === '') {
562 $manualroles[$ra->roleid] = $ra->roleid;
563 } else if ($ra->component === 'enrol_'.$instance->enrol and $ra->itemid == $instance->id) {
564 $componentroles[$ra->roleid] = $ra->roleid;
568 if ($componentroles and !isset($componentroles[$roleid])) {
569 // Do not unenrol using this method, user has some other protected role!
572 } else if (empty($ras)) {
573 // If user does not have any roles then let's just suspend as many methods as possible.
575 } else if (!$plugin->roles_protected()) {
576 if (!$componentroles and $manualroles and !isset($manualroles[$roleid])) {
577 // Most likely we want to keep users enrolled because they have some other course roles.
582 if ($action == ENROL_EXT_REMOVED_UNENROL) {
584 if (!$plugin->roles_protected()) {
585 role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'roleid'=>$roleid, 'component'=>'', 'itemid'=>0), true);
587 $plugin->unenrol_user($instance, $user->id);
588 $trace->output("User $user->id was unenrolled from course $course->id (enrol_$instance->enrol)", 1);
590 } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
591 if ($plugin->allow_manage($instance)) {
592 if ($ue->status == ENROL_USER_ACTIVE) {
594 $plugin->update_user_enrol($instance, $user->id, ENROL_USER_SUSPENDED);
595 if (!$plugin->roles_protected()) {
596 role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'component'=>'enrol_'.$instance->enrol, 'itemid'=>$instance->id), true);
597 role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'roleid'=>$roleid, 'component'=>'', 'itemid'=>0), true);
599 $trace->output("User $user->id enrolment was suspended in course $course->id (enrol_$instance->enrol)", 1);
606 if (0 == $DB->count_records('role_assignments', array('userid'=>$user->id, 'contextid'=>$context->id))) {
607 role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'component'=>'', 'itemid'=>0), true);
609 $trace->output("User $user->id (with role $roleid) not unenrolled from course $course->id", 1);
617 * Returns the user who is responsible for flatfile enrolments in given curse.
619 * Usually it is the first editing teacher - the person with "highest authority"
620 * as defined by sort_by_roleassignment_authority() having 'enrol/flatfile:manage'
621 * or 'moodle/role:assign' capability.
623 * @param int $courseid enrolment instance id
624 * @return stdClass user record
626 protected function get_enroller($courseid) {
627 if ($this->lasternollercourseid == $courseid and $this->lasternoller) {
628 return $this->lasternoller;
631 $context = context_course::instance($courseid);
633 $users = get_enrolled_users($context, 'enrol/flatfile:manage');
635 $users = get_enrolled_users($context, 'moodle/role:assign');
639 $users = sort_by_roleassignment_authority($users, $context);
640 $this->lasternoller = reset($users);
643 $this->lasternoller = get_admin();
646 $this->lasternollercourseid == $courseid;
648 return $this->lasternoller;
652 * Returns a mapping of ims roles to role ids.
654 * @param progress_trace $trace
655 * @return array imsrolename=>roleid
657 protected function get_role_map(progress_trace $trace) {
662 $roles = $DB->get_records('role', null, '', 'id, name, shortname');
663 foreach ($roles as $id=>$role) {
664 $alias = $this->get_config('map_'.$id, $role->shortname, '');
665 $alias = trim(core_text::strtolower($alias));
667 // Either not configured yet or somebody wants to skip these intentionally.
670 if (isset($rolemap[$alias])) {
671 $trace->output("Duplicate role alias $alias detected!");
673 $rolemap[$alias] = $id;
681 * Restore instance and map settings.
683 * @param restore_enrolments_structure_step $step
684 * @param stdClass $data
685 * @param stdClass $course
688 public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
691 if ($instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>$this->get_name()))) {
692 $instanceid = $instance->id;
694 $instanceid = $this->add_instance($course);
696 $step->set_mapping('enrol', $oldid, $instanceid);
700 * Restore user enrolment.
702 * @param restore_enrolments_structure_step $step
703 * @param stdClass $data
704 * @param stdClass $instance
705 * @param int $oldinstancestatus
708 public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
709 $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
713 * Restore role assignment.
715 * @param stdClass $instance
718 * @param int $contextid
720 public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
721 role_assign($roleid, $userid, $contextid, 'enrol_'.$instance->enrol, $instance->id);