Index: enrol.php
===================================================================
--- enrol.php	(.../trunk/enrol/ldap/enrol.php)	(revision 76)
+++ enrol.php	(.../branches/enrol/ldap/enrol.php)	(revision 79)
@@ -54,7 +56,7 @@
 
         foreach ($enrolments as $enrol){
     
-            $course_ext_id = $enrol[$CFG->enrol_ldap_course_idnumber][0];
+            $course_ext_id = $enrol[strtolower($CFG->enrol_ldap_course_idnumber)][0];
             if(empty($course_ext_id)){
                 error_log("[ENROL_LDAP] The course external id is invalid!\n");
                 continue; // next; skip this one!
@@ -156,9 +158,6 @@
     if (!empty($CFG->enrol_ldap_course_summary)){
         array_push($ldap_fields_wanted, $CFG->enrol_ldap_course_summary);
     }
-    if($enrol){
-        array_push($ldap_fields_wanted, $CFG->{'enrol_ldap_memberattribute_role'.$role->id});
-    }
 
     // define the search pattern
     if (!empty($CFG->enrol_ldap_objectclass)){ 
@@ -171,20 +170,20 @@
     // first, pack the sortorder...
     fix_course_sortorder();
 
-    foreach ($ldap_contexts as $context) {
+    foreach ($ldap_contexts as $ldap_context) {
 
-        $context = trim($context);
+        $ldap_context = trim($ldap_context);
         if ($CFG->enrol_ldap_search_sub){
             //use ldap_search to find first user from subtree
             $ldap_result = @ldap_search($ldap_connection, 
-                                        $context, 
+                                        $ldap_context, 
                                         $ldap_search_pattern,
                                         $ldap_fields_wanted);
 
         } else {
             //search only in this context
             $ldap_result = @ldap_list($ldap_connection, 
-                                        $context, 
+                                        $ldap_context, 
                                         $ldap_search_pattern,
                                         $ldap_fields_wanted,0,0);
         }
@@ -205,15 +204,16 @@
         if (count($flat_records)) {
 
 
+            $idnumber = NULL;
             foreach($flat_records as $course){
-                $idnumber = $course{$CFG->enrol_ldap_course_idnumber}[0];
+                $idnumber = $course{strtolower($CFG->enrol_ldap_course_idnumber)}[0];
                 print "== Synching $idnumber\n";
                 // does the course exist in moodle already? 
                 $course_obj = false;
                 $course_obj = get_record( 'course',
                                           $this->enrol_localcoursefield,
                                           $idnumber );
-                if (!is_object($course_obj)) {
+                if (!is_object($course_obj) && $CFG->enrol_ldap_autocreate) {
                     // ok, now then let's create it!
                     print "Creating Course $idnumber...";
                     $newcourseid = $this->create_course($course, true); // we are skipping fix_course_sortorder()
@@ -227,7 +227,49 @@
 
                 // enrol&unenrol if required
                 if($enrol && is_object($course_obj)){
+                    $rangeStart = 0;
+                    $rangeLength = 0;
+                    $member = $CFG->{'enrol_ldap_memberattribute_role'.$role->id};
+                    $tempMembers = array('count' => 0);
+                    while ($rangeStart > -1) {
+                        if (1 == 1) { // MS-AD
+                            $member = $CFG->{'enrol_ldap_memberattribute_role'.$role->id}.';Range='.$rangeStart.'-'.(($rangeLength) ? ($rangeStart+$rangeLength-1) : '*');
+                        }
+                        $ldap_fields_wanted = array('dn', $member);
+                        if ($CFG->enrol_ldap_search_sub){
+                            //use ldap_search to find first group from subtree
+                            $ldap_result = @ldap_search($ldap_connection, $ldap_context, '(&('.$CFG->enrol_ldap_course_idnumber.'='.$idnumber.')'.$ldap_search_pattern.')', $ldap_fields_wanted);
+                        } else {
+                            //search only in this context
+                            $ldap_result = @ldap_list($ldap_connection, $ldap_context, '(&('.$CFG->enrol_ldap_course_idnumber.'='.$idnumber.')'.$ldap_search_pattern.')', $ldap_fields_wanted,0,0);
+                        }
+ 
+                        // check and push results
+                        $records = $ldap_result ? ldap_get_entries($ldap_connection,$ldap_result) : array('count' => 0);
+                        $record = $records[0];
 
+                        if (array_key_exists(strtolower($CFG->{'enrol_ldap_memberattribute_role'.$role->id}), $record)){
+                            $tempMembers = $record[strtolower($CFG->{'enrol_ldap_memberattribute_role'.$role->id})];
+                            $rangeStart = -1;
+                        } elseif (array_key_exists(strtolower($CFG->{'enrol_ldap_memberattribute_role'.$role->id}.';Range='.$rangeStart.'-*'), $record)) {
+                            $record[strtolower($CFG->{'enrol_ldap_memberattribute_role'.$role->id}.';Range='.$rangeStart.'-*')]['count'] += $tempMembers['count'];
+                            unset($tempMembers['count']);
+                            $tempMembers = array_merge($tempMembers, $record[strtolower($CFG->{'enrol_ldap_memberattribute_role'.$role->id}.';Range='.$rangeStart.'-*')]);
+                            $rangeStart = -1;
+                        } elseif ($rangeLength == 0) {
+                            $rangeLength = 100;
+                        } elseif (array_key_exists(strtolower($CFG->{'enrol_ldap_memberattribute_role'.$role->id}.';Range='.$rangeStart.'-'.($rangeStart+$rangeLength-1)), $record)) {
+                            $record[strtolower($CFG->{'enrol_ldap_memberattribute_role'.$role->id}.'Range='.$rangeStart.'-'.($rangeStart+$rangeLength-1))]['count'] += $tempMembers['count'];
+                            unset($tempMembers['count']);
+                            $tempMembers = array_merge($tempMembers, $record[strtolower($CFG->{'enrol_ldap_memberattribute_role'.$role->id}.';Range='.$rangeStart.'-'.($rangeStart+$rangeLength-1))]);
+                            $rangeStart = $rangeStart + $rangeLength;
+                        } else {
+                            // Failed to find anything!
+                            $rangeStart = -1;
+                        }
+                    }
+                    $course[strtolower($CFG->{'enrol_ldap_memberattribute_role'.$role->id})] = $tempMembers;
+
                     // Get a context object.
                     $context = get_context_instance(CONTEXT_COURSE, $course_obj->id);
 
@@ -244,6 +286,26 @@
                         $ldapmembers = addslashes_recursive($ldapmembers);
                     }
                     
+                    $idnumber_field = get_config('auth/cas', 'field_map_idnumber');
+                    if (!$idnumber_field) {
+                        $idnumber_field = get_config('auth/ldap', 'field_map_idnumber');
+                    }
+                    if (!empty($idnumber_field) && strtolower($idnumber_field) != "dn") {
+                        $tempmembers = array();
+                        $ldap_fields_wanted = array('dn', $idnumber_field);
+                        foreach($ldapmembers as $ldapmember) { 
+                            $ldap_result = @ldap_read($ldap_connection, $ldapmember, '(objectclass=*)', $ldap_fields_wanted);
+                            $record = $ldap_result ? ldap_get_entries($ldap_connection,$ldap_result) : array('count' => 0);
+                            $tempmember = NULL;
+                            $tempmember = $record[0][strtolower($idnumber_field)][0];
+                            if ($this->isbinary($tempmember)) {
+                              $tempmember = $this->escape_for_ad($tempmember);
+                            }
+                            $tempmembers[] = $tempmember;
+                        }
+                        $ldapmembers = $tempmembers;
+                    }
+
                     // prune old ldap enrolments
                     // hopefully they'll fit in the max buffer size for the RDBMS
                     $sql = '
@@ -254,7 +316,7 @@
                          AND enr.contextid = '.$context->id.'
                          AND enr.enrol = \'ldap\' ';
                     if (!empty($ldapmembers)) {
-                        $sql .= 'AND usr.idnumber NOT IN (\''. join('\',\'', $ldapmembers).'\')';
+                        $sql .= 'AND usr.idnumber NOT IN (\''. join('\',\'', addslashes_recursive($ldapmembers)).'\')';
                     } else {
                         print ("Empty enrolment for $course_obj->shortname \n");
                     }
@@ -275,7 +337,7 @@
                     // bad we can't do INSERT IGNORE with postgres...
                     foreach ($ldapmembers as $ldapmember) {
                         $sql = 'SELECT id,1 FROM '.$CFG->prefix.'user '
-                                ." WHERE idnumber='$ldapmember'";
+                                ." WHERE idnumber='".addslashes($ldapmember)."'";
                         $member = get_record_sql($sql); 
 //                        print "sql: $sql \nidnumber = ".stripslashes($ldapmember)." \n".var_dump($member); 
                         if(empty($member) || empty($member->id)){
@@ -380,11 +442,6 @@
     }
     set_config('enrol_ldap_course_idnumber', $config->enrol_ldap_course_idnumber); 
     
-    if (!isset ($config->enrol_localcoursefield)) {
-        $config->enrol_localcoursefield = '';
-    }
-    set_config('enrol_localcoursefield', $config->enrol_localcoursefield);
-    
     if (!isset ($config->enrol_ldap_user_memberfield)) {
         $config->enrol_ldap_user_memberfield = '';
     }
@@ -671,6 +819,32 @@
     }
 }
 
+function isbinary($input)
+{
+    $isbinary = 0;
+    for($x=0;$x < strlen($input); $x++) {
+        $c = substr($input,$x,1);
+        if($c < chr(32) || $c > chr(127)) {
+            if($c != chr(10) && $c != chr(13) && $c != chr(9)) {
+                $isbinary = 1;
+                break;
+            }
+        }
+    }
+    return $isbinary;
+}
+
+function escape_for_ad($input)
+{
+    $new_input = implode('', unpack('H*', $input));
+    $i = 0;
+    $v = '';
+    for ($i=0; $i<strlen($new_input); $i = $i + 2) {
+        $v = $v . '\\' . substr($new_input, $i, 2);
+    }
+    return $v;
+}
+
 } // end of class
 
 ?>
