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');
20 * CAS authentication plugin.
22 class auth_plugin_cas
extends auth_plugin_base
{
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
;
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) {
61 return phpCAS
::isAuthenticated();
64 * Returns true if this authentication plugin is 'internal'.
68 function is_internal() {
72 * Returns true if this authentication plugin can change the user's
77 function can_change_password() {
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() {
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
);
100 // Test si cas activé et paramêtres non remplis
101 if (empty($this->config
->hostname
)) {
105 // Connection to CAS server
108 // Gestion de la connection CAS si accès direct d'un ent ou autre
109 if (phpCAS
::checkAuthentication()) {
110 $frm->username
=phpCAS
::getUser();
111 // if (phpCAS::getUser()=='esup9992')
112 // $frm->username='erhar0062';
113 $frm->password
="passwdCas";
117 if ($this->config
->multiauth
) {
118 $authCAS = optional_param("authCAS");
119 if ($authCAS=="NOCAS")
122 // choice authentication form for multi-authentication
123 // test pgtIou parameter for proxy mode (https connection
124 // in background from CAS server to the php server)
125 if ($authCAS!="CAS" && !isset($_GET["pgtIou"])) {
126 print_header("$site->fullname: $CASform", $site->fullname
, $CASform);
127 include($CFG->dirroot
."/auth/cas/cas_form.html");
132 // CAS authentication
133 if (!phpCAS
::isAuthenticated())
134 {phpCAS
::forceAuthentication();}
137 * logout from the cas
139 * This function is called from admin/auth.php
142 function prelogout_hook() {
144 if ($this->config
->logoutcas
) {
145 $backurl = $CFG->wwwroot
;
147 phpCAS
::logout($backurl);
151 * Connect to the cas (clientcas connection or proxycas connection
153 * This function is called from admin/auth.php
156 function connectCAS() {
158 global $PHPCAS_CLIENT;
160 if ( !is_object($PHPCAS_CLIENT) ) {
161 if ($this->config
->proxycas
) {
162 phpCAS
::proxy($this->config
->casversion
, $this-> config
->hostname
, (int) $this->config
->port
, $this->config
->baseuri
);
166 phpCAS
::client($this->config
->casversion
, $this-> config
->hostname
, (int) $this->config
->port
, $this->config
->baseuri
);
172 * Prints a form for configuring this authentication plugin.
174 * This function is called from admin/auth.php, and outputs a full page with
175 * a form for configuring this plugin.
177 * @param array $page An object containing all the data for this page.
179 function config_form($config, $err, $user_fields) {
180 include 'config.html';
183 * Returns the URL for changing the user's pw, or empty if the default can
188 function change_password_url() {
192 * returns predefined usertypes
194 * @return array of predefined usertypes
196 function ldap_suppported_usertypes() {
198 $types['edir']='Novell Edirectory';
199 $types['rfc2307']='posixAccount (rfc2307)';
200 $types['rfc2307bis']='posixAccount (rfc2307bis)';
201 $types['samba']='sambaSamAccount (v.3.0.7)';
202 $types['ad']='MS ActiveDirectory';
203 $types['default']=get_string('default');
207 * Processes and stores configuration data for this authentication plugin.
209 function process_config($config) {
210 // set to defaults if undefined
212 if (!isset ($config->hostname
))
213 $config->hostname
= '';
214 if (!isset ($config->port
))
216 if (!isset ($config->casversion
))
217 $config->casversion
= '';
218 if (!isset ($config->baseuri
))
219 $config->baseuri
= '';
220 if (!isset ($config->language
))
221 $config->language
= '';
222 if (!isset ($config->proxycas
))
223 $config->proxycas
= '';
224 if (!isset ($config->logoutcas
))
225 $config->logoutcas
= '';
226 if (!isset ($config->multiauth
))
227 $config->multiauth
= '';
229 if (!isset($config->host_url
))
230 { $config->host_url
= ''; }
231 if (empty($config->ldapencoding
))
232 { $config->ldapencoding
= 'utf-8'; }
233 if (!isset($config->contexts
))
234 { $config->contexts
= ''; }
235 if (!isset($config->user_type
))
236 { $config->user_type
= 'default'; }
237 if (!isset($config->user_attribute
))
238 { $config->user_attribute
= ''; }
239 if (!isset($config->search_sub
))
240 { $config->search_sub
= ''; }
241 if (!isset($config->opt_deref
))
242 { $config->opt_deref
= ''; }
243 if (!isset($config->bind_dn
))
244 {$config->bind_dn
= ''; }
245 if (!isset($config->bind_pw
))
246 {$config->bind_pw
= ''; }
247 if (!isset($config->version
))
248 {$config->version
= '2'; }
249 if (!isset($config->objectclass
))
250 {$config->objectclass
= ''; }
251 if (!isset($config->memberattribute
))
252 {$config->memberattribute
= ''; }
253 if (!isset($config->memberattribute_isdn
))
254 {$config->memberattribute_isdn
= ''; }
255 if (!isset($config->attrcreators
))
256 {$config->attrcreators
= ''; }
257 if (!isset($config->groupecreators
))
258 {$config->groupecreators
= ''; }
259 if (!isset($config->removeuser
))
260 {$config->removeuser
= 0; }
262 set_config('hostname', $config->hostname
, 'auth/cas');
263 set_config('port', $config->port
, 'auth/cas');
264 set_config('casversion', $config->casversion
, 'auth/cas');
265 set_config('baseuri', $config->baseuri
, 'auth/cas');
266 set_config('language', $config->language
, 'auth/cas');
267 set_config('proxycas', $config->proxycas
, 'auth/cas');
268 set_config('logoutcas', $config->logoutcas
, 'auth/cas');
269 set_config('multiauth', $config->multiauth
, 'auth/cas');
270 // save LDAP settings
271 set_config('host_url', $config->host_url
, 'auth/cas');
272 set_config('ldapencoding', $config->ldapencoding
, 'auth/cas');
273 set_config('host_url', $config->host_url
, 'auth/cas');
274 set_config('contexts', $config->contexts
, 'auth/cas');
275 set_config('user_type', $config->user_type
, 'auth/cas');
276 set_config('user_attribute', $config->user_attribute
, 'auth/cas');
277 set_config('search_sub', $config->search_sub
, 'auth/cas');
278 set_config('opt_deref', $config->opt_deref
, 'auth/cas');
279 set_config('bind_dn', $config->bind_dn
, 'auth/cas');
280 set_config('bind_pw', $config->bind_pw
, 'auth/cas');
281 set_config('version', $config->version
, 'auth/cas');
282 set_config('objectclass', $config->objectclass
, 'auth/cas');
283 set_config('memberattribute', $config->memberattribute
, 'auth/cas');
284 set_config('memberattribute_isdn', $config->memberattribute_isdn
, 'auth/cas');
285 set_config('attrcreators', $config->attrcreators
, 'auth/cas');
286 set_config('groupecreators', $config->groupecreators
, 'auth/cas');
287 set_config('removeuser', $config->removeuser
, 'auth/cas');
291 * Initializes needed ldap variables for cas-module
293 * Uses names defined in ldap_supported_usertypes.
294 * $default is first defined as:
295 * $default['pseudoname'] = array(
296 * 'typename1' => 'value',
297 * 'typename2' => 'value'
301 * @return array of default values
303 function ldap_getdefaults() {
304 $default['objectclass'] = array(
306 'rfc2307' => 'posixAccount',
307 'rfc2307bis' => 'posixAccount',
308 'samba' => 'sambaSamAccount',
312 $default['user_attribute'] = array(
315 'rfc2307bis' => 'uid',
320 $default['memberattribute'] = array(
322 'rfc2307' => 'member',
323 'rfc2307bis' => 'member',
326 'default' => 'member'
328 $default['memberattribute_isdn'] = array(
332 'samba' => '0', //is this right?
339 * reads userinformation from ldap and return it in array()
341 * Read user information from external database and returns it as array().
342 * Function should return all information available. If you are saving
343 * this information to moodle user-table you should honor syncronization flags
345 * @param string $username username (with system magic quotes)
347 * @return mixed array with no magic quotes or false on error
349 function get_userinfo($username) {
350 $textlib = textlib_get_instance();
351 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config
->ldapencoding
);
352 $ldapconnection = $this->ldap_connect();
353 $attrmap = $this->ldap_attributes();
355 $search_attribs = array();
356 foreach ($attrmap as $key=>$values) {
357 if (!is_array($values)) {
358 $values = array($values);
360 foreach ($values as $value) {
361 if (!in_array($value, $search_attribs)) {
362 array_push($search_attribs, $value);
366 $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
367 if (!$user_info_result = ldap_read($ldapconnection, $user_dn, $this->config
->objectclass
, $search_attribs)) {
368 return false; // error!
370 $user_entry = $this->ldap_get_entries($ldapconnection, $user_info_result);
371 if (empty($user_entry)) {
372 return false; // entry not found
374 foreach ($attrmap as $key=>$values) {
375 if (!is_array($values)) {
376 $values = array($values);
379 foreach ($values as $value) {
380 if ($value == 'dn') {
381 $result[$key] = $user_dn;
383 if (!array_key_exists(strtolower($value), $user_entry[0])) {
384 continue; // wrong data mapping!
386 if (is_array($user_entry[0][strtolower($value)])) {
387 $newval = $textlib->convert($user_entry[0][strtolower($value)][0], $this->config
->ldapencoding
, 'utf-8');
389 $newval = $textlib->convert($user_entry[0][strtolower($value)], $this->config
->ldapencoding
, 'utf-8');
392 if (!empty($newval)) { // favour ldap entries that are set
396 if (!is_null($ldapval)) {
397 $result[$key] = $ldapval;
400 @ldap_close
($ldapconnection);
404 * reads userinformation from ldap and return it in an object
406 * @param string $username username (with system magic quotes)
407 * @return mixed object or false on error
409 function get_userinfo_asobj($username) {
410 $user_array = $this->get_userinfo($username);
411 if ($user_array == false) {
412 return false; //error or not found
414 $user_array = truncate_userinfo($user_array);
415 $user = new object();
416 foreach ($user_array as $key=>$value) {
417 $user->{$key} = $value;
422 * connects to ldap server
424 * Tries connect to specified ldap servers.
425 * Returns connection result or error.
427 * @return connection result
429 function ldap_connect($binddn='',$bindpwd='') {
430 //Select bind password, With empty values use
431 //ldap_bind_* variables or anonymous bind if ldap_bind_* are empty
432 if ($binddn == '' and $bindpwd == '') {
433 if (!empty($this->config
->bind_dn
)) {
434 $binddn = $this->config
->bind_dn
;
436 if (!empty($this->config
->bind_pw
)) {
437 $bindpwd = $this->config
->bind_pw
;
440 $urls = explode(";",$this->config
->host_url
);
441 foreach ($urls as $server) {
442 $server = trim($server);
443 if (empty($server)) {
446 $connresult = ldap_connect($server);
447 //ldap_connect returns ALWAYS true
448 if (!empty($this->config
->version
)) {
449 ldap_set_option($connresult, LDAP_OPT_PROTOCOL_VERSION
, $this->config
->version
);
451 if (!empty($binddn)) {
452 //bind with search-user
453 //$debuginfo .= 'Using bind user'.$binddn.'and password:'.$bindpwd;
454 $bindresult=ldap_bind($connresult, $binddn,$bindpwd);
458 $bindresult=@ldap_bind
($connresult);
460 if (!empty($this->config
->opt_deref
)) {
461 ldap_set_option($connresult, LDAP_OPT_DEREF
, $this->config
->opt_deref
);
466 $debuginfo .= "<br/>Server: '$server' <br/> Connection: '$connresult'<br/> Bind result: '$bindresult'</br>";
468 //If any of servers are alive we have already returned connection
469 print_error('auth_ldap_noconnect_all','auth',$this->config
->user_type
);
473 * retuns user attribute mappings between moodle and ldap
477 function ldap_attributes () {
478 $fields = array("firstname", "lastname", "email", "phone1", "phone2",
479 "department", "address", "city", "country", "description",
480 "idnumber", "lang" );
481 $moodleattributes = array();
482 foreach ($fields as $field) {
483 if (!empty($this->config
->{"field_map_$field"})) {
484 $moodleattributes[$field] = $this->config
->{"field_map_$field"};
485 if (preg_match('/,/',$moodleattributes[$field])) {
486 $moodleattributes[$field] = explode(',', $moodleattributes[$field]); // split ?
490 $moodleattributes['username'] = $this->config
->user_attribute
;
491 return $moodleattributes;
494 * retuns dn of username
496 * Search specified contexts for username and return user dn
497 * like: cn=username,ou=suborg,o=org
499 * @param mixed $ldapconnection $ldapconnection result
500 * @param mixed $username username (external encoding no slashes)
503 function ldap_find_userdn ($ldapconnection, $extusername) {
504 //default return value
505 $ldap_user_dn = FALSE;
506 //get all contexts and look for first matching user
507 $ldap_contexts = explode(";",$this->config
->contexts
);
508 if (!empty($this->config
->create_context
)) {
509 array_push($ldap_contexts, $this->config
->create_context
);
511 foreach ($ldap_contexts as $context) {
512 $context = trim($context);
513 if (empty($context)) {
516 if ($this->config
->search_sub
) {
517 //use ldap_search to find first user from subtree
518 $ldap_result = ldap_search($ldapconnection, $context, "(".$this->config
->user_attribute
."=".$this->filter_addslashes($extusername).")",array($this->config
->user_attribute
));
521 //search only in this context
522 $ldap_result = ldap_list($ldapconnection, $context, "(".$this->config
->user_attribute
."=".$this->filter_addslashes($extusername).")",array($this->config
->user_attribute
));
524 $entry = ldap_first_entry($ldapconnection,$ldap_result);
526 $ldap_user_dn = ldap_get_dn($ldapconnection, $entry);
530 return $ldap_user_dn;
533 * Quote control characters in quoted "texts" used in ldap
537 function ldap_addslashes($text) {
538 $text = str_replace('\\', '\\\\', $text);
539 $text = str_replace(array('"', "\0"),
540 array('\\"', '\\00'), $text);
544 * returns all usernames from external database
546 * get_userlist returns all usernames from external database
550 function get_userlist() {
551 return $this->ldap_get_userlist("({$this->config->user_attribute}=*)");
554 * checks if user exists on external db
556 * @param string $username (with system magic quotes)
558 function user_exists($username) {
559 $textlib = textlib_get_instance();
560 $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config
->ldapencoding
);
561 //returns true if given username exist on ldap
562 $users = $this->ldap_get_userlist("({$this->config->user_attribute}=".$this->filter_addslashes($extusername).")");
563 return count($users);
566 * syncronizes user fron external db to moodle user table
568 * Sync is now using username attribute.
570 * Syncing users removes or suspends users that dont exists anymore in external db.
571 * Creates new users and updates coursecreator status of users.
573 * @param int $bulk_insert_records will insert $bulkinsert_records per insert statement
574 * valid only with $unsafe. increase to a couple thousand for
575 * blinding fast inserts -- but test it: you may hit mysqld's
576 * max_allowed_packet limit.
577 * @param bool $do_updates will do pull in data updates from ldap if relevant
579 function sync_users ($bulk_insert_records = 1000, $do_updates = true) {
581 $textlib = textlib_get_instance();
582 $droptablesql = array(); /// sql commands to drop the table (because session scope could be a problem for
583 /// some persistent drivers like ODBTP (mssql) or if this function is invoked
584 /// from within a PHP application using persistent connections
585 // configure a temp table
586 print "Configuring temp table\n";
587 switch (strtolower($CFG->dbfamily
)) {
589 $temptable = $CFG->prefix
. 'extuser';
590 $droptablesql[] = 'DROP TEMPORARY TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
591 execute_sql_arr($droptablesql, true, false); /// Drop temp table to avoid persistence problems later
592 echo "Creating temp table $temptable\n";
593 execute_sql('CREATE TEMPORARY TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username)) TYPE=MyISAM', false);
596 $temptable = $CFG->prefix
. 'extuser';
597 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
598 execute_sql_arr($droptablesql, true, false); /// Drop temp table to avoid persistence problems later
599 echo "Creating temp table $temptable\n";
600 $bulk_insert_records = 1; // no support for multiple sets of values
601 execute_sql('CREATE TEMPORARY TABLE '. $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))', false);
604 $temptable = '#'.$CFG->prefix
. 'extuser'; /// MSSQL temp tables begin with #
605 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
606 execute_sql_arr($droptablesql, true, false); /// Drop temp table to avoid persistence problems later
607 echo "Creating temp table $temptable\n";
608 $bulk_insert_records = 1; // no support for multiple sets of values
609 execute_sql('CREATE TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))', false);
612 $temptable = $CFG->prefix
. 'extuser';
613 $droptablesql[] = 'TRUNCATE TABLE ' . $temptable; // oracle requires truncate before being able to drop a temp table
614 $droptablesql[] = 'DROP TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
615 execute_sql_arr($droptablesql, true, false); /// Drop temp table to avoid persistence problems later
616 echo "Creating temp table $temptable\n";
617 $bulk_insert_records = 1; // no support for multiple sets of values
618 execute_sql('CREATE GLOBAL TEMPORARY TABLE '.$temptable.' (username VARCHAR(64), PRIMARY KEY (username)) ON COMMIT PRESERVE ROWS', false);
621 print "Connecting to ldap...\n";
622 $ldapconnection = $this->ldap_connect();
623 if (!$ldapconnection) {
624 @ldap_close
($ldapconnection);
625 print get_string('auth_ldap_noconnect','auth',$this->config
->host_url
);
629 //// get user's list from ldap to sql in a scalable fashion
631 // prepare some data we'll need
632 $filter = "(&(".$this->config
->user_attribute
."=*)(".$this->config
->objectclass
."))";
633 $contexts = explode(";",$this->config
->contexts
);
634 if (!empty($this->config
->create_context
)) {
635 array_push($contexts, $this->config
->create_context
);
638 foreach ($contexts as $context) {
639 $context = trim($context);
640 if (empty($context)) {
644 if ($this->config
->search_sub
) {
645 //use ldap_search to find first user from subtree
646 $ldap_result = ldap_search($ldapconnection, $context,
648 array($this->config
->user_attribute
));
650 //search only in this context
651 $ldap_result = ldap_list($ldapconnection, $context,
653 array($this->config
->user_attribute
));
655 if ($entry = ldap_first_entry($ldapconnection, $ldap_result)) {
657 $value = ldap_get_values_len($ldapconnection, $entry, $this->config
->user_attribute
);
658 $value = $textlib->convert($value[0], $this->config
->ldapencoding
, 'utf-8');
659 array_push($fresult, $value);
660 if (count($fresult) >= $bulk_insert_records) {
661 $this->ldap_bulk_insert($fresult, $temptable);
664 } while ($entry = ldap_next_entry($ldapconnection, $entry));
666 unset($ldap_result); // free mem
667 // insert any remaining users and release mem
668 if (count($fresult)) {
669 $this->ldap_bulk_insert($fresult, $temptable);
674 /// preserve our user database
675 /// if the temp table is empty, it probably means that something went wrong, exit
676 /// so as to avoid mass deletion of users; which is hard to undo
677 $count = get_record_sql('SELECT COUNT(username) AS count, 1 FROM ' . $temptable);
678 $count = $count->{'count'};
680 print "Did not get any users from LDAP -- error? -- exiting\n";
683 print "Got $count records from LDAP\n\n";
686 // find users in DB that aren't in ldap -- to be removed!
687 // this is still not as scalable (but how often do we mass delete?)
688 if (!empty($this->config
->removeuser
)) {
689 $sql = "SELECT u.id, u.username, u.email
690 FROM {$CFG->prefix}user u
691 LEFT JOIN $temptable e ON u.username = e.username
694 AND e.username IS NULL";
695 $remove_users = get_records_sql($sql);
696 if (!empty($remove_users)) {
697 print "User entries to remove: ". count($remove_users) . "\n";
699 foreach ($remove_users as $user) {
700 if ($this->config
->removeuser
== 2) {
701 //following is copy pasted from admin/user.php
702 //maybe this should moved to function in lib/datalib.php
703 $updateuser = new object();
704 $updateuser->id
= $user->id
;
705 $updateuser->deleted
= 1;
706 $updateuser->username
= addslashes("$user->email.".time()); // Remember it just in case
707 $updateuser->email
= ''; // Clear this field to free it up
708 $updateuser->idnumber
= ''; // Clear this field to free it up
709 $updateuser->timemodified
= time();
710 if (update_record('user', $updateuser)) {
711 delete_records('role_assignments', 'userid', $user->id
); // unassign all roles
712 //copy pasted part ends
713 echo "\t"; print_string('auth_dbdeleteuser', 'auth', array($user->username
, $user->id
)); echo "\n";
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";
724 echo "\t"; print_string('auth_dbsuspendusererror', 'auth', $user->username
); echo "\n";
730 print "No user entries to be removed\n";
732 unset($remove_users); // free mem!
734 /// Revive suspended users
735 if (!empty($this->config
->removeuser
) and $this->config
->removeuser
== 1) {
736 $sql = "SELECT u.id, u.username
737 FROM $temptable e, {$CFG->prefix}user u
738 WHERE e.username=u.username
739 AND u.auth='nologin'";
740 $revive_users = get_records_sql($sql);
741 if (!empty($revive_users)) {
742 print "User entries to be revived: ". count($revive_users) . "\n";
744 foreach ($revive_users as $user) {
745 $updateuser = new object();
746 $updateuser->id
= $user->id
;
747 $updateuser->auth
= 'cas';
748 if (update_record('user', $updateuser)) {
749 echo "\t"; print_string('auth_dbreviveser', 'auth', array($user->username
, $user->id
)); echo "\n";
751 echo "\t"; print_string('auth_dbreviveusererror', 'auth', $user->username
); echo "\n";
756 print "No user entries to be revived\n";
758 unset($revive_users);
760 /// User Updates - time-consuming (optional)
762 // narrow down what fields we need to update
763 $all_keys = array_keys(get_object_vars($this->config
));
764 $updatekeys = array();
765 foreach ($all_keys as $key) {
766 if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
767 // if we have a field to update it from
768 // and it must be updated 'onlogin' we
770 if ( !empty($this->config
->{'field_map_'.$match[1]})
771 and $this->config
->{$match[0]} === 'onlogin') {
772 array_push($updatekeys, $match[1]); // the actual key name
776 // print_r($all_keys); print_r($updatekeys);
777 unset($all_keys); unset($key);
779 print "No updates to be done\n";
781 if ( $do_updates and !empty($updatekeys) ) { // run updates only if relevant
782 $users = get_records_sql("SELECT u.username, u.id
783 FROM {$CFG->prefix}user u
784 WHERE u.deleted=0 AND u.auth='cas'");
785 if (!empty($users)) {
786 print "User entries to update: ". count($users). "\n";
787 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
788 if (!empty($this->config
->creators
) and !empty($this->config
->memberattribute
)
789 and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW
)) {
790 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
792 $creatorrole = false;
797 foreach ($users as $user) {
798 echo "\t"; print_string('auth_dbupdatinguser', 'auth', array($user->username
, $user->id
));
799 if (!$this->update_user_record(addslashes($user->username
), $updatekeys)) {
800 echo " - ".get_string('skipped');
804 // update course creators if needed
805 if ($creatorrole !== false) {
806 if ($this->iscreator($user->username
)) {
807 role_assign($creatorrole->id
, $user->id
, 0, $sitecontext->id
, 0, 0, 0, 'cas');
809 role_unassign($creatorrole->id
, $user->id
, 0, $sitecontext->id
, 'cas');
812 if ($xcount++
> $maxxcount) {
819 unset($users); // free mem
821 } else { // end do updates
822 print "No updates to be done\n";
825 // find users missing in DB that are in LDAP
826 // note that get_records_sql wants at least 2 fields returned,
827 // and gives me a nifty object I don't want.
828 // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
829 $sql = "SELECT e.username, e.username
830 FROM $temptable e LEFT JOIN {$CFG->prefix}user u ON e.username = u.username
832 $add_users = get_records_sql($sql); // get rid of the fat
833 if (!empty($add_users)) {
834 print "User entries to add: ". count($add_users). "\n";
835 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
836 if (!empty($this->config
->creators
) and !empty($this->config
->memberattribute
)
837 and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW
)) {
838 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
840 $creatorrole = false;
843 foreach ($add_users as $user) {
844 $user = $this->get_userinfo_asobj(addslashes($user->username
));
846 $user->modified
= time();
847 $user->confirmed
= 1;
849 $user->mnethostid
= $CFG->mnet_localhost_id
;
850 if (empty($user->lang
)) {
851 $user->lang
= $CFG->lang
;
853 $user = addslashes_recursive($user);
854 if ($id = insert_record('user',$user)) {
855 echo "\t"; print_string('auth_dbinsertuser', 'auth', array(stripslashes($user->username
), $id)); echo "\n";
856 $userobj = $this->update_user_record($user->username
);
857 if (!empty($this->config
->forcechangepassword
)) {
858 set_user_preference('auth_forcepasswordchange', 1, $userobj->id
);
861 echo "\t"; print_string('auth_dbinsertusererror', 'auth', $user->username
); echo "\n";
863 // add course creators if needed
864 if ($creatorrole !== false and $this->iscreator(stripslashes($user->username
))) {
865 role_assign($creatorrole->id
, $user->id
, 0, $sitecontext->id
, 0, 0, 0, 'cas');
869 unset($add_users); // free mem
871 print "No users to be added\n";
876 * Update a local user record from an external source.
877 * This is a lighter version of the one in moodlelib -- won't do
878 * expensive ops such as enrolment.
880 * If you don't pass $updatekeys, there is a performance hit and
881 * values removed from LDAP won't be removed from moodle.
883 * @param string $username username (with system magic quotes)
885 function update_user_record($username, $updatekeys = false) {
887 //just in case check text case
888 $username = trim(moodle_strtolower($username));
889 // get the current user record
890 $user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id
);
891 if (empty($user)) { // trouble
892 error_log("Cannot update non-existent user: ".stripslashes($username));
893 print_error('auth_dbusernotexist','auth',$username);
896 // Protect the userid from being overwritten
898 if ($newinfo = $this->get_userinfo($username)) {
899 $newinfo = truncate_userinfo($newinfo);
900 if (empty($updatekeys)) { // all keys? this does not support removing values
901 $updatekeys = array_keys($newinfo);
903 foreach ($updatekeys as $key) {
904 if (isset($newinfo[$key])) {
905 $value = $newinfo[$key];
909 if (!empty($this->config
->{'field_updatelocal_' . $key})) {
910 if ($user->{$key} != $value) { // only update if it's changed
911 set_field('user', $key, addslashes($value), 'id', $userid);
918 return get_record_select('user', "id = $userid AND deleted = 0");
921 * Bulk insert in SQL's temp table
922 * @param array $users is an array of usernames
924 function ldap_bulk_insert($users, $temptable) {
925 // bulk insert -- superfast with $bulk_insert_records
926 $sql = 'INSERT INTO ' . $temptable . ' (username) VALUES ';
927 // make those values safe
928 $users = addslashes_recursive($users);
929 // join and quote the whole lot
930 $sql = $sql . "('" . implode("'),('", $users) . "')";
931 print "\t+ " . count($users) . " users\n";
932 execute_sql($sql, false);
935 * Returns true if user should be coursecreator.
937 * @param mixed $username username (without system magic quotes)
938 * @return boolean result
940 function iscreator($username) {
941 if ((empty($this->config
->attrcreators
) && empty($this->config
->groupecreators
)) or empty($this->config
->memberattribute
)) {
944 $textlib = textlib_get_instance();
945 $extusername = $textlib->convert($username, 'utf-8', $this->config
->ldapencoding
);
946 //test for groupe creator
947 if (!empty($this->config
->groupecreators
))
948 if ((boolean
)$this->ldap_isgroupmember($extusername, $this->config
->groupecreators
))
950 //build filter for attrcreator
951 if (!empty($this->config
->attrcreators
)) {
952 $attrs = explode(";",$this->config
->attrcreators
);
953 $filter = "(& (".$this->config
->user_attribute
."=$username)(|";
954 foreach ($attrs as $attr){
955 if(strpos($attr, "="))
956 $filter .= "($attr)";
958 $filter .= "(".$this->config
->memberattribute
."=$attr)";
962 $result = $this->ldap_get_userlist($filter);
963 if (count($result)!=0)
970 * checks if user belong to specific group(s)
972 * Returns true if user belongs group in grupdns string.
974 * @param mixed $username username
975 * @param mixed $groupdns string of group dn separated by ;
978 function ldap_isgroupmember($extusername='', $groupdns='') {
979 // Takes username and groupdn(s) , separated by ;
980 // Returns true if user is member of any given groups
981 $ldapconnection = $this->ldap_connect();
982 if (empty($extusername) or empty($groupdns)) {
985 if ($this->config
->memberattribute_isdn
) {
986 $memberuser = $this->ldap_find_userdn($ldapconnection, $extusername);
988 $memberuser = $extusername;
990 if (empty($memberuser)) {
993 $groups = explode(";",$groupdns);
995 foreach ($groups as $group) {
996 $group = trim($group);
1000 //echo "Checking group $group for member $username\n";
1001 $search = ldap_read($ldapconnection, $group, '('.$this->config
->memberattribute
.'='.$this->filter_addslashes($memberuser).')', array($this->config
->memberattribute
));
1002 if (!empty($search) and ldap_count_entries($ldapconnection, $search)) {
1003 $info = $this->ldap_get_entries($ldapconnection, $search);
1004 if (count($info) > 0 ) {
1005 // user is member of group
1014 * return all usernames from ldap
1018 function ldap_get_userlist($filter="*") {
1019 /// returns all users from ldap servers
1021 $ldapconnection = $this->ldap_connect();
1023 $filter = "(&(".$this->config
->user_attribute
."=*)(".$this->config
->objectclass
."))";
1025 $contexts = explode(";",$this->config
->contexts
);
1026 if (!empty($this->config
->create_context
)) {
1027 array_push($contexts, $this->config
->create_context
);
1029 foreach ($contexts as $context) {
1030 $context = trim($context);
1031 if (empty($context)) {
1034 if ($this->config
->search_sub
) {
1035 //use ldap_search to find first user from subtree
1036 $ldap_result = ldap_search($ldapconnection, $context,$filter,array($this->config
->user_attribute
));
1039 //search only in this context
1040 $ldap_result = ldap_list($ldapconnection, $context,
1042 array($this->config
->user_attribute
));
1044 $users = $this->ldap_get_entries($ldapconnection, $ldap_result);
1045 //add found users to list
1046 for ($i=0;$i<count($users);$i++
) {
1047 array_push($fresult, ($users[$i][$this->config
->user_attribute
][0]) );
1053 * return entries from ldap
1055 * Returns values like ldap_get_entries but is
1056 * binary compatible and return all attributes as array
1058 * @return array ldap-entries
1060 function ldap_get_entries($conn, $searchresult) {
1061 //Returns values like ldap_get_entries but is
1065 $entry = ldap_first_entry($conn, $searchresult);
1067 $attributes = @ldap_get_attributes
($conn, $entry);
1068 for ($j=0; $j<$attributes['count']; $j++
) {
1069 $values = ldap_get_values_len($conn, $entry,$attributes[$j]);
1071 if (is_array($values)) {
1072 $fresult[$i][strtolower($attributes[$j])] = $values;
1075 $fresult[$i][strtolower($attributes[$j])] = array($values);
1080 while ($entry = @ldap_next_entry
($conn, $entry));
1086 * Sync roles for this user
1088 * @param $user object user object (without system magic quotes)
1090 function sync_roles($user) {
1091 $iscreator = $this->iscreator($user->username
);
1092 if ($iscreator === null) {
1093 return; //nothing to sync - creators not configured
1095 if ($roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW
)) {
1096 $creatorrole = array_shift($roles); // We can only use one, let's use the first one
1097 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1098 if ($iscreator) { // Following calls will not create duplicates
1099 role_assign($creatorrole->id
, $user->id
, 0, $systemcontext->id
, 0, 0, 0, 'cas');
1101 //unassign only if previously assigned by this plugin!
1102 role_unassign($creatorrole->id
, $user->id
, 0, $systemcontext->id
, 'cas');
1107 * Quote control characters in texts used in ldap filters - see rfc2254.txt
1111 function filter_addslashes($text) {
1112 $text = str_replace('\\', '\\5c', $text);
1113 $text = str_replace(array('*', '(', ')', "\0"),
1114 array('\\2a', '\\28', '\\29', '\\00'), $text);