Fixes bug MDL-8454, "students can't post to forums"
[moodle-pu.git] / enrol / database / enrol.php
blob3d99bc3ed860c86a79ae6d25cf798deb7c366de7
1 <?php // $Id$
3 require_once($CFG->dirroot.'/enrol/enrol.class.php');
5 class enrolment_plugin_database {
7 var $log;
9 /*
10 * For the given user, let's go out and look in an external database
11 * for an authoritative list of enrolments, and then adjust the
12 * local Moodle assignments to match.
14 function setup_enrolments(&$user) {
15 global $CFG;
17 // NOTE: if $this->enrol_connect() succeeds you MUST remember to call
18 // $this->enrol_disconnect() as it is doing some nasty vodoo with $CFG->prefix
19 $enroldb = $this->enrol_connect();
20 if (!$enroldb) {
21 error_log('[ENROL_DB] Could not make a connection');
22 return;
25 // If we are expecting to get role information from our remote db, then
26 // we execute the below code for every role type. Otherwise we just
27 // execute it once with null (hence the dummy array).
28 $roles = !empty($CFG->enrol_db_remoterolefield) && !empty($CFG->enrol_db_localrolefield)
29 ? get_records('role')
30 : array(null);
32 //error_log('[ENROL_DB] found ' . count($roles) . ' roles:');
34 foreach($roles as $role) {
36 //error_log('[ENROL_DB] setting up enrolments for '.$role->shortname);
38 /// Get the authoritative list of enrolments from the external database table
39 /// We're using the ADOdb functions natively here and not our datalib functions
40 /// because we didn't want to mess with the $db global
42 $useridfield = $enroldb->quote($user->{$CFG->enrol_localuserfield});
44 list($have_role, $remote_role_name, $remote_role_value) = $this->role_fields($enroldb, $role);
46 /// Check if a particular role has been forced by the plugin site-wide
47 /// (if we aren't doing a role-based select)
48 if (!$have_role && $CFG->enrol_db_defaultcourseroleid) {
49 $role = get_record('role', 'id', $CFG->enrol_db_defaultcourseroleid);
52 /// Whether to fetch the default role on a per-course basis (below) or not.
53 $use_default_role = !$role;
56 if ($have_role) {
57 error_log('[ENROL_DB] Doing role-specific select from db for role: '.$role->shortname);
58 } elseif ($use_default_role) {
59 error_log('[ENROL_DB] Using course default for roles - assuming that database lists defaults');
60 } else {
61 error_log('[ENROL_DB] Using config default for roles: '.$role->shortname);
62 }*/
64 if ($rs = $enroldb->Execute("SELECT {$CFG->enrol_remotecoursefield} as enrolremotecoursefield
65 FROM {$CFG->enrol_dbtable}
66 WHERE {$CFG->enrol_remoteuserfield} = " . $useridfield .
67 (isset($remote_role_name, $remote_role_value) ? ' AND '.$remote_role_name.' = '.$remote_role_value : ''))) {
69 // We'll use this to see what to add and remove
70 $existing = $role
71 ? get_records_sql("
72 SELECT * FROM {$CFG->prefix}role_assignments
73 WHERE userid = {$user->id}
74 AND roleid = {$role->id}")
75 : get_records('role_assignments', 'userid', $user->id);
77 if (!$existing) {
78 $existing = array();
81 //error_log('[ENROL_DB] Found '.count($existing).' existing roles and '.$rs->RecordCount().' in external database');
83 if ($rs->RecordCount() > 0) { // We found some courses
85 $courselist = array();
86 while ($fields_obj = rs_fetch_next_record($rs)) { // Make a nice little array of courses to process
87 $courselist[] = $fields_obj->enrolremotecoursefield;
89 rs_close($rs);
91 foreach ($courselist as $coursefield) { /// Check the list of courses against existing
92 if ($course = get_record('course', $CFG->enrol_localcoursefield, $coursefield)) {
94 /// If there's no role specified, we get the default course role (usually student)
95 if ($use_default_role) {
96 $role = get_default_course_role($course);
99 $context = get_context_instance(CONTEXT_COURSE, $course->id);
101 // Couldn't get a role or context, skip.
102 if (!$role || !$context) {
103 continue;
107 // Search the role assignments to see if this user
108 // already has this role in this context. If it is, we
109 // skip to the next course.
110 foreach($existing as $key => $role_assignment) {
111 if ($role_assignment->roleid = $role->id
112 && $role_assignment->contextid = $context->id) {
113 unset($existing[$key]);
114 //error_log('[ENROL_DB] User is already enroled in course '.$course->idnumber);
115 continue 2;
119 //error_log('[ENROL_DB] Enrolling user in course '.$course->idnumber);
120 role_assign($role->id, $user->id, 0, $context->id, 0, 0, 0, 'database');
123 } // We've processed all external courses found
125 /// We have some courses left that we might need to unenrol from
126 /// Note: we only process enrolments that we (ie 'database' plugin) made
127 foreach ($existing as $role_assignment) {
128 if ($role_assignment->enrol == 'database') {
129 //error_log('[ENROL_DB] Removing user from context '.$role_assignment->contextid);
130 role_unassign($role_assignment->roleid, $user->id, '', $role_assignment->contextid);
133 } else {
134 error_log('[ENROL_DB] Couldn\'t get rows from external db: '.$enroldb->ErrorMsg());
137 $this->enrol_disconnect($enroldb);
141 * sync enrolments with database, create courses if required.
143 * @param object The role to sync for. If no role is specified, defaults are
144 * used.
146 function sync_enrolments($role = null) {
147 global $CFG;
148 global $db;
149 error_reporting(E_ALL);
151 // Connect to the external database
152 $enroldb = $this->enrol_connect();
153 if (!$enroldb) {
154 notify("enrol/database cannot connect to server");
155 return false;
158 if (isset($role)) {
159 echo '=== Syncing enrolments for role: '.$role->shortname." ===\n";
160 } else {
161 echo "=== Syncing enrolments for default role ===\n";
164 // first, pack the sortorder...
165 fix_course_sortorder();
167 list($have_role, $remote_role_name, $remote_role_value) = $this->role_fields($enroldb, $role);
169 if (!$have_role) {
170 if (!empty($CFG->enrol_db_defaultcourseroleid)
171 and $role = get_record('role', 'id', $CFG->enrol_db_defaultcourseroleid)) {
172 echo "=== Using enrol_db_defaultcourseroleid: {$role->id} ({$role->shortname}) ===\n";
173 } elseif (isset($role)) {
174 echo "!!! WARNING: Role specified by caller, but no (or invalid) role configuration !!!\n";
178 // get enrolments per-course
179 $sql = "SELECT DISTINCT {$CFG->enrol_remotecoursefield} " .
180 " FROM {$CFG->enrol_dbtable} " .
181 " WHERE {$CFG->enrol_remoteuserfield} IS NOT NULL" .
182 (isset($remote_role_name, $remote_role_value) ? ' AND '.$remote_role_name.' = '.$remote_role_value : '');
184 $rs = $enroldb->Execute($sql);
185 if (!$rs) {
186 trigger_error($enroldb->ErrorMsg() .' STATEMENT: '. $sql);
187 return false;
189 if ( $rs->RecordCount() == 0 ) { // no courses! outta here...
190 return true;
193 begin_sql();
194 $extcourses = array();
195 while ($extcourse_obj = rs_fetch_next_record($rs)) { // there are more course records
196 $extcourse = $extcourse_obj->{$CFG->enrol_remotecoursefield};
197 array_push($extcourses, $extcourse);
199 print "course $extcourse\n";
201 // does the course exist in moodle already?
202 $course = false;
203 $course = get_record( 'course',
204 $CFG->enrol_localcoursefield,
205 $extcourse );
207 if (!is_object($course)) {
208 if (empty($CFG->enrol_db_autocreate)) { // autocreation not allowed
209 print "Course $extcourse does not exist, skipping\n";
210 continue; // next foreach course
212 // ok, now then let's create it!
213 print "Creating Course $extcourse...";
214 // prepare any course properties we actually have
215 $course = new StdClass;
216 $course->{$CFG->enrol_localcoursefield} = $extcourse;
217 $course->fullname = $extcourse;
218 $course->shortname = $extcourse;
219 if ($newcourseid = $this->create_course($course, true)
220 and $course = get_record( 'course', 'id', $newcourseid)) {
221 // we are skipping fix_course_sortorder()
222 print "created\n";
223 } else {
224 print "failed\n";
225 continue; // nothing left to do...
230 $context = get_context_instance(CONTEXT_COURSE, $course->id);
232 // If we don't have a proper role setup, then we default to the default
233 // role for the current course.
234 if (!$have_role) {
235 $role = get_default_course_role($course);
238 // get a list of the student ids the are enrolled
239 // in the external db -- hopefully it'll fit in memory...
240 $extenrolments = array();
241 $sql = "SELECT {$CFG->enrol_remoteuserfield} " .
242 " FROM {$CFG->enrol_dbtable} " .
243 " WHERE {$CFG->enrol_remotecoursefield} = " . $enroldb->quote($extcourse) .
244 ($have_role ? ' AND '.$remote_role_name.' = '.$remote_role_value : '');
246 $crs = $enroldb->Execute($sql);
247 if (!$crs) {
248 trigger_error($enroldb->ErrorMsg() .' STATEMENT: '. $sql);
249 return false;
251 if ( $crs->RecordCount() == 0 ) { // shouldn't happen, but cover all bases
252 continue;
255 // slurp results into an array
256 while ($crs_obj = rs_fetch_next_record($crs)) {
257 array_push($extenrolments, $crs_obj->{$CFG->enrol_remoteuserfield});
259 rs_close($crs); // release the handle
262 // prune enrolments
263 // hopefully they'll fit in the max buffer size for the RDBMS
265 // TODO: This doesn't work perfectly. If we are operating without
266 // roles in the external DB, then this doesn't handle changes of role
267 // within a course (because the user is still enrolled in the course,
268 // so NOT IN misses the course).
270 // When the user logs in though, their role list will be updated
271 // correctly.
273 $to_prune = get_records_sql("
274 SELECT ra.*
275 FROM {$CFG->prefix}role_assignments ra
276 JOIN {$CFG->prefix}user u ON ra.userid = u.id
277 WHERE ra.enrol = 'database'
278 AND ra.contextid = {$context->id}
279 AND ra.roleid = ". $role->id . ($extenrolments
280 ? " AND u.{$CFG->enrol_localuserfield} NOT IN (".join(", ", array_map(array(&$db, 'quote'), $extenrolments)).")"
281 : ''));
283 if ($to_prune) {
284 foreach ($to_prune as $role_assignment) {
285 if (role_unassign($role->id, $role_assignment->userid, 0, $role_assignment->contextid)){
286 print "Unassigned {$role->shortname} assignment #{$role_assignment->id} for course {$course->id} ({$course->shortname}); user {$role_assignment->userid}\n";
287 } else {
288 print "Failed to unassign {$role->shortname} assignment #{$role_assignment->id} for course {$course->id} ({$course->shortname}); user {$role_assignment->userid}\n";
294 // insert current enrolments
295 // bad we can't do INSERT IGNORE with postgres...
297 foreach ($extenrolments as $member) {
298 // Get the user id and whether is enrolled in one fell swoop
299 $sql = "
300 SELECT u.id AS userid, ra.id AS enrolmentid
301 FROM {$CFG->prefix}user u
302 LEFT OUTER JOIN {$CFG->prefix}role_assignments ra ON u.id = ra.userid
303 AND ra.roleid = {$role->id}
304 AND ra.contextid = {$context->id}
305 WHERE u.{$CFG->enrol_localuserfield} = ".$db->quote($member) .
306 " AND (u.deleted IS NULL OR u.deleted=0) ";
308 $ers = $db->Execute($sql);
309 if (!$ers) {
310 trigger_error($db->ErrorMsg() .' STATEMENT: '. $sql);
311 return false;
313 if ( $ers->RecordCount() == 0 ) { // if this returns empty, it means we don't have the student record.
314 // should not happen -- but skip it anyway
315 trigger_error('weird! no user record entry?');
316 continue;
318 $user_obj = rs_fetch_record($ers);
319 $userid = $user_obj->userid;
320 $enrolmentid = $user_obj->enrolmentid;
321 rs_close($ers); // release the handle
323 if ($enrolmentid) { // already enrolled - skip
324 continue;
327 if (role_assign($role->id, $userid, 0, $context->id, 0, 0, 0, 'database')){
328 print "Assigned role {$role->shortname} to user {$userid} in course {$course->id} ({$course->shortname})\n";
329 } else {
330 print "Failed to assign role {$role->shortname} to user {$userid} in course {$course->id} ({$course->shortname})\n";
333 } // end foreach member
334 } // end while course records
335 rs_close($rs); //Close the main course recordset
338 // prune enrolments to courses that are no longer in ext auth
340 // TODO: This doesn't work perfectly. If we are operating without
341 // roles in the external DB, then this doesn't handle changes of role
342 // within a course (because the user is still enrolled in the course,
343 // so NOT IN misses the course).
345 // When the user logs in though, their role list will be updated
346 // correctly.
348 $sql = "
349 SELECT ra.roleid, ra.userid, ra.contextid
350 FROM {$CFG->prefix}role_assignments ra
351 LEFT OUTER JOIN ({$CFG->prefix}context cn
352 JOIN {$CFG->prefix}course c ON cn.contextlevel = ".CONTEXT_COURSE." AND cn.instanceid = c.id)
353 ON ra.contextid = cn.id
354 WHERE ra.enrol = 'database'" .
355 ($have_role ? ' AND ra.roleid = '.$role->id : '') .
356 ($extcourses
357 ? " AND (c.id IS NULL OR c.{$CFG->enrol_localcoursefield} NOT IN (" . join(",", array_map(array(&$db, 'quote'), $extcourses)) . "))"
358 : '');
360 $ers = $db->Execute($sql);
361 if (!$ers) {
362 trigger_error($db->ErrorMsg() .' STATEMENT: '. $sql);
363 return false;
365 if ( $ers->RecordCount() > 0 ) {
366 while ($user_obj = rs_fetch_next_record($ers)) {
367 $roleid = $user_obj->roleid;
368 $user = $user_obj->userid;
369 $contextid = $user_obj->contextid;
370 if (role_unassign($roleid, $user, 0, $contextid)){
371 print "Unassigned role {$roleid} from user $user in context $contextid\n";
372 } else {
373 print "Failed unassign role {$roleid} from user $user in context $contextid\n";
376 rs_close($ers); // release the handle
378 commit_sql();
380 // we are done now, a bit of housekeeping
381 fix_course_sortorder();
383 $this->enrol_disconnect($enroldb);
384 return true;
387 /// Overide the get_access_icons() function
388 function get_access_icons($course) {
392 /// Overide the base config_form() function
393 function config_form($frm) {
394 global $CFG;
396 $vars = array('enrol_dbhost', 'enrol_dbuser', 'enrol_dbpass',
397 'enrol_dbname', 'enrol_dbtable',
398 'enrol_localcoursefield', 'enrol_localuserfield',
399 'enrol_remotecoursefield', 'enrol_remoteuserfield',
400 'enrol_db_autocreate', 'enrol_db_category', 'enrol_db_template',
401 'enrol_db_localrolefield', 'enrol_db_remoterolefield',
402 'enrol_remotecoursefield', 'enrol_remoteuserfield');
404 foreach ($vars as $var) {
405 if (!isset($frm->$var)) {
406 $frm->$var = '';
409 include("$CFG->dirroot/enrol/database/config.html");
412 /// Override the base process_config() function
413 function process_config($config) {
415 if (!isset($config->enrol_dbtype)) {
416 $config->enrol_dbtype = 'mysql';
418 set_config('enrol_dbtype', $config->enrol_dbtype);
420 if (!isset($config->enrol_dbhost)) {
421 $config->enrol_dbhost = '';
423 set_config('enrol_dbhost', $config->enrol_dbhost);
425 if (!isset($config->enrol_dbuser)) {
426 $config->enrol_dbuser = '';
428 set_config('enrol_dbuser', $config->enrol_dbuser);
430 if (!isset($config->enrol_dbpass)) {
431 $config->enrol_dbpass = '';
433 set_config('enrol_dbpass', $config->enrol_dbpass);
435 if (!isset($config->enrol_dbname)) {
436 $config->enrol_dbname = '';
438 set_config('enrol_dbname', $config->enrol_dbname);
440 if (!isset($config->enrol_dbtable)) {
441 $config->enrol_dbtable = '';
443 set_config('enrol_dbtable', $config->enrol_dbtable);
445 if (!isset($config->enrol_localcoursefield)) {
446 $config->enrol_localcoursefield = '';
448 set_config('enrol_localcoursefield', $config->enrol_localcoursefield);
450 if (!isset($config->enrol_localuserfield)) {
451 $config->enrol_localuserfield = '';
453 set_config('enrol_localuserfield', $config->enrol_localuserfield);
455 if (!isset($config->enrol_remotecoursefield)) {
456 $config->enrol_remotecoursefield = '';
458 set_config('enrol_remotecoursefield', $config->enrol_remotecoursefield);
460 if (!isset($config->enrol_remoteuserfield)) {
461 $config->enrol_remoteuserfield = '';
463 set_config('enrol_remoteuserfield', $config->enrol_remoteuserfield);
465 if (!isset($config->enrol_db_autocreate)) {
466 $config->enrol_db_autocreate = '';
468 set_config('enrol_db_autocreate', $config->enrol_db_autocreate);
470 if (!isset($config->enrol_db_category)) {
471 $config->enrol_db_category = '';
473 set_config('enrol_db_category', $config->enrol_db_category);
475 if (!isset($config->enrol_db_template)) {
476 $config->enrol_db_template = '';
478 set_config('enrol_db_template', $config->enrol_db_template);
480 if (!isset($config->enrol_db_defaultcourseroleid)) {
481 $config->enrol_db_defaultcourseroleid = '';
483 set_config('enrol_db_defaultcourseroleid', $config->enrol_db_defaultcourseroleid);
485 if (!isset($config->enrol_db_localrolefield)) {
486 $config->enrol_db_localrolefield = '';
488 set_config('enrol_db_localrolefield', $config->enrol_db_localrolefield);
490 if (!isset($config->enrol_db_remoterolefield)) {
491 $config->enrol_db_remoterolefield = '';
493 set_config('enrol_db_remoterolefield', $config->enrol_db_remoterolefield);
495 return true;
498 // will create the moodle course from the template
499 // course_ext is an array as obtained from ldap -- flattened somewhat
500 // NOTE: if you pass true for $skip_fix_course_sortorder
501 // you will want to call fix_course_sortorder() after your are done
502 // with course creation
503 function create_course ($course,$skip_fix_course_sortorder=0){
504 global $CFG;
506 // define a template
507 if(!empty($CFG->enrol_db_template)){
508 $template = get_record("course", 'shortname', $CFG->enrol_db_template);
509 $template = (array)$template;
510 } else {
511 $site = get_site();
512 $template = array(
513 'startdate' => time() + 3600 * 24,
514 'summary' => get_string("defaultcoursesummary"),
515 'format' => "weeks",
516 'password' => "",
517 'guest' => 0,
518 'numsections' => 10,
519 'idnumber' => '',
520 'cost' => '',
521 'newsitems' => 5,
522 'showgrades' => 1,
523 'groupmode' => 0,
524 'groupmodeforce' => 0,
525 'student' => $site->student,
526 'students' => $site->students,
527 'teacher' => $site->teacher,
528 'teachers' => $site->teachers,
531 // overlay template
532 foreach (array_keys($template) AS $key) {
533 if (empty($course->$key)) {
534 $course->$key = $template[$key];
538 $course->category = 1; // the misc 'catch-all' category
539 if (!empty($CFG->enrol_db_category)){ //category = 0 or undef will break moodle
540 $course->category = $CFG->enrol_db_category;
543 // define the sortorder
544 $sort = get_field_sql('SELECT COALESCE(MAX(sortorder)+1, 100) AS max ' .
545 ' FROM ' . $CFG->prefix . 'course ' .
546 ' WHERE category=' . $course->category);
547 $course->sortorder = $sort;
549 // override with local data
550 $course->startdate = time() + 3600 * 24;
551 $course->timecreated = time();
552 $course->visible = 1;
554 // clear out id just in case
555 unset($course->id);
557 // truncate a few key fields
558 $course->idnumber = substr($course->idnumber, 0, 100);
559 $course->shortname = substr($course->shortname, 0, 15);
561 // store it and log
562 if ($newcourseid = insert_record("course", $course)) { // Set up new course
563 $section = NULL;
564 $section->course = $newcourseid; // Create a default section.
565 $section->section = 0;
566 $section->id = insert_record("course_sections", $section);
567 $page = page_create_object(PAGE_COURSE_VIEW, $newcourseid);
568 blocks_repopulate_page($page); // Return value no
571 if(!$skip_fix_course_sortorder){
572 fix_course_sortorder();
574 add_to_log($newcourseid, "course", "new", "view.php?id=$newcourseid", "enrol/database auto-creation");
575 } else {
576 trigger_error("Could not create new course $extcourse from from database");
577 notify("Serious Error! Could not create the new course!");
578 return false;
581 return $newcourseid;
584 /// DB Connect
585 /// NOTE: You MUST remember to disconnect
586 /// when you stop using it -- as this call will
587 /// sometimes modify $CFG->prefix for the whole of Moodle!
588 function enrol_connect() {
589 global $CFG;
591 // Try to connect to the external database (forcing new connection)
592 $enroldb = &ADONewConnection($CFG->enrol_dbtype);
593 if ($enroldb->Connect($CFG->enrol_dbhost, $CFG->enrol_dbuser, $CFG->enrol_dbpass, $CFG->enrol_dbname, true)) {
594 $enroldb->SetFetchMode(ADODB_FETCH_ASSOC); ///Set Assoc mode always after DB connection
595 return $enroldb;
596 } else {
597 trigger_error("Error connecting to enrolment DB backend with: "
598 . "$CFG->enrol_dbhost,$CFG->enrol_dbuser,$CFG->enrol_dbpass,$CFG->enrol_dbname");
599 return false;
603 /// DB Disconnect
604 function enrol_disconnect($enroldb) {
605 global $CFG;
607 $enroldb->Close();
611 * This function returns the name and value of the role field to query the db
612 * for, or null if there isn't one.
614 * @param object The ADOdb connection
615 * @param object The role
616 * @return array (boolean, string, db quoted string)
618 function role_fields($enroldb, $role) {
619 global $CFG;
621 if ($have_role = !empty($role)
622 && !empty($CFG->enrol_db_remoterolefield)
623 && !empty($CFG->enrol_db_localrolefield)
624 && !empty($role->{$CFG->enrol_db_localrolefield})) {
625 $remote_role_name = $CFG->enrol_db_remoterolefield;
626 $remote_role_value = $enroldb->quote($role->{$CFG->enrol_db_localrolefield});
627 } else {
628 $remote_role_name = $remote_role_value = null;
631 return array($have_role, $remote_role_name, $remote_role_value);
634 } // end of class