MDL-11515:
[moodle-linuxchix.git] / auth / cas / auth.php
blobff01fa9a3925808216a2ed3eaa1c2563d2057e21
1 <?php
2 /**
3 * @author Martin Dougiamas
4 * @authro Jerome GUTIERREZ
5 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
6 * @package moodle multiauth
8 * Authentication Plugin: CAS Authentication
10 * Authentication using CAS (Central Authentication Server).
12 * 2006-08-28 File created.
14 if (!defined('MOODLE_INTERNAL')) {
15 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
17 require_once($CFG->libdir.'/authlib.php');
18 require_once($CFG->dirroot.'/auth/cas/CAS/CAS.php');
19 /**
20 * CAS authentication plugin.
22 class auth_plugin_cas extends auth_plugin_base {
23 /**
24 * Constructor.
26 function auth_plugin_cas() {
27 $this->authtype = 'cas';
28 $this->config = get_config('auth/cas');
29 if (empty($this->config->ldapencoding)) {
30 $this->config->ldapencoding = 'utf-8';
32 if (empty($this->config->user_type)) {
33 $this->config->user_type = 'default';
35 $default = $this->ldap_getdefaults();
36 //use defaults if values not given
37 foreach ($default as $key => $value) {
38 // watch out - 0, false are correct values too
39 if (!isset($this->config->{$key}) or $this->config->{$key} == '') {
40 $this->config->{$key} = $value[$this->config->user_type];
43 //hack prefix to objectclass
44 if (empty($this->config->objectclass)) { // Can't send empty filter
45 $this->config->objectclass='objectClass=*';
46 } else if (strpos($this->config->objectclass, 'objectClass=') !== 0) {
47 $this->config->objectclass = 'objectClass='.$this->config->objectclass;
50 /**
51 * Authenticates user againt CAS
52 * Returns true if the username and password work and false if they are
53 * wrong or don't exist.
55 * @param string $username The username
56 * @param string $password The password
57 * @return bool Authentication success or failure.
59 function user_login ($username, $password) {
60 $this->connectCAS();
61 return phpCAS::isAuthenticated();
63 /**
64 * Returns true if this authentication plugin is 'internal'.
66 * @return bool
68 function is_internal() {
69 return false;
71 /**
72 * Returns true if this authentication plugin can change the user's
73 * password.
75 * @return bool
77 function can_change_password() {
78 return false;
80 /**
81 * authentication choice (CAS or other)
82 * redirection to the CAS form or to login/index.php
83 * for other authentication
85 function loginpage_hook() {
86 global $frm;
87 global $CFG;
88 global $SESSION;
90 $site = get_site();
91 $CASform = get_string("CASform","auth");
92 $username = optional_param("username");
94 if (!empty($username)) {
95 if (strstr($SESSION->wantsurl,'ticket') || strstr($SESSION->wantsurl,'NOCAS'))
96 unset($SESSION->wantsurl);
97 return;
102 // Test si cas activ� et param�tres non remplis
103 if (empty($this->config->hostname)) {
104 return;
107 // Connection to CAS server
108 $this->connectCAS();
110 // Gestion de la connection CAS si acc�s direct d'un ent ou autre
111 if (phpCAS::checkAuthentication()) {
112 $frm->username=phpCAS::getUser();
113 // if (phpCAS::getUser()=='esup9992')
114 // $frm->username='erhar0062';
115 $frm->password="passwdCas";
116 return;
119 if ($_GET["loginguest"]== true) {
120 $frm->username="guest";
121 $frm->password="guest";
122 return;
125 if ($this->config->multiauth) {
126 $authCAS = optional_param("authCAS");
127 if ($authCAS=="NOCAS")
128 return;
130 // choice authentication form for multi-authentication
131 // test pgtIou parameter for proxy mode (https connection
132 // in background from CAS server to the php server)
133 if ($authCAS!="CAS" && !isset($_GET["pgtIou"])) {
134 $navlinks = array();
135 $navlinks[] = array('name' => $CASform, 'link' => null, 'type' => 'misc');
136 $navigation = build_navigation($navlinks);
138 print_header("$site->fullname: $CASform", $site->fullname, $navigation);
139 include($CFG->dirroot."/auth/cas/cas_form.html");
140 print_footer();
141 exit();
144 // CAS authentication
145 if (!phpCAS::isAuthenticated())
146 {phpCAS::forceAuthentication();}
149 * logout from the cas
151 * This function is called from admin/auth.php
154 function prelogout_hook() {
155 global $CFG;
156 if ($this->config->logoutcas ) {
157 $backurl = $CFG->wwwroot;
158 $this->connectCAS();
159 phpCAS::logout($backurl);
163 * Connect to the cas (clientcas connection or proxycas connection
165 * This function is called from admin/auth.php
168 function connectCAS() {
170 global $PHPCAS_CLIENT;
171 // mode proxy CAS
172 if ( !is_object($PHPCAS_CLIENT) ) {
173 if ($this->config->proxycas) {
174 phpCAS::proxy($this->config->casversion, $this-> config->hostname, (int) $this->config->port, $this->config->baseuri);
176 // mode client CAS
177 else {
178 phpCAS::client($this->config->casversion, $this-> config->hostname, (int) $this->config->port, $this->config->baseuri);
184 * Prints a form for configuring this authentication plugin.
186 * This function is called from admin/auth.php, and outputs a full page with
187 * a form for configuring this plugin.
189 * @param array $page An object containing all the data for this page.
191 function config_form($config, $err, $user_fields) {
192 include 'config.html';
195 * Returns the URL for changing the user's pw, or empty if the default can
196 * be used.
198 * @return string
200 function change_password_url() {
201 return "";
204 * returns predefined usertypes
206 * @return array of predefined usertypes
208 function ldap_suppported_usertypes() {
209 $types = array();
210 $types['edir']='Novell Edirectory';
211 $types['rfc2307']='posixAccount (rfc2307)';
212 $types['rfc2307bis']='posixAccount (rfc2307bis)';
213 $types['samba']='sambaSamAccount (v.3.0.7)';
214 $types['ad']='MS ActiveDirectory';
215 $types['default']=get_string('default');
216 return $types;
219 * Processes and stores configuration data for this authentication plugin.
221 function process_config($config) {
222 // set to defaults if undefined
223 // CAS settings
224 if (!isset ($config->hostname))
225 $config->hostname = '';
226 if (!isset ($config->port))
227 $config->port = '';
228 if (!isset ($config->casversion))
229 $config->casversion = '';
230 if (!isset ($config->baseuri))
231 $config->baseuri = '';
232 if (!isset ($config->language))
233 $config->language = '';
234 if (!isset ($config->proxycas))
235 $config->proxycas = '';
236 if (!isset ($config->logoutcas))
237 $config->logoutcas = '';
238 if (!isset ($config->multiauth))
239 $config->multiauth = '';
240 // LDAP settings
241 if (!isset($config->host_url))
242 { $config->host_url = ''; }
243 if (empty($config->ldapencoding))
244 { $config->ldapencoding = 'utf-8'; }
245 if (!isset($config->contexts))
246 { $config->contexts = ''; }
247 if (!isset($config->user_type))
248 { $config->user_type = 'default'; }
249 if (!isset($config->user_attribute))
250 { $config->user_attribute = ''; }
251 if (!isset($config->search_sub))
252 { $config->search_sub = ''; }
253 if (!isset($config->opt_deref))
254 { $config->opt_deref = ''; }
255 if (!isset($config->bind_dn))
256 {$config->bind_dn = ''; }
257 if (!isset($config->bind_pw))
258 {$config->bind_pw = ''; }
259 if (!isset($config->version))
260 {$config->version = '2'; }
261 if (!isset($config->objectclass))
262 {$config->objectclass = ''; }
263 if (!isset($config->memberattribute))
264 {$config->memberattribute = ''; }
265 if (!isset($config->memberattribute_isdn))
266 {$config->memberattribute_isdn = ''; }
267 if (!isset($config->attrcreators))
268 {$config->attrcreators = ''; }
269 if (!isset($config->groupecreators))
270 {$config->groupecreators = ''; }
271 if (!isset($config->removeuser))
272 {$config->removeuser = 0; }
273 // save CAS settings
274 set_config('hostname', $config->hostname, 'auth/cas');
275 set_config('port', $config->port, 'auth/cas');
276 set_config('casversion', $config->casversion, 'auth/cas');
277 set_config('baseuri', $config->baseuri, 'auth/cas');
278 set_config('language', $config->language, 'auth/cas');
279 set_config('proxycas', $config->proxycas, 'auth/cas');
280 set_config('logoutcas', $config->logoutcas, 'auth/cas');
281 set_config('multiauth', $config->multiauth, 'auth/cas');
282 // save LDAP settings
283 set_config('host_url', $config->host_url, 'auth/cas');
284 set_config('ldapencoding', $config->ldapencoding, 'auth/cas');
285 set_config('host_url', $config->host_url, 'auth/cas');
286 set_config('contexts', $config->contexts, 'auth/cas');
287 set_config('user_type', $config->user_type, 'auth/cas');
288 set_config('user_attribute', $config->user_attribute, 'auth/cas');
289 set_config('search_sub', $config->search_sub, 'auth/cas');
290 set_config('opt_deref', $config->opt_deref, 'auth/cas');
291 set_config('bind_dn', $config->bind_dn, 'auth/cas');
292 set_config('bind_pw', $config->bind_pw, 'auth/cas');
293 set_config('version', $config->version, 'auth/cas');
294 set_config('objectclass', $config->objectclass, 'auth/cas');
295 set_config('memberattribute', $config->memberattribute, 'auth/cas');
296 set_config('memberattribute_isdn', $config->memberattribute_isdn, 'auth/cas');
297 set_config('attrcreators', $config->attrcreators, 'auth/cas');
298 set_config('groupecreators', $config->groupecreators, 'auth/cas');
299 set_config('removeuser', $config->removeuser, 'auth/cas');
300 return true;
303 * Initializes needed ldap variables for cas-module
305 * Uses names defined in ldap_supported_usertypes.
306 * $default is first defined as:
307 * $default['pseudoname'] = array(
308 * 'typename1' => 'value',
309 * 'typename2' => 'value'
310 * ....
311 * );
313 * @return array of default values
315 function ldap_getdefaults() {
316 $default['objectclass'] = array(
317 'edir' => 'User',
318 'rfc2307' => 'posixAccount',
319 'rfc2307bis' => 'posixAccount',
320 'samba' => 'sambaSamAccount',
321 'ad' => 'user',
322 'default' => '*'
324 $default['user_attribute'] = array(
325 'edir' => 'cn',
326 'rfc2307' => 'uid',
327 'rfc2307bis' => 'uid',
328 'samba' => 'uid',
329 'ad' => 'cn',
330 'default' => 'cn'
332 $default['memberattribute'] = array(
333 'edir' => 'member',
334 'rfc2307' => 'member',
335 'rfc2307bis' => 'member',
336 'samba' => 'member',
337 'ad' => 'member',
338 'default' => 'member'
340 $default['memberattribute_isdn'] = array(
341 'edir' => '1',
342 'rfc2307' => '0',
343 'rfc2307bis' => '1',
344 'samba' => '0', //is this right?
345 'ad' => '1',
346 'default' => '0'
348 return $default;
351 * reads userinformation from ldap and return it in array()
353 * Read user information from external database and returns it as array().
354 * Function should return all information available. If you are saving
355 * this information to moodle user-table you should honor syncronization flags
357 * @param string $username username (with system magic quotes)
359 * @return mixed array with no magic quotes or false on error
361 function get_userinfo($username) {
362 $textlib = textlib_get_instance();
363 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
364 $ldapconnection = $this->ldap_connect();
365 $attrmap = $this->ldap_attributes();
366 $result = array();
367 $search_attribs = array();
368 foreach ($attrmap as $key=>$values) {
369 if (!is_array($values)) {
370 $values = array($values);
372 foreach ($values as $value) {
373 if (!in_array($value, $search_attribs)) {
374 array_push($search_attribs, $value);
378 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
379 if (!$user_info_result = ldap_read($ldapconnection, $user_dn, $this->config->objectclass, $search_attribs)) {
380 return false; // error!
382 $user_entry = $this->ldap_get_entries($ldapconnection, $user_info_result);
383 if (empty($user_entry)) {
384 return false; // entry not found
386 foreach ($attrmap as $key=>$values) {
387 if (!is_array($values)) {
388 $values = array($values);
390 $ldapval = NULL;
391 foreach ($values as $value) {
392 if ($value == 'dn') {
393 $result[$key] = $user_dn;
395 if (!array_key_exists(strtolower($value), $user_entry[0])) {
396 continue; // wrong data mapping!
398 if (is_array($user_entry[0][strtolower($value)])) {
399 $newval = $textlib->convert($user_entry[0][strtolower($value)][0], $this->config->ldapencoding, 'utf-8');
400 } else {
401 $newval = $textlib->convert($user_entry[0][strtolower($value)], $this->config->ldapencoding, 'utf-8');
404 if (!empty($newval)) { // favour ldap entries that are set
405 $ldapval = $newval;
408 if (!is_null($ldapval)) {
409 $result[$key] = $ldapval;
412 @ldap_close($ldapconnection);
413 return $result;
416 * reads userinformation from ldap and return it in an object
418 * @param string $username username (with system magic quotes)
419 * @return mixed object or false on error
421 function get_userinfo_asobj($username) {
422 $user_array = $this->get_userinfo($username);
423 if ($user_array == false) {
424 return false; //error or not found
426 $user_array = truncate_userinfo($user_array);
427 $user = new object();
428 foreach ($user_array as $key=>$value) {
429 $user->{$key} = $value;
431 return $user;
434 * connects to ldap server
436 * Tries connect to specified ldap servers.
437 * Returns connection result or error.
439 * @return connection result
441 function ldap_connect($binddn='',$bindpwd='') {
442 //Select bind password, With empty values use
443 //ldap_bind_* variables or anonymous bind if ldap_bind_* are empty
444 if ($binddn == '' and $bindpwd == '') {
445 if (!empty($this->config->bind_dn)) {
446 $binddn = $this->config->bind_dn;
448 if (!empty($this->config->bind_pw)) {
449 $bindpwd = $this->config->bind_pw;
452 $urls = explode(";",$this->config->host_url);
453 foreach ($urls as $server) {
454 $server = trim($server);
455 if (empty($server)) {
456 continue;
458 $connresult = ldap_connect($server);
459 //ldap_connect returns ALWAYS true
460 if (!empty($this->config->version)) {
461 ldap_set_option($connresult, LDAP_OPT_PROTOCOL_VERSION, $this->config->version);
463 if (!empty($binddn)) {
464 //bind with search-user
465 //$debuginfo .= 'Using bind user'.$binddn.'and password:'.$bindpwd;
466 $bindresult=ldap_bind($connresult, $binddn,$bindpwd);
468 else {
469 //bind anonymously
470 $bindresult=@ldap_bind($connresult);
472 if (!empty($this->config->opt_deref)) {
473 ldap_set_option($connresult, LDAP_OPT_DEREF, $this->config->opt_deref);
475 if ($bindresult) {
476 return $connresult;
478 $debuginfo .= "<br/>Server: '$server' <br/> Connection: '$connresult'<br/> Bind result: '$bindresult'</br>";
480 //If any of servers are alive we have already returned connection
481 print_error('auth_ldap_noconnect_all','auth',$this->config->user_type);
482 return false;
485 * retuns user attribute mappings between moodle and ldap
487 * @return array
489 function ldap_attributes () {
490 $fields = array("firstname", "lastname", "email", "phone1", "phone2",
491 "department", "address", "city", "country", "description",
492 "idnumber", "lang" );
493 $moodleattributes = array();
494 foreach ($fields as $field) {
495 if (!empty($this->config->{"field_map_$field"})) {
496 $moodleattributes[$field] = $this->config->{"field_map_$field"};
497 if (preg_match('/,/',$moodleattributes[$field])) {
498 $moodleattributes[$field] = explode(',', $moodleattributes[$field]); // split ?
502 $moodleattributes['username'] = $this->config->user_attribute;
503 return $moodleattributes;
506 * retuns dn of username
508 * Search specified contexts for username and return user dn
509 * like: cn=username,ou=suborg,o=org
511 * @param mixed $ldapconnection $ldapconnection result
512 * @param mixed $username username (external encoding no slashes)
515 function ldap_find_userdn ($ldapconnection, $extusername) {
516 //default return value
517 $ldap_user_dn = FALSE;
518 //get all contexts and look for first matching user
519 $ldap_contexts = explode(";",$this->config->contexts);
520 if (!empty($this->config->create_context)) {
521 array_push($ldap_contexts, $this->config->create_context);
523 foreach ($ldap_contexts as $context) {
524 $context = trim($context);
525 if (empty($context)) {
526 continue;
528 if ($this->config->search_sub) {
529 //use ldap_search to find first user from subtree
530 $ldap_result = ldap_search($ldapconnection, $context, "(".$this->config->user_attribute."=".$this->filter_addslashes($extusername).")",array($this->config->user_attribute));
532 else {
533 //search only in this context
534 $ldap_result = ldap_list($ldapconnection, $context, "(".$this->config->user_attribute."=".$this->filter_addslashes($extusername).")",array($this->config->user_attribute));
536 $entry = ldap_first_entry($ldapconnection,$ldap_result);
537 if ($entry) {
538 $ldap_user_dn = ldap_get_dn($ldapconnection, $entry);
539 break ;
542 return $ldap_user_dn;
545 * Quote control characters in quoted "texts" used in ldap
547 * @param string
549 function ldap_addslashes($text) {
550 $text = str_replace('\\', '\\\\', $text);
551 $text = str_replace(array('"', "\0"),
552 array('\\"', '\\00'), $text);
553 return $text;
556 * returns all usernames from external database
558 * get_userlist returns all usernames from external database
560 * @return array
562 function get_userlist() {
563 return $this->ldap_get_userlist("({$this->config->user_attribute}=*)");
566 * checks if user exists on external db
568 * @param string $username (with system magic quotes)
570 function user_exists($username) {
571 $textlib = textlib_get_instance();
572 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
573 //returns true if given username exist on ldap
574 $users = $this->ldap_get_userlist("({$this->config->user_attribute}=".$this->filter_addslashes($extusername).")");
575 return count($users);
578 * syncronizes user fron external db to moodle user table
580 * Sync is now using username attribute.
582 * Syncing users removes or suspends users that dont exists anymore in external db.
583 * Creates new users and updates coursecreator status of users.
585 * @param int $bulk_insert_records will insert $bulkinsert_records per insert statement
586 * valid only with $unsafe. increase to a couple thousand for
587 * blinding fast inserts -- but test it: you may hit mysqld's
588 * max_allowed_packet limit.
589 * @param bool $do_updates will do pull in data updates from ldap if relevant
591 function sync_users ($bulk_insert_records = 1000, $do_updates = true) {
592 global $CFG;
593 $textlib = textlib_get_instance();
594 $droptablesql = array(); /// sql commands to drop the table (because session scope could be a problem for
595 /// some persistent drivers like ODBTP (mssql) or if this function is invoked
596 /// from within a PHP application using persistent connections
597 // configure a temp table
598 print "Configuring temp table\n";
599 switch (strtolower($CFG->dbfamily)) {
600 case 'mysql':
601 $temptable = $CFG->prefix . 'extuser';
602 $droptablesql[] = 'DROP TEMPORARY TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
603 execute_sql_arr($droptablesql, true, false); /// Drop temp table to avoid persistence problems later
604 echo "Creating temp table $temptable\n";
605 execute_sql('CREATE TEMPORARY TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username)) TYPE=MyISAM', false);
606 break;
607 case 'postgres':
608 $temptable = $CFG->prefix . 'extuser';
609 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
610 execute_sql_arr($droptablesql, true, false); /// Drop temp table to avoid persistence problems later
611 echo "Creating temp table $temptable\n";
612 $bulk_insert_records = 1; // no support for multiple sets of values
613 execute_sql('CREATE TEMPORARY TABLE '. $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))', false);
614 break;
615 case 'mssql':
616 $temptable = '#'.$CFG->prefix . 'extuser'; /// MSSQL temp tables begin with #
617 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
618 execute_sql_arr($droptablesql, true, false); /// Drop temp table to avoid persistence problems later
619 echo "Creating temp table $temptable\n";
620 $bulk_insert_records = 1; // no support for multiple sets of values
621 execute_sql('CREATE TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))', false);
622 break;
623 case 'oracle':
624 $temptable = $CFG->prefix . 'extuser';
625 $droptablesql[] = 'TRUNCATE TABLE ' . $temptable; // oracle requires truncate before being able to drop a temp table
626 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
627 execute_sql_arr($droptablesql, true, false); /// Drop temp table to avoid persistence problems later
628 echo "Creating temp table $temptable\n";
629 $bulk_insert_records = 1; // no support for multiple sets of values
630 execute_sql('CREATE GLOBAL TEMPORARY TABLE '.$temptable.' (username VARCHAR(64), PRIMARY KEY (username)) ON COMMIT PRESERVE ROWS', false);
631 break;
633 print "Connecting to ldap...\n";
634 $ldapconnection = $this->ldap_connect();
635 if (!$ldapconnection) {
636 @ldap_close($ldapconnection);
637 print get_string('auth_ldap_noconnect','auth',$this->config->host_url);
638 exit;
640 ////
641 //// get user's list from ldap to sql in a scalable fashion
642 ////
643 // prepare some data we'll need
644 $filter = "(&(".$this->config->user_attribute."=*)(".$this->config->objectclass."))";
645 $contexts = explode(";",$this->config->contexts);
646 if (!empty($this->config->create_context)) {
647 array_push($contexts, $this->config->create_context);
649 $fresult = array();
650 foreach ($contexts as $context) {
651 $context = trim($context);
652 if (empty($context)) {
653 continue;
655 begin_sql();
656 if ($this->config->search_sub) {
657 //use ldap_search to find first user from subtree
658 $ldap_result = ldap_search($ldapconnection, $context,
659 $filter,
660 array($this->config->user_attribute));
661 } else {
662 //search only in this context
663 $ldap_result = ldap_list($ldapconnection, $context,
664 $filter,
665 array($this->config->user_attribute));
667 if ($entry = ldap_first_entry($ldapconnection, $ldap_result)) {
668 do {
669 $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
670 $value = $textlib->convert($value[0], $this->config->ldapencoding, 'utf-8');
671 array_push($fresult, $value);
672 if (count($fresult) >= $bulk_insert_records) {
673 $this->ldap_bulk_insert($fresult, $temptable);
674 $fresult = array();
676 } while ($entry = ldap_next_entry($ldapconnection, $entry));
678 unset($ldap_result); // free mem
679 // insert any remaining users and release mem
680 if (count($fresult)) {
681 $this->ldap_bulk_insert($fresult, $temptable);
682 $fresult = array();
684 commit_sql();
686 /// preserve our user database
687 /// if the temp table is empty, it probably means that something went wrong, exit
688 /// so as to avoid mass deletion of users; which is hard to undo
689 $count = get_record_sql('SELECT COUNT(username) AS count, 1 FROM ' . $temptable);
690 $count = $count->{'count'};
691 if ($count < 1) {
692 print "Did not get any users from LDAP -- error? -- exiting\n";
693 exit;
694 } else {
695 print "Got $count records from LDAP\n\n";
697 /// User removal
698 // find users in DB that aren't in ldap -- to be removed!
699 // this is still not as scalable (but how often do we mass delete?)
700 if (!empty($this->config->removeuser)) {
701 $sql = "SELECT u.id, u.username, u.email
702 FROM {$CFG->prefix}user u
703 LEFT JOIN $temptable e ON u.username = e.username
704 WHERE u.auth='cas'
705 AND u.deleted=0
706 AND e.username IS NULL";
707 $remove_users = get_records_sql($sql);
708 if (!empty($remove_users)) {
709 print "User entries to remove: ". count($remove_users) . "\n";
710 foreach ($remove_users as $user) {
711 if ($this->config->removeuser == 2) {
712 if (delete_user($user)) {
713 echo "\t"; print_string('auth_dbdeleteuser', 'auth', array($user->username, $user->id)); echo "\n";
714 } else {
715 echo "\t"; print_string('auth_dbdeleteusererror', 'auth', $user->username); echo "\n";
717 } else if ($this->config->removeuser == 1) {
718 $updateuser = new object();
719 $updateuser->id = $user->id;
720 $updateuser->auth = 'nologin';
721 if (update_record('user', $updateuser)) {
722 echo "\t"; print_string('auth_dbsuspenduser', 'auth', array($user->username, $user->id)); echo "\n";
723 } else {
724 echo "\t"; print_string('auth_dbsuspendusererror', 'auth', $user->username); echo "\n";
728 } else {
729 print "No user entries to be removed\n";
731 unset($remove_users); // free mem!
733 /// Revive suspended users
734 if (!empty($this->config->removeuser) and $this->config->removeuser == 1) {
735 $sql = "SELECT u.id, u.username
736 FROM $temptable e, {$CFG->prefix}user u
737 WHERE e.username=u.username
738 AND u.auth='nologin'";
739 $revive_users = get_records_sql($sql);
740 if (!empty($revive_users)) {
741 print "User entries to be revived: ". count($revive_users) . "\n";
742 begin_sql();
743 foreach ($revive_users as $user) {
744 $updateuser = new object();
745 $updateuser->id = $user->id;
746 $updateuser->auth = 'cas';
747 if (update_record('user', $updateuser)) {
748 echo "\t"; print_string('auth_dbreviveser', 'auth', array($user->username, $user->id)); echo "\n";
749 } else {
750 echo "\t"; print_string('auth_dbreviveusererror', 'auth', $user->username); echo "\n";
753 commit_sql();
754 } else {
755 print "No user entries to be revived\n";
757 unset($revive_users);
759 /// User Updates - time-consuming (optional)
760 if ($do_updates) {
761 // narrow down what fields we need to update
762 $all_keys = array_keys(get_object_vars($this->config));
763 $updatekeys = array();
764 foreach ($all_keys as $key) {
765 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
766 // if we have a field to update it from
767 // and it must be updated 'onlogin' we
768 // update it on cron
769 if ( !empty($this->config->{'field_map_'.$match[1]})
770 and $this->config->{$match[0]} === 'onlogin') {
771 array_push($updatekeys, $match[1]); // the actual key name
775 // print_r($all_keys); print_r($updatekeys);
776 unset($all_keys); unset($key);
777 } else {
778 print "No updates to be done\n";
780 if ( $do_updates and !empty($updatekeys) ) { // run updates only if relevant
781 $users = get_records_sql("SELECT u.username, u.id
782 FROM {$CFG->prefix}user u
783 WHERE u.deleted=0 AND u.auth='cas'");
784 if (!empty($users)) {
785 print "User entries to update: ". count($users). "\n";
786 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
787 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
788 and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
789 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
790 } else {
791 $creatorrole = false;
793 begin_sql();
794 $xcount = 0;
795 $maxxcount = 100;
796 foreach ($users as $user) {
797 echo "\t"; print_string('auth_dbupdatinguser', 'auth', array($user->username, $user->id));
798 if (!$this->update_user_record(addslashes($user->username), $updatekeys)) {
799 echo " - ".get_string('skipped');
801 echo "\n";
802 $xcount++;
803 // update course creators if needed
804 if ($creatorrole !== false) {
805 if ($this->iscreator($user->username)) {
806 role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'cas');
807 } else {
808 role_unassign($creatorrole->id, $user->id, 0, $sitecontext->id, 'cas');
811 if ($xcount++ > $maxxcount) {
812 commit_sql();
813 begin_sql();
814 $xcount = 0;
817 commit_sql();
818 unset($users); // free mem
820 } else { // end do updates
821 print "No updates to be done\n";
823 /// User Additions
824 // find users missing in DB that are in LDAP
825 // note that get_records_sql wants at least 2 fields returned,
826 // and gives me a nifty object I don't want.
827 // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
828 $sql = "SELECT e.username, e.username
829 FROM $temptable e LEFT JOIN {$CFG->prefix}user u ON e.username = u.username
830 WHERE u.id IS NULL";
831 $add_users = get_records_sql($sql); // get rid of the fat
832 if (!empty($add_users)) {
833 print "User entries to add: ". count($add_users). "\n";
834 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
835 if (!empty($this->config->creators) and !empty($this->config->memberattribute)
836 and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
837 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
838 } else {
839 $creatorrole = false;
841 begin_sql();
842 foreach ($add_users as $user) {
843 $user = $this->get_userinfo_asobj(addslashes($user->username));
844 // prep a few params
845 $user->modified = time();
846 $user->confirmed = 1;
847 $user->auth = 'cas';
848 $user->mnethostid = $CFG->mnet_localhost_id;
849 if (empty($user->lang)) {
850 $user->lang = $CFG->lang;
852 $user = addslashes_recursive($user);
853 if ($id = insert_record('user',$user)) {
854 echo "\t"; print_string('auth_dbinsertuser', 'auth', array(stripslashes($user->username), $id)); echo "\n";
855 $userobj = $this->update_user_record($user->username);
856 if (!empty($this->config->forcechangepassword)) {
857 set_user_preference('auth_forcepasswordchange', 1, $userobj->id);
859 } else {
860 echo "\t"; print_string('auth_dbinsertusererror', 'auth', $user->username); echo "\n";
862 // add course creators if needed
863 if ($creatorrole !== false and $this->iscreator(stripslashes($user->username))) {
864 role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'cas');
867 commit_sql();
868 unset($add_users); // free mem
869 } else {
870 print "No users to be added\n";
872 return true;
875 * Update a local user record from an external source.
876 * This is a lighter version of the one in moodlelib -- won't do
877 * expensive ops such as enrolment.
879 * If you don't pass $updatekeys, there is a performance hit and
880 * values removed from LDAP won't be removed from moodle.
882 * @param string $username username (with system magic quotes)
884 function update_user_record($username, $updatekeys = false) {
885 global $CFG;
886 //just in case check text case
887 $username = trim(moodle_strtolower($username));
888 // get the current user record
889 $user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id);
890 if (empty($user)) { // trouble
891 error_log("Cannot update non-existent user: ".stripslashes($username));
892 print_error('auth_dbusernotexist','auth',$username);
893 die;
895 // Protect the userid from being overwritten
896 $userid = $user->id;
897 if ($newinfo = $this->get_userinfo($username)) {
898 $newinfo = truncate_userinfo($newinfo);
899 if (empty($updatekeys)) { // all keys? this does not support removing values
900 $updatekeys = array_keys($newinfo);
902 foreach ($updatekeys as $key) {
903 if (isset($newinfo[$key])) {
904 $value = $newinfo[$key];
905 } else {
906 $value = '';
908 if (!empty($this->config->{'field_updatelocal_' . $key})) {
909 if ($user->{$key} != $value) { // only update if it's changed
910 set_field('user', $key, addslashes($value), 'id', $userid);
914 } else {
915 return false;
917 return get_record_select('user', "id = $userid AND deleted = 0");
920 * Bulk insert in SQL's temp table
921 * @param array $users is an array of usernames
923 function ldap_bulk_insert($users, $temptable) {
924 // bulk insert -- superfast with $bulk_insert_records
925 $sql = 'INSERT INTO ' . $temptable . ' (username) VALUES ';
926 // make those values safe
927 $users = addslashes_recursive($users);
928 // join and quote the whole lot
929 $sql = $sql . "('" . implode("'),('", $users) . "')";
930 print "\t+ " . count($users) . " users\n";
931 execute_sql($sql, false);
934 * Returns true if user should be coursecreator.
936 * @param mixed $username username (without system magic quotes)
937 * @return boolean result
939 function iscreator($username) {
940 if ((empty($this->config->attrcreators) && empty($this->config->groupecreators)) or empty($this->config->memberattribute)) {
941 return null;
943 $textlib = textlib_get_instance();
944 $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
945 //test for groupe creator
946 if (!empty($this->config->groupecreators))
947 if ((boolean)$this->ldap_isgroupmember($extusername, $this->config->groupecreators))
948 return true;
949 //build filter for attrcreator
950 if (!empty($this->config->attrcreators)) {
951 $attrs = explode(";",$this->config->attrcreators);
952 $filter = "(& (".$this->config->user_attribute."=$username)(|";
953 foreach ($attrs as $attr){
954 if(strpos($attr, "="))
955 $filter .= "($attr)";
956 else
957 $filter .= "(".$this->config->memberattribute."=$attr)";
959 $filter .= "))";
960 //search
961 $result = $this->ldap_get_userlist($filter);
962 if (count($result)!=0)
963 return true;
966 return false;
969 * checks if user belong to specific group(s)
971 * Returns true if user belongs group in grupdns string.
973 * @param mixed $username username
974 * @param mixed $groupdns string of group dn separated by ;
977 function ldap_isgroupmember($extusername='', $groupdns='') {
978 // Takes username and groupdn(s) , separated by ;
979 // Returns true if user is member of any given groups
980 $ldapconnection = $this->ldap_connect();
981 if (empty($extusername) or empty($groupdns)) {
982 return false;
984 if ($this->config->memberattribute_isdn) {
985 $memberuser = $this->ldap_find_userdn($ldapconnection, $extusername);
986 } else {
987 $memberuser = $extusername;
989 if (empty($memberuser)) {
990 return false;
992 $groups = explode(";",$groupdns);
993 $result = false;
994 foreach ($groups as $group) {
995 $group = trim($group);
996 if (empty($group)) {
997 continue;
999 //echo "Checking group $group for member $username\n";
1000 $search = ldap_read($ldapconnection, $group, '('.$this->config->memberattribute.'='.$this->filter_addslashes($memberuser).')', array($this->config->memberattribute));
1001 if (!empty($search) and ldap_count_entries($ldapconnection, $search)) {
1002 $info = $this->ldap_get_entries($ldapconnection, $search);
1003 if (count($info) > 0 ) {
1004 // user is member of group
1005 $result = true;
1006 break;
1010 return $result;
1013 * return all usernames from ldap
1015 * @return array
1017 function ldap_get_userlist($filter="*") {
1018 /// returns all users from ldap servers
1019 $fresult = array();
1020 $ldapconnection = $this->ldap_connect();
1021 if ($filter=="*") {
1022 $filter = "(&(".$this->config->user_attribute."=*)(".$this->config->objectclass."))";
1024 $contexts = explode(";",$this->config->contexts);
1025 if (!empty($this->config->create_context)) {
1026 array_push($contexts, $this->config->create_context);
1028 foreach ($contexts as $context) {
1029 $context = trim($context);
1030 if (empty($context)) {
1031 continue;
1033 if ($this->config->search_sub) {
1034 //use ldap_search to find first user from subtree
1035 $ldap_result = ldap_search($ldapconnection, $context,$filter,array($this->config->user_attribute));
1037 else {
1038 //search only in this context
1039 $ldap_result = ldap_list($ldapconnection, $context,
1040 $filter,
1041 array($this->config->user_attribute));
1043 $users = $this->ldap_get_entries($ldapconnection, $ldap_result);
1044 //add found users to list
1045 for ($i=0;$i<count($users);$i++) {
1046 array_push($fresult, ($users[$i][$this->config->user_attribute][0]) );
1049 return $fresult;
1052 * return entries from ldap
1054 * Returns values like ldap_get_entries but is
1055 * binary compatible and return all attributes as array
1057 * @return array ldap-entries
1059 function ldap_get_entries($conn, $searchresult) {
1060 //Returns values like ldap_get_entries but is
1061 //binary compatible
1062 $i=0;
1063 $fresult=array();
1064 $entry = ldap_first_entry($conn, $searchresult);
1065 do {
1066 $attributes = @ldap_get_attributes($conn, $entry);
1067 for ($j=0; $j<$attributes['count']; $j++) {
1068 $values = ldap_get_values_len($conn, $entry,$attributes[$j]);
1070 if (is_array($values)) {
1071 $fresult[$i][strtolower($attributes[$j])] = $values;
1073 else {
1074 $fresult[$i][strtolower($attributes[$j])] = array($values);
1077 $i++;
1079 while ($entry = @ldap_next_entry($conn, $entry));
1080 //were done
1082 return ($fresult);
1085 * Sync roles for this user
1087 * @param $user object user object (without system magic quotes)
1089 function sync_roles($user) {
1090 $iscreator = $this->iscreator($user->username);
1091 if ($iscreator === null) {
1092 return; //nothing to sync - creators not configured
1094 if ($roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
1095 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
1096 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1097 if ($iscreator) { // Following calls will not create duplicates
1098 role_assign($creatorrole->id, $user->id, 0, $systemcontext->id, 0, 0, 0, 'cas');
1099 } else {
1100 //unassign only if previously assigned by this plugin!
1101 role_unassign($creatorrole->id, $user->id, 0, $systemcontext->id, 'cas');
1106 * Quote control characters in texts used in ldap filters - see rfc2254.txt
1108 * @param string
1110 function filter_addslashes($text) {
1111 $text = str_replace('\\', '\\5c', $text);
1112 $text = str_replace(array('*', '(', ')', "\0"),
1113 array('\\2a', '\\28', '\\29', '\\00'), $text);
1114 return $text;