adding some strings
[moodle-linuxchix.git] / enrol / database / enrol.php
blob1b3a22af171d026a1298a542cb139473a40abc51
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 $course = get_record('course', $CFG->enrol_localcoursefield, $coursefield);
93 if (!is_object($course)) {
94 if (empty($CFG->enrol_db_autocreate)) { // autocreation not allowed
95 if (debugging('',DEBUG_ALL)) {
96 error_log( "Course $coursefield does not exist, skipping") ;
98 continue; // next foreach course
100 // ok, now then let's create it!
101 // prepare any course properties we actually have
102 $course = new StdClass;
103 $course->{$CFG->enrol_localcoursefield} = $coursefield;
104 $course->fullname = $coursefield;
105 $course->shortname = $coursefield;
106 if (!($newcourseid = $this->create_course($course, true)
107 and $course = get_record( 'course', 'id', $newcourseid))) {
108 error_log( "Creating course $coursefield failed");
109 continue; // nothing left to do...
113 // if the course is hidden and we don't want to enrol in hidden courses
114 // then just skip it
115 if (!$course->visible and $CFG->enrol_db_ignorehiddencourse) {
116 continue;
119 /// If there's no role specified, we get the default course role (usually student)
120 if ($use_default_role) {
121 $role = get_default_course_role($course);
124 $context = get_context_instance(CONTEXT_COURSE, $course->id);
126 // Couldn't get a role or context, skip.
127 if (!$role || !$context) {
128 continue;
131 // Search the role assignments to see if this user
132 // already has this role in this context. If it is, we
133 // skip to the next course.
134 foreach($existing as $key => $role_assignment) {
135 if ($role_assignment->roleid == $role->id
136 && $role_assignment->contextid == $context->id) {
137 unset($existing[$key]);
138 //error_log('[ENROL_DB] User is already enroled in course '.$course->idnumber);
139 continue 2;
143 //error_log('[ENROL_DB] Enrolling user in course '.$course->idnumber);
144 role_assign($role->id, $user->id, 0, $context->id, 0, 0, 0, 'database');
146 } // We've processed all external courses found
148 /// We have some courses left that we might need to unenrol from
149 /// Note: we only process enrolments that we (ie 'database' plugin) made
150 foreach ($existing as $role_assignment) {
151 if ($role_assignment->enrol == 'database') {
152 //error_log('[ENROL_DB] Removing user from context '.$role_assignment->contextid);
153 role_unassign($role_assignment->roleid, $user->id, '', $role_assignment->contextid);
156 } else {
157 error_log('[ENROL_DB] Couldn\'t get rows from external db: '.$enroldb->ErrorMsg());
160 $this->enrol_disconnect($enroldb);
164 * sync enrolments with database, create courses if required.
166 * @param object The role to sync for. If no role is specified, defaults are
167 * used.
169 function sync_enrolments($role = null) {
170 global $CFG;
171 global $db;
172 error_reporting(E_ALL);
174 // Connect to the external database
175 $enroldb = $this->enrol_connect();
176 if (!$enroldb) {
177 notify("enrol/database cannot connect to server");
178 return false;
181 if (isset($role)) {
182 echo '=== Syncing enrolments for role: '.$role->shortname." ===\n";
183 } else {
184 echo "=== Syncing enrolments for default role ===\n";
187 // first, pack the sortorder...
188 fix_course_sortorder();
190 list($have_role, $remote_role_name, $remote_role_value) = $this->role_fields($enroldb, $role);
192 if (!$have_role) {
193 if (!empty($CFG->enrol_db_defaultcourseroleid)
194 and $role = get_record('role', 'id', $CFG->enrol_db_defaultcourseroleid)) {
195 echo "=== Using enrol_db_defaultcourseroleid: {$role->id} ({$role->shortname}) ===\n";
196 } elseif (isset($role)) {
197 echo "!!! WARNING: Role specified by caller, but no (or invalid) role configuration !!!\n";
201 // get enrolments per-course
202 $sql = "SELECT DISTINCT {$CFG->enrol_remotecoursefield} " .
203 " FROM {$CFG->enrol_dbtable} " .
204 " WHERE {$CFG->enrol_remoteuserfield} IS NOT NULL" .
205 (isset($remote_role_name, $remote_role_value) ? ' AND '.$remote_role_name.' = '.$remote_role_value : '');
207 $rs = $enroldb->Execute($sql);
208 if (!$rs) {
209 trigger_error($enroldb->ErrorMsg() .' STATEMENT: '. $sql);
210 return false;
212 if ( $rs->RecordCount() == 0 ) { // no courses! outta here...
213 return true;
216 begin_sql();
217 $extcourses = array();
218 while ($extcourse_obj = rs_fetch_next_record($rs)) { // there are more course records
219 $extcourse = $extcourse_obj->{$CFG->enrol_remotecoursefield};
220 array_push($extcourses, $extcourse);
222 // does the course exist in moodle already?
223 $course = false;
224 $course = get_record( 'course',
225 $CFG->enrol_localcoursefield,
226 $extcourse );
228 if (!is_object($course)) {
229 if (empty($CFG->enrol_db_autocreate)) { // autocreation not allowed
230 if (debugging('', DEBUG_ALL)) {
231 error_log( "Course $extcourse does not exist, skipping");
233 continue; // next foreach course
235 // ok, now then let's create it!
236 // prepare any course properties we actually have
237 $course = new StdClass;
238 $course->{$CFG->enrol_localcoursefield} = $extcourse;
239 $course->fullname = $extcourse;
240 $course->shortname = $extcourse;
241 if (!($newcourseid = $this->create_course($course, true)
242 and $course = get_record( 'course', 'id', $newcourseid))) {
243 error_log( "Creating course $extcourse failed");
244 continue; // nothing left to do...
249 $context = get_context_instance(CONTEXT_COURSE, $course->id);
251 // If we don't have a proper role setup, then we default to the default
252 // role for the current course.
253 if (!$have_role) {
254 $role = get_default_course_role($course);
257 // get a list of the student ids the are enrolled
258 // in the external db -- hopefully it'll fit in memory...
259 $extenrolments = array();
260 $sql = "SELECT {$CFG->enrol_remoteuserfield} " .
261 " FROM {$CFG->enrol_dbtable} " .
262 " WHERE {$CFG->enrol_remotecoursefield} = " . $enroldb->quote($extcourse) .
263 ($have_role ? ' AND '.$remote_role_name.' = '.$remote_role_value : '');
265 $crs = $enroldb->Execute($sql);
266 if (!$crs) {
267 trigger_error($enroldb->ErrorMsg() .' STATEMENT: '. $sql);
268 return false;
270 if ( $crs->RecordCount() == 0 ) { // shouldn't happen, but cover all bases
271 continue;
274 // slurp results into an array
275 while ($crs_obj = rs_fetch_next_record($crs)) {
276 array_push($extenrolments, $crs_obj->{$CFG->enrol_remoteuserfield});
278 rs_close($crs); // release the handle
281 // prune enrolments
282 // hopefully they'll fit in the max buffer size for the RDBMS
284 // TODO: This doesn't work perfectly. If we are operating without
285 // roles in the external DB, then this doesn't handle changes of role
286 // within a course (because the user is still enrolled in the course,
287 // so NOT IN misses the course).
289 // When the user logs in though, their role list will be updated
290 // correctly.
292 $to_prune = get_records_sql("
293 SELECT ra.*
294 FROM {$CFG->prefix}role_assignments ra
295 JOIN {$CFG->prefix}user u ON ra.userid = u.id
296 WHERE ra.enrol = 'database'
297 AND ra.contextid = {$context->id}
298 AND ra.roleid = ". $role->id . ($extenrolments
299 ? " AND u.{$CFG->enrol_localuserfield} NOT IN (".join(", ", array_map(array(&$db, 'quote'), $extenrolments)).")"
300 : ''));
302 if ($to_prune) {
303 foreach ($to_prune as $role_assignment) {
304 if (role_unassign($role->id, $role_assignment->userid, 0, $role_assignment->contextid)){
305 error_log( "Unassigned {$role->shortname} assignment #{$role_assignment->id} for course {$course->id} (" . format_string($course->shortname) . "); user {$role_assignment->userid}");
306 } else {
307 error_log( "Failed to unassign {$role->shortname} assignment #{$role_assignment->id} for course {$course->id} (" . format_string($course->shortname) . "); user {$role_assignment->userid}");
313 // insert current enrolments
314 // bad we can't do INSERT IGNORE with postgres...
316 foreach ($extenrolments as $member) {
317 // Get the user id and whether is enrolled in one fell swoop
318 $sql = "
319 SELECT u.id AS userid, ra.id AS enrolmentid
320 FROM {$CFG->prefix}user u
321 LEFT OUTER JOIN {$CFG->prefix}role_assignments ra ON u.id = ra.userid
322 AND ra.roleid = {$role->id}
323 AND ra.contextid = {$context->id}
324 WHERE u.{$CFG->enrol_localuserfield} = ".$db->quote($member) .
325 " AND (u.deleted IS NULL OR u.deleted=0) ";
327 $ers = $db->Execute($sql);
328 if (!$ers) {
329 trigger_error($db->ErrorMsg() .' STATEMENT: '. $sql);
330 return false;
332 if ( $ers->RecordCount() == 0 ) { // if this returns empty, it means we don't have the student record.
333 // should not happen -- but skip it anyway
334 trigger_error('weird! no user record entry?');
335 continue;
337 $user_obj = rs_fetch_record($ers);
338 $userid = $user_obj->userid;
339 $enrolmentid = $user_obj->enrolmentid;
340 rs_close($ers); // release the handle
342 if ($enrolmentid) { // already enrolled - skip
343 continue;
346 if (role_assign($role->id, $userid, 0, $context->id, 0, 0, 0, 'database')){
347 error_log( "Assigned role {$role->shortname} to user {$userid} in course {$course->id} (" . format_string($course->shortname) . ")");
348 } else {
349 error_log( "Failed to assign role {$role->shortname} to user {$userid} in course {$course->id} (" . format_string($course->shortname) . ")");
352 } // end foreach member
353 } // end while course records
354 rs_close($rs); //Close the main course recordset
357 // prune enrolments to courses that are no longer in ext auth
359 // TODO: This doesn't work perfectly. If we are operating without
360 // roles in the external DB, then this doesn't handle changes of role
361 // within a course (because the user is still enrolled in the course,
362 // so NOT IN misses the course).
364 // When the user logs in though, their role list will be updated
365 // correctly.
367 $sql = "
368 SELECT ra.roleid, ra.userid, ra.contextid
369 FROM {$CFG->prefix}role_assignments ra
370 LEFT OUTER JOIN ({$CFG->prefix}context cn
371 JOIN {$CFG->prefix}course c ON cn.contextlevel = ".CONTEXT_COURSE." AND cn.instanceid = c.id)
372 ON ra.contextid = cn.id
373 WHERE ra.enrol = 'database'" .
374 ($have_role ? ' AND ra.roleid = '.$role->id : '') .
375 ($extcourses
376 ? " AND (c.id IS NULL OR c.{$CFG->enrol_localcoursefield} NOT IN (" . join(",", array_map(array(&$db, 'quote'), $extcourses)) . "))"
377 : '');
379 $ers = $db->Execute($sql);
380 if (!$ers) {
381 trigger_error($db->ErrorMsg() .' STATEMENT: '. $sql);
382 return false;
384 if ( $ers->RecordCount() > 0 ) {
385 while ($user_obj = rs_fetch_next_record($ers)) {
386 $roleid = $user_obj->roleid;
387 $user = $user_obj->userid;
388 $contextid = $user_obj->contextid;
389 if (role_unassign($roleid, $user, 0, $contextid)){
390 error_log( "Unassigned role {$roleid} from user $user in context $contextid");
391 } else {
392 error_log( "Failed unassign role {$roleid} from user $user in context $contextid");
395 rs_close($ers); // release the handle
397 commit_sql();
399 // we are done now, a bit of housekeeping
400 fix_course_sortorder();
402 $this->enrol_disconnect($enroldb);
403 return true;
406 /// Overide the get_access_icons() function
407 function get_access_icons($course) {
411 /// Overide the base config_form() function
412 function config_form($frm) {
413 global $CFG;
415 $vars = array('enrol_dbhost', 'enrol_dbuser', 'enrol_dbpass',
416 'enrol_dbname', 'enrol_dbtable',
417 'enrol_localcoursefield', 'enrol_localuserfield',
418 'enrol_remotecoursefield', 'enrol_remoteuserfield',
419 'enrol_db_autocreate', 'enrol_db_category', 'enrol_db_template',
420 'enrol_db_localrolefield', 'enrol_db_remoterolefield',
421 'enrol_remotecoursefield', 'enrol_remoteuserfield',
422 'enrol_db_ignorehiddencourse');
424 foreach ($vars as $var) {
425 if (!isset($frm->$var)) {
426 $frm->$var = '';
429 include("$CFG->dirroot/enrol/database/config.html");
432 /// Override the base process_config() function
433 function process_config($config) {
435 if (!isset($config->enrol_dbtype)) {
436 $config->enrol_dbtype = 'mysql';
438 set_config('enrol_dbtype', $config->enrol_dbtype);
440 if (!isset($config->enrol_dbhost)) {
441 $config->enrol_dbhost = '';
443 set_config('enrol_dbhost', $config->enrol_dbhost);
445 if (!isset($config->enrol_dbuser)) {
446 $config->enrol_dbuser = '';
448 set_config('enrol_dbuser', $config->enrol_dbuser);
450 if (!isset($config->enrol_dbpass)) {
451 $config->enrol_dbpass = '';
453 set_config('enrol_dbpass', $config->enrol_dbpass);
455 if (!isset($config->enrol_dbname)) {
456 $config->enrol_dbname = '';
458 set_config('enrol_dbname', $config->enrol_dbname);
460 if (!isset($config->enrol_dbtable)) {
461 $config->enrol_dbtable = '';
463 set_config('enrol_dbtable', $config->enrol_dbtable);
465 if (!isset($config->enrol_localcoursefield)) {
466 $config->enrol_localcoursefield = '';
468 set_config('enrol_localcoursefield', $config->enrol_localcoursefield);
470 if (!isset($config->enrol_localuserfield)) {
471 $config->enrol_localuserfield = '';
473 set_config('enrol_localuserfield', $config->enrol_localuserfield);
475 if (!isset($config->enrol_remotecoursefield)) {
476 $config->enrol_remotecoursefield = '';
478 set_config('enrol_remotecoursefield', $config->enrol_remotecoursefield);
480 if (!isset($config->enrol_remoteuserfield)) {
481 $config->enrol_remoteuserfield = '';
483 set_config('enrol_remoteuserfield', $config->enrol_remoteuserfield);
485 if (!isset($config->enrol_db_autocreate)) {
486 $config->enrol_db_autocreate = '';
488 set_config('enrol_db_autocreate', $config->enrol_db_autocreate);
490 if (!isset($config->enrol_db_category)) {
491 $config->enrol_db_category = '';
493 set_config('enrol_db_category', $config->enrol_db_category);
495 if (!isset($config->enrol_db_template)) {
496 $config->enrol_db_template = '';
498 set_config('enrol_db_template', $config->enrol_db_template);
500 if (!isset($config->enrol_db_defaultcourseroleid)) {
501 $config->enrol_db_defaultcourseroleid = '';
503 set_config('enrol_db_defaultcourseroleid', $config->enrol_db_defaultcourseroleid);
505 if (!isset($config->enrol_db_localrolefield)) {
506 $config->enrol_db_localrolefield = '';
508 set_config('enrol_db_localrolefield', $config->enrol_db_localrolefield);
510 if (!isset($config->enrol_db_remoterolefield)) {
511 $config->enrol_db_remoterolefield = '';
513 set_config('enrol_db_remoterolefield', $config->enrol_db_remoterolefield);
515 if (!isset($config->enrol_db_ignorehiddencourse)) {
516 $config->enrol_db_ignorehiddencourse = '';
518 set_config('enrol_db_ignorehiddencourse', $config->enrol_db_ignorehiddencourse );
520 return true;
523 // will create the moodle course from the template
524 // course_ext is an array as obtained from ldap -- flattened somewhat
525 // NOTE: if you pass true for $skip_fix_course_sortorder
526 // you will want to call fix_course_sortorder() after your are done
527 // with course creation
528 function create_course ($course,$skip_fix_course_sortorder=0){
529 global $CFG;
531 // define a template
532 if(!empty($CFG->enrol_db_template)){
533 $template = get_record("course", 'shortname', $CFG->enrol_db_template);
534 $template = (array)$template;
535 } else {
536 $site = get_site();
537 $template = array(
538 'startdate' => time() + 3600 * 24,
539 'summary' => get_string("defaultcoursesummary"),
540 'format' => "weeks",
541 'password' => "",
542 'guest' => 0,
543 'numsections' => 10,
544 'idnumber' => '',
545 'cost' => '',
546 'newsitems' => 5,
547 'showgrades' => 1,
548 'groupmode' => 0,
549 'groupmodeforce' => 0,
550 'student' => $site->student,
551 'students' => $site->students,
552 'teacher' => $site->teacher,
553 'teachers' => $site->teachers,
556 // overlay template
557 foreach (array_keys($template) AS $key) {
558 if (empty($course->$key)) {
559 $course->$key = $template[$key];
563 $course->category = 1; // the misc 'catch-all' category
564 if (!empty($CFG->enrol_db_category)){ //category = 0 or undef will break moodle
565 $course->category = $CFG->enrol_db_category;
568 // define the sortorder
569 $sort = get_field_sql('SELECT COALESCE(MAX(sortorder)+1, 100) AS max ' .
570 ' FROM ' . $CFG->prefix . 'course ' .
571 ' WHERE category=' . $course->category);
572 $course->sortorder = $sort;
574 // override with local data
575 $course->startdate = time() + 3600 * 24;
576 $course->timecreated = time();
577 $course->visible = 1;
579 // clear out id just in case
580 unset($course->id);
582 // truncate a few key fields
583 $course->idnumber = substr($course->idnumber, 0, 100);
584 $course->shortname = substr($course->shortname, 0, 15);
586 // store it and log
587 if ($newcourseid = insert_record("course", addslashes_object($course))) { // Set up new course
588 $section = NULL;
589 $section->course = $newcourseid; // Create a default section.
590 $section->section = 0;
591 $section->id = insert_record("course_sections", $section);
592 $page = page_create_object(PAGE_COURSE_VIEW, $newcourseid);
593 blocks_repopulate_page($page); // Return value no
596 if(!$skip_fix_course_sortorder){
597 fix_course_sortorder();
599 add_to_log($newcourseid, "course", "new", "view.php?id=$newcourseid", "enrol/database auto-creation");
600 } else {
601 trigger_error("Could not create new course $extcourse from from database");
602 notify("Serious Error! Could not create the new course!");
603 return false;
606 return $newcourseid;
609 /// DB Connect
610 /// NOTE: You MUST remember to disconnect
611 /// when you stop using it -- as this call will
612 /// sometimes modify $CFG->prefix for the whole of Moodle!
613 function enrol_connect() {
614 global $CFG;
616 // Try to connect to the external database (forcing new connection)
617 $enroldb = &ADONewConnection($CFG->enrol_dbtype);
618 if ($enroldb->Connect($CFG->enrol_dbhost, $CFG->enrol_dbuser, $CFG->enrol_dbpass, $CFG->enrol_dbname, true)) {
619 $enroldb->SetFetchMode(ADODB_FETCH_ASSOC); ///Set Assoc mode always after DB connection
620 return $enroldb;
621 } else {
622 trigger_error("Error connecting to enrolment DB backend with: "
623 . "$CFG->enrol_dbhost,$CFG->enrol_dbuser,$CFG->enrol_dbpass,$CFG->enrol_dbname");
624 return false;
628 /// DB Disconnect
629 function enrol_disconnect($enroldb) {
630 global $CFG;
632 $enroldb->Close();
636 * This function returns the name and value of the role field to query the db
637 * for, or null if there isn't one.
639 * @param object The ADOdb connection
640 * @param object The role
641 * @return array (boolean, string, db quoted string)
643 function role_fields($enroldb, $role) {
644 global $CFG;
646 if ($have_role = !empty($role)
647 && !empty($CFG->enrol_db_remoterolefield)
648 && !empty($CFG->enrol_db_localrolefield)
649 && !empty($role->{$CFG->enrol_db_localrolefield})) {
650 $remote_role_name = $CFG->enrol_db_remoterolefield;
651 $remote_role_value = $enroldb->quote($role->{$CFG->enrol_db_localrolefield});
652 } else {
653 $remote_role_name = $remote_role_value = null;
656 return array($have_role, $remote_role_name, $remote_role_value);
659 } // end of class