3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Database enrolment plugin.
21 * This plugin synchronises enrolment and roles with external database table.
24 * @subpackage database
25 * @copyright 2010 Petr Skoda {@link http://skodak.org}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
32 * Database enrolment plugin implementation.
33 * @author Petr Skoda - based on code by Martin Dougiamas, Martin Langhoff and others
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 class enrol_database_plugin extends enrol_plugin {
38 * Is it possible to delete enrol instance via standard UI?
40 * @param object $instance
43 public function instance_deleteable($instance) {
44 if (!enrol_is_enabled('database')) {
47 if (!$this->get_config('dbtype') or !$this->get_config('dbhost') or !$this->get_config('remoteenroltable') or !$this->get_config('remotecoursefield') or !$this->get_config('remoteuserfield')) {
51 //TODO: connect to external system and make sure no users are to be enrolled in this course
56 * Forces synchronisation of user enrolments with external database,
57 * does not create new courses.
59 * @param object $user user record
62 public function sync_user_enrolments($user) {
65 // we do not create courses here intentionally because it requires full sync and is slow
66 if (!$this->get_config('dbtype') or !$this->get_config('dbhost') or !$this->get_config('remoteenroltable') or !$this->get_config('remotecoursefield') or !$this->get_config('remoteuserfield')) {
70 $table = $this->get_config('remoteenroltable');
71 $coursefield = strtolower($this->get_config('remotecoursefield'));
72 $userfield = strtolower($this->get_config('remoteuserfield'));
73 $rolefield = strtolower($this->get_config('remoterolefield'));
75 $localrolefield = $this->get_config('localrolefield');
76 $localuserfield = $this->get_config('localuserfield');
77 $localcoursefiled = $this->get_config('localcoursefield');
79 $unenrolaction = $this->get_config('unenrolaction');
80 $defaultrole = $this->get_config('defaultrole');
82 $ignorehidden = $this->get_config('ignorehiddencourses');
84 if (!is_object($user) or !property_exists($user, 'id')) {
85 throw new coding_exception('Invalid $user parameter in sync_user_enrolments()');
88 if (!property_exists($user, $localuserfield)) {
89 debugging('Invalid $user parameter in sync_user_enrolments(), missing '.$localuserfield);
90 $user = $DB->get_record('user', array('id'=>$user->id));
93 // create roles mapping
94 $allroles = get_all_roles();
95 if (!isset($allroles[$defaultrole])) {
99 foreach ($allroles as $role) {
100 $roles[$role->$localrolefield] = $role->id;
104 $instances = array();
106 $extdb = $this->db_init();
108 // read remote enrols and create instances
109 $sql = $this->db_get_sql($table, array($userfield=>$user->$localuserfield), array(), false);
111 if ($rs = $extdb->Execute($sql)) {
113 while ($fields = $rs->FetchRow()) {
114 $fields = $this->db_decode($fields);
116 if (empty($fields[$coursefield])) {
117 // missing course info
120 if (!$course = $DB->get_record('course', array($localcoursefiled=>$fields[$coursefield]), 'id,visible')) {
123 if (!$course->visible and $ignorehidden) {
127 if (empty($fields[$rolefield]) or !isset($roles[$fields[$rolefield]])) {
132 $roleid = $defaultrole;
134 $roleid = $roles[$fields[$rolefield]];
137 if (empty($enrols[$course->id])) {
138 $enrols[$course->id] = array();
140 $enrols[$course->id][] = $roleid;
142 if ($instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>'database'), '*', IGNORE_MULTIPLE)) {
143 $instances[$course->id] = $instance;
147 $enrolid = $this->add_instance($course);
148 $instances[$course->id] = $DB->get_record('enrol', array('id'=>$enrolid));
154 // bad luck, something is wrong with the db connection
159 // enrol user into courses and sync roles
160 foreach ($enrols as $courseid => $roles) {
161 if (!isset($instances[$courseid])) {
165 $instance = $instances[$courseid];
167 if ($e = $DB->get_record('user_enrolments', array('userid'=>$user->id, 'enrolid'=>$instance->id))) {
168 // reenable enrolment when previously disable enrolment refreshed
169 if ($e->status == ENROL_USER_SUSPENDED) {
170 $DB->set_field('user_enrolments', 'status', ENROL_USER_ACTIVE, array('enrolid'=>$instance->id, 'userid'=>$user->id));
173 $roleid = reset($roles);
174 $this->enrol_user($instance, $user->id, $roleid);
177 if (!$context = get_context_instance(CONTEXT_COURSE, $instance->courseid)) {
181 $current = $DB->get_records('role_assignments', array('contextid'=>$context->id, 'userid'=>$user->id, 'component'=>'enrol_database', 'itemid'=>$instance->id), '', 'id, roleid');
184 foreach ($current as $r) {
185 if (in_array($r->id, $roles)) {
186 $existing[$r->roleid] = $r->roleid;
188 role_unassign($r->roleid, $user->id, $context->id, 'enrol_database', $instance->id);
191 foreach ($roles as $rid) {
192 if (!isset($existing[$rid])) {
193 role_assign($rid, $user->id, $context->id, 'enrol_database', $instance->id);
198 // unenrol as necessary
199 $sql = "SELECT e.*, c.visible AS cvisible, ue.status AS ustatus
201 JOIN {user_enrolments} ue ON ue.enrolid = e.id
202 JOIN {course} c ON c.id = e.courseid
203 WHERE ue.userid = :userid AND e.enrol = 'database'";
204 $rs = $DB->get_recordset_sql($sql, array('userid'=>$user->id));
205 foreach ($rs as $instance) {
206 if (!$instance->cvisible and $ignorehidden) {
210 if (!$context = get_context_instance(CONTEXT_COURSE, $instance->courseid)) {
215 if (!empty($enrols[$instance->courseid])) {
216 // we want this user enrolled
220 // deal with enrolments removed from external table
221 if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
223 $this->unenrol_user($instance, $user->id);
225 } else if ($unenrolaction == ENROL_EXT_REMOVED_KEEP) {
226 // keep - only adding enrolments
228 } else if ($unenrolaction == ENROL_EXT_REMOVED_SUSPEND or $unenrolaction == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
230 if ($instance->ustatus != ENROL_USER_SUSPENDED) {
231 $DB->set_field('user_enrolments', 'status', ENROL_USER_SUSPENDED, array('enrolid'=>$instance->id, 'userid'=>$user->id));
233 if ($unenrolaction == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
234 role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'component'=>'enrol_database', 'itemid'=>$instance->id));
242 * Forces synchronisation of all enrolments with external database.
246 public function sync_enrolments() {
249 // we do not create courses here intentionally because it requires full sync and is slow
250 if (!$this->get_config('dbtype') or !$this->get_config('dbhost') or !$this->get_config('remoteenroltable') or !$this->get_config('remotecoursefield') or !$this->get_config('remoteuserfield')) {
254 // we may need a lot of memory here
256 raise_memory_limit(MEMORY_HUGE);
258 $extdb = $this->db_init();
260 // second step is to sync instances and users
261 $table = $this->get_config('remoteenroltable');
262 $coursefield = strtolower($this->get_config('remotecoursefield'));
263 $userfield = strtolower($this->get_config('remoteuserfield'));
264 $rolefield = strtolower($this->get_config('remoterolefield'));
266 $localrolefield = $this->get_config('localrolefield');
267 $localuserfield = $this->get_config('localuserfield');
268 $localcoursefiled = $this->get_config('localcoursefield');
270 $unenrolaction = $this->get_config('unenrolaction');
271 $defaultrole = $this->get_config('defaultrole');
273 // create roles mapping
274 $allroles = get_all_roles();
275 if (!isset($allroles[$defaultrole])) {
279 foreach ($allroles as $role) {
280 $roles[$role->$localrolefield] = $role->id;
283 // get a list of courses to be synced that are in external table
284 $externalcourses = array();
285 $sql = $this->db_get_sql($table, array(), array($coursefield), true);
286 if ($rs = $extdb->Execute($sql)) {
288 while ($mapping = $rs->FetchRow()) {
289 $mapping = reset($mapping);
290 $mapping = $this->db_decode($mapping);
291 if (empty($mapping)) {
295 $externalcourses[$mapping] = true;
300 debugging('Error while communicating with external enrolment database');
304 $preventfullunenrol = empty($externalcourses);
305 if ($preventfullunenrol and $unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
306 debugging('Preventing unenrolment of all current users, because it might result in major data loss, there has to be at least one record in external enrol table, sorry.');
309 // first find all existing courses with enrol instance
311 $sql = "SELECT c.id, c.visible, c.$localcoursefiled AS mapping, e.id AS enrolid
313 JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'database')";
314 $rs = $DB->get_recordset_sql($sql); // watch out for idnumber duplicates
315 foreach ($rs as $course) {
316 if (empty($course->mapping)) {
319 $existing[$course->mapping] = $course;
323 // add necessary enrol instances that are not present yet
324 $sql = "SELECT c.id, c.visible, c.$localcoursefiled AS mapping
326 LEFT JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'database')
327 WHERE e.id IS NULL AND c.$localcoursefiled <> ?";
328 $rs = $DB->get_recordset_sql($sql, array($DB->sql_empty()));
329 foreach ($rs as $course) {
330 if (empty($course->mapping)) {
333 if (!isset($externalcourses[$course->mapping])) {
337 if (isset($existing[$course->mapping])) {
338 // some duplicate, sorry
341 $course->enrolid = $this->add_instance($course);
342 $existing[$course->mapping] = $course;
347 unset($externalcourses);
350 $ignorehidden = $this->get_config('ignorehiddencourses');
351 $sqlfields = array($userfield);
353 $sqlfields[] = $rolefield;
355 foreach ($existing as $course) {
356 if ($ignorehidden and !$course->visible) {
359 if (!$instance = $DB->get_record('enrol', array('id'=>$course->enrolid))) {
362 $context = get_context_instance(CONTEXT_COURSE, $course->id);
364 // get current list of enrolled users with their roles
365 $current_roles = array();
366 $current_status = array();
367 $user_mapping = array();
368 $sql = "SELECT u.$localuserfield AS mapping, u.id, ue.status, ue.userid, ra.roleid
370 JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
371 JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.itemid = ue.enrolid AND ra.component = 'enrol_database')
372 WHERE u.deleted = 0";
373 $params = array('enrolid'=>$instance->id);
374 if ($localuserfield === 'username') {
375 $sql .= " AND u.mnethostid = :mnethostid";
376 $params['mnethostid'] = $CFG->mnet_localhost_id;
378 $rs = $DB->get_recordset_sql($sql, $params);
379 foreach ($rs as $ue) {
380 $current_roles[$ue->userid][$ue->roleid] = $ue->roleid;
381 $current_status[$ue->userid] = $ue->status;
382 $user_mapping[$ue->mapping] = $ue->userid;
386 // get list of users that need to be enrolled and their roles
387 $requested_roles = array();
388 $sql = $this->db_get_sql($table, array($coursefield=>$course->mapping), $sqlfields);
389 if ($rs = $extdb->Execute($sql)) {
391 if ($localuserfield === 'username') {
392 $usersearch = array('mnethostid'=>$CFG->mnet_localhost_id, 'deleted' =>0);
394 while ($fields = $rs->FetchRow()) {
395 $fields = array_change_key_case($fields, CASE_LOWER);
396 if (empty($fields[$userfield])) {
397 //user identification is mandatory!
399 $mapping = $fields[$userfield];
400 if (!isset($user_mapping[$mapping])) {
401 $usersearch[$localuserfield] = $mapping;
402 if (!$user = $DB->get_record('user', $usersearch, 'id', IGNORE_MULTIPLE)) {
403 // user does not exist or was deleted
406 $user_mapping[$mapping] = $user->id;
409 $userid = $user_mapping[$mapping];
411 if (empty($fields[$rolefield]) or !isset($roles[$fields[$rolefield]])) {
416 $roleid = $defaultrole;
418 $roleid = $roles[$fields[$rolefield]];
421 $requested_roles[$userid][$roleid] = $roleid;
426 debugging('Error while communicating with external enrolment database');
430 unset($user_mapping);
432 // enrol all users and sync roles
433 foreach ($requested_roles as $userid=>$userroles) {
434 foreach ($userroles as $roleid) {
435 if (empty($current_roles[$userid])) {
436 $this->enrol_user($instance, $userid, $roleid);
437 $current_roles[$userid][$roleid] = $roleid;
438 $current_status[$userid] = ENROL_USER_ACTIVE;
442 // unassign removed roles
443 foreach($current_roles[$userid] as $cr) {
444 if (empty($userroles[$cr])) {
445 role_unassign($cr, $userid, $context->id, 'enrol_database', $instance->id);
446 unset($current_roles[$userid][$cr]);
450 // reenable enrolment when previously disable enrolment refreshed
451 if ($current_status[$userid] == ENROL_USER_SUSPENDED) {
452 $DB->set_field('user_enrolments', 'status', ENROL_USER_ACTIVE, array('enrolid'=>$instance->id, 'userid'=>$userid));
456 // deal with enrolments removed from external table
457 if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) {
458 if (!$preventfullunenrol) {
460 foreach ($current_status as $userid=>$status) {
461 if (isset($requested_roles[$userid])) {
464 $this->unenrol_user($instance, $userid);
468 } else if ($unenrolaction == ENROL_EXT_REMOVED_KEEP) {
469 // keep - only adding enrolments
471 } else if ($unenrolaction == ENROL_EXT_REMOVED_SUSPEND or $unenrolaction == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
473 foreach ($current_status as $userid=>$status) {
474 if (isset($requested_roles[$userid])) {
477 if ($status != ENROL_USER_SUSPENDED) {
478 $DB->set_field('user_enrolments', 'status', ENROL_USER_SUSPENDED, array('enrolid'=>$instance->id, 'userid'=>$userid));
480 if ($unenrolaction == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
481 role_unassign_all(array('contextid'=>$context->id, 'userid'=>$userid, 'component'=>'enrol_database', 'itemid'=>$instance->id));
487 // close db connection
492 * Performs a full sync with external database.
494 * First it creates new courses if necessary, then
495 * enrols and unenrols users.
498 public function sync_courses() {
501 // make sure we sync either enrolments or courses
502 if (!$this->get_config('dbtype') or !$this->get_config('dbhost') or !$this->get_config('newcoursetable') or !$this->get_config('newcoursefullname') or !$this->get_config('newcourseshortname')) {
506 // we may need a lot of memory here
508 raise_memory_limit(MEMORY_HUGE);
510 $extdb = $this->db_init();
512 // first create new courses
513 $table = $this->get_config('newcoursetable');
514 $fullname = strtolower($this->get_config('newcoursefullname'));
515 $shortname = strtolower($this->get_config('newcourseshortname'));
516 $idnumber = strtolower($this->get_config('newcourseidnumber'));
517 $category = strtolower($this->get_config('newcoursecategory'));
519 $sqlfields = array($fullname, $shortname);
521 $sqlfields[] = $category;
524 $sqlfields[] = $idnumber;
526 $sql = $this->db_get_sql($table, array(), $sqlfields);
527 $createcourses = array();
528 if ($rs = $extdb->Execute($sql)) {
530 $courselist = array();
531 while ($fields = $rs->FetchRow()) {
532 $fields = array_change_key_case($fields, CASE_LOWER);
533 if (empty($fields[$shortname]) or empty($fields[$fullname])) {
534 //invalid record - these two are mandatory
537 $fields = $this->db_decode($fields);
538 if ($DB->record_exists('course', array('shortname'=>$fields[$shortname]))) {
542 if ($idnumber and $DB->record_exists('course', array('idnumber'=>$fields[$idnumber]))) {
543 // idnumber duplicates are not allowed
546 if ($category and !$DB->record_exists('course_categories', array('id'=>$fields[$category]))) {
547 // invalid category id, better to skip
550 $course = new stdClass();
551 $course->fullname = $fields[$fullname];
552 $course->shortname = $fields[$shortname];
553 $course->idnumber = $idnumber ? $fields[$idnumber] : NULL;
554 $course->category = $category ? $fields[$category] : NULL;
555 $createcourses[] = $course;
560 debugging('Error while communicating with external enrolment database');
564 if ($createcourses) {
565 require_once("$CFG->dirroot/course/lib.php");
567 $template = $this->get_config('templatecourse');
568 $defaultcategory = $this->get_config('defaultcategory');
571 if ($template = $DB->get_record('course', array('shortname'=>$template))) {
572 unset($template->id);
573 unset($template->fullname);
574 unset($template->shortname);
575 unset($template->idnumber);
577 $template = new stdClass();
580 $template = new stdClass();
582 if (!$DB->record_exists('course_categories', array('id'=>$defaultcategory))) {
583 $categories = $DB->get_records('course_categories', array(), 'sortorder', 'id', 0, 1);
584 $first = reset($categories);
585 $defaultcategory = $first->id;
588 foreach ($createcourses as $fields) {
589 $newcourse = clone($template);
590 $newcourse->fullname = $fields->fullname;
591 $newcourse->shortname = $fields->shortname;
592 $newcourse->idnumber = $fields->idnumber;
593 $newcourse->category = $fields->category ? $fields->category : $defaultcategory;
595 create_course($newcourse);
598 unset($createcourses);
602 // close db connection
606 protected function db_get_sql($table, array $conditions, array $fields, $distinct = false, $sort = "") {
607 $fields = $fields ? implode(',', $fields) : "*";
610 foreach ($conditions as $key=>$value) {
611 $value = $this->db_encode($this->db_addslashes($value));
613 $where[] = "$key = '$value'";
616 $where = $where ? "WHERE ".implode(" AND ", $where) : "";
617 $sort = $sort ? "ORDER BY $sort" : "";
618 $distinct = $distinct ? "DISTINCT" : "";
619 $sql = "SELECT $distinct $fields
627 protected function db_init() {
630 require_once($CFG->libdir.'/adodb/adodb.inc.php');
632 // Connect to the external database (forcing new connection)
633 $extdb = ADONewConnection($this->get_config('dbtype'));
634 if ($this->get_config('debugdb')) {
635 $extdb->debug = true;
636 ob_start(); //start output buffer to allow later use of the page headers
639 $extdb->Connect($this->get_config('dbhost'), $this->get_config('dbuser'), $this->get_config('dbpass'), $this->get_config('dbname'), true);
640 $extdb->SetFetchMode(ADODB_FETCH_ASSOC);
641 if ($this->get_config('dbsetupsql')) {
642 $extdb->Execute($this->get_config('dbsetupsql'));
647 protected function db_addslashes($text) {
648 // using custom made function for now
649 if ($this->get_config('dbsybasequoting')) {
650 $text = str_replace('\\', '\\\\', $text);
651 $text = str_replace(array('\'', '"', "\0"), array('\\\'', '\\"', '\\0'), $text);
653 $text = str_replace("'", "''", $text);
658 protected function db_encode($text) {
659 $dbenc = $this->get_config('dbencoding');
660 if (empty($dbenc) or $dbenc == 'utf-8') {
663 if (is_array($text)) {
664 foreach($text as $k=>$value) {
665 $text[$k] = $this->db_encode($value);
669 return textlib_get_instance()->convert($text, 'utf-8', $dbenc);
673 protected function db_decode($text) {
674 $dbenc = $this->get_config('dbencoding');
675 if (empty($dbenc) or $dbenc == 'utf-8') {
678 if (is_array($text)) {
679 foreach($text as $k=>$value) {
680 $text[$k] = $this->db_decode($value);
684 return textlib_get_instance()->convert($text, $dbenc, 'utf-8');