This directory contains authentication modules.
-Each of these modules describes a different way to
-check that a user has provided a correct
+Each of these modules describes a different way to
+check that a user has provided a correct
- - username, and
+ - username, and
- password.
Even when external forms of authentication are being used, Moodle still
email - authentication by email (DEFAULT METHOD)
- user fills out form with email address
- - email sent to user with link
+ - email sent to user with link
- user clicks on link in email to confirm
- user account is created
- user can log in
none - no authentication at all .. very insecure!!
-
+
- user logs in using ANY username and password
- if the username doesn't already exist then
a new account is created
- - when user tries to access a course they
+ - when user tries to access a course they
are forced to set up their account details
manual - internal authentication only
db - Uses an external database to check username/password
-
+
- user logs in using username and password
- these are checked against an external database
- if correct, user is logged in
Basic fuctions to authenticate users with external db.
-Mandatory:
+Mandatory:
auth_plugin_foo()
Constructor. At the least, it populates config member variable with settings
from the Moodle database. It makes sense to put other startup code here.
- user_login($username, $password)
+ user_login($username, $password)
Authenticate username, password with userdatabase.
Query other userinformation from database.
Returns:
- Userinformation in array ( name => value, ....
+ Userinformation in array ( name => value, ....
or false in case of error
Functions that enable usercreation, activation and deactivation
from moodle to external database
-
-
- user_exists ($username)
+
+
+ user_exists ($username)
Checks if given username exist on external db
true if given usernname exist or false
- user_create ($userobject,$plainpass)
+ user_create ($userobject,$plainpass)
Creates new user to external db. User should be created
in inactive stage until confirmed by email.
True on success otherwise false
- user_activate ($username)
+ user_activate ($username)
activate new user after email-address is confirmed
All usernames in array or false on error.
- get_users($filter='*')
-
- Get ALL USEROBJECTS FROM EXTERNAL DB.
-
- Returns:
- Array of all users as objects from external db
-
-
$ldapauth = get_auth_plugin('ldap');
-If an auth is not specified, get_auth_plugin() will return you the auth plugin
-defined in the $CFG->auth variable.
-
Auth plugin classes are pretty basic. They contain the same functions that were
previously in each plugin's lib.php file, but refactored to become class
methods, and tweaked to reference the plugin's instantiated config to get at the
This is the primary method that is used by the authenticate_user_login()
function in moodlelib.php. This method should return a boolean indicating
whether or not the username and password authenticate successfully.
+ Both parameter must have magic quotes applied.
is_internal()
Returns true if this authentication plugin is "internal" (which means that
Other Methods
-----------------
-get_userinfo()
+get_userinfo($username)
This method should return an array of fields from the authentication source
- for the given username.
+ for the given username. Username parameter must have magic quotes applied.
+ The returned array does not have magic quotes applied.
Upgrading from Moodle 1.7
-----------------------------
Please read comments from lib.php for auth/cas module
The auth/cas module is using part of the /auth/ldap module. The /auth/ldap directory should exist.
-The auth/cas use the PHPCAS project from http://esup-phpcas.sourceforge.net
+The auth/cas use the PHPCAS project from http://esup-phpcas.sourceforge.net
* 2006-08-28 File created.
*/
-// This page cannot be called directly
-if (!isset($CFG)) exit;
+if (!defined('MOODLE_INTERNAL')) {
+ die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
+}
/**
* CAS authentication plugin.
*
* @param string $username The username
* @param string $password The password
- * @returns bool Authentication success or failure.
+ * @return bool Authentication success or failure.
*/
function user_login ($username, $password) {
if (! function_exists('ldap_connect')) {
print_error('auth_casnotinstalled','mnet');
return false;
}
-
+
global $CFG;
// don't allow blank usernames or passwords
if (!$username or !$password) {
return false;
}
-
+
// CAS specific
if ($CFG->auth == "cas" and !empty($this->config->enabled)) {
if ($this->config->create_user == '0') {
if ($ldap_connection) {
$ldap_user_dn = auth_ldap_find_userdn($ldap_connection, $username);
-
+
// if ldap_user_dn is empty, user does not exist
if (!$ldap_user_dn) {
ldap_close($ldap_connection);
/**
* Returns true if this authentication plugin is 'internal'.
*
- * @returns bool
+ * @return bool
*/
function is_internal() {
return false;
* Returns true if this authentication plugin can change the user's
* password.
*
- * @returns bool
+ * @return bool
*/
function can_change_password() {
return false;
*
* @param array $page An object containing all the data for this page.
*/
- function config_form($config, $err) {
+ function config_form($config, $err, $user_fields) {
include 'config.html';
}
* Returns the URL for changing the user's pw, or false if the default can
* be used.
*
- * @returns bool
+ * @return bool
*/
function change_password_url() {
return $this->config->changepasswordurl;
set_config('changepasswordurl', $config->changepasswordurl, 'auth/cas');
// save LDAP settings
- // TODO: Do we want the CAS LDAP settings to be separate from the LDAP settings?
+ // TODO: settings must be separated now that we have multiauth!
$ldapauth = get_auth_plugin('ldap');
$ldapauth->process_config($config);
/** auth_ldap_sync_users.php
* Modified for cas Module
*
- * This script is meant to be called from a cronjob to sync moodle with the LDAP
+ * This script is meant to be called from a cronjob to sync moodle with the LDAP
* backend in those setups where the LDAP backend acts as 'master'.
- *
+ *
* Recommended cron entry:
* # 5 minutes past 4am
* 5 4 * * * /usr/bin/php -c /etc/php4/cli/php.ini /var/www/moodle/auth/ldap/auth_ldap_sync_users.php
- *
- * Notes:
+ *
+ * Notes:
* - If you have a large number of users, you may want to raise the memory limits
* by passing -d momory_limit=256M
* - For debugging & better logging, you are encouraged to use in the command line:
* -d log_errors=1 -d error_reporting=E_ALL -d display_errors=0 -d html_errors=0
- *
+ *
* Performance notes:
* We have optimized it as best as we could for Postgres and mySQL, with 27K students
- * we have seen this take 10 minutes.
- *
+ * we have seen this take 10 minutes.
+ *
*/
-if (!empty($_SERVER['GATEWAY_INTERFACE'])) {
- error_log("should not be called from apache!");
+if (isset($_SERVER['REMOTE_ADDR'])) {
+ error_log("should not be called from web server!");
exit;
}
+$nomoodlecookie = true; // cookie not needed
+
require_once(dirname(dirname(dirname(__FILE__))).'/config.php'); // global moodle config file.
require_once($CFG->dirroot.'/course/lib.php');
require_once($CFG->dirroot.'/mod/resource/lib.php');
require_once($CFG->dirroot.'/mod/forum/lib.php');
require_once($CFG->dirroot.'/lib/moodlelib.php');
-$CFG->debug=10;
+
+if (!is_enabled_auth('cas')) {
+ echo "Plugin not enabled!";
+ die;
+}
+
$casauth = get_auth_plugin('cas');
$casauth->sync_users(1000, true);
unset($options);
$options[1] = get_string('yes');
choose_from_menu ($options, 'use_cas', $config->use_cas, get_string('no'), '', '');
-
+
?>
</td>
<td><?php print_string('auth_cas_enabled', 'auth') ?></td>
<td>
<input name="hostname" type="text" size="30" value="<?php echo $config->hostname ?>" />
<?php
-
+
if (isset($err['hostname'])) {
formerr($err['hostname']);
- }
-
+ }
+
?>
</td>
<td><?php print_string('auth_cas_hostname', 'auth') ?></td>
<td>
<input name="baseuri" type="text" size="30" value="<?php echo $config->baseuri ?>" />
<?php
-
+
if (isset($err['baseuri'])) {
formerr($err['baseuri']);
}
-
+
?>
</td>
<td><?php print_string('auth_cas_baseuri', 'auth') ?></td>
<td>
<input name="port" type="text" size="30" value="<?php echo $config->port ?>" />
<?php
-
+
if (isset($err['port'])) {
formerr($err['port']);
}
-
+
?>
</td>
<td><?php print_string('auth_cas_port', 'auth') ?></td>
<tr>
<td width="50%" align="center" valign="top" class="generalbox">
<p><?php print_string("loginusing") ?>:<br />
- (<?php print_string("cookiesenabled");?>)
+ (<?php print_string("cookiesenabled");?>)
<?php helpbutton("cookies", get_string("cookiesenabled"))?><br /><?php formerr($errormsg) ?>
</p>
<form action="index.php" method="post" id="login">
$changebuttonname = get_string("senddetails");
?>
<hr width="80%" />
- <p><?php print_string("forgotten") ?></p>
+ <p><?php print_string("forgotten") ?></p>
<form action="<?php p($changepassword) ?>" method="get" id="changepassword">
<input type="submit" value="<?php p($changebuttonname) ?>" />
</form>
update_login_count();
if ($user) {
- if (! $user->confirmed ) { // they never confirmed via email
- print_header(get_string("mustconfirm"), get_string("mustconfirm") );
+ if (! $user->confirmed ) { // they never confirmed via email
+ print_header(get_string("mustconfirm"), get_string("mustconfirm") );
print_heading(get_string("mustconfirm"));
print_simple_box(get_string("emailconfirmsent", "", $user->email), "center");
print_footer();
$USER->firstname = get_string("guestuser"); // Name always in current language
$USER->lastname = " ";
}
-
+
if (!update_user_login_times()) {
error("Wierd error: could not update login records");
}
$userauth = get_auth_plugin($USER->auth);
if (method_exists($userauth, 'can_change_password') and $userauth->can_change_password()) {
$passwordchangeurl=$CFG->wwwroot.'/login/change_password.php';
- }
+ }
// check whether the user should be changing password
if (get_user_preferences('auth_forcepasswordchange', false)) {
}
}
-
+
add_to_log(SITEID, "user", "login", "view.php?id=$user->id&course=".SITEID, $user->id, 0, $user->id);
if (user_not_fully_set_up($USER)) {
if ($ldapauth->config->expiration == 1) {
$days2expire = $ldapauth->password_expire($USER->username);
if (intval($days2expire) > 0 && intval($days2expire) < intval($CFG->{$USER->auth.'_expiration_warning'})) {
- print_header("$site->fullname: $loginsite", "$site->fullname", $loginsite, $focus, "", true, "<div align=\"right\">$langmenu</div>");
- notice_yesno(get_string('auth_passwordwillexpire', 'auth', $days2expire), $passwordchangeurl, $urltogo);
+ print_header("$site->fullname: $loginsite", "$site->fullname", $loginsite, $focus, "", true, "<div align=\"right\">$langmenu</div>");
+ notice_yesno(get_string('auth_passwordwillexpire', 'auth', $days2expire), $passwordchangeurl, $urltogo);
print_footer();
exit;
} elseif (intval($days2expire) < 0 ) {
- print_header("$site->fullname: $loginsite", "$site->fullname", $loginsite, $focus, "", true, "<div align=\"right\">$langmenu</div>");
+ print_header("$site->fullname: $loginsite", "$site->fullname", $loginsite, $focus, "", true, "<div align=\"right\">$langmenu</div>");
notice_yesno(get_string('auth_passwordisexpired', 'auth'), $passwordchangeurl, $urltogo);
print_footer();
exit;
redirect($urltogo);
exit;
-
+
} else {
if ($CFG->auth == "cas" ) { /// CAS error login
$errormsg = get_string("invalidcaslogin");
}
$user = $casauth->automatic_authenticate($user);
if ($user) {
- if (! $user->confirmed ) { // they never confirmed via email
- print_header(get_string("mustconfirm"), get_string("mustconfirm") );
+ if (! $user->confirmed ) { // they never confirmed via email
+ print_header(get_string("mustconfirm"), get_string("mustconfirm") );
print_heading(get_string("mustconfirm"));
print_simple_box(get_string("emailconfirmsent", "", $user->email), "center");
print_footer();
}
}
-
+
add_to_log(SITEID, "user", "login", "view.php?id=$user->id&course=".SITEID, $user->id, 0, $user->id);
if (user_not_fully_set_up($USER)) {
if ($ldapauth->config->expiration == 1) {
$days2expire = $ldapauth->password_expire($USER->username);
if (intval($days2expire) > 0 && intval($days2expire) < intval($CFG->{$USER->auth.'_expiration_warning'})) {
- print_header("$site->fullname: $loginsite", "$site->fullname", $loginsite, $focus, "", true, "<div class=\"langmenu\">$langmenu</div>");
- notice_yesno(get_string('auth_passwordwillexpire', 'auth', $days2expire), $passwordchangeurl, $urltogo);
+ print_header("$site->fullname: $loginsite", "$site->fullname", $loginsite, $focus, "", true, "<div class=\"langmenu\">$langmenu</div>");
+ notice_yesno(get_string('auth_passwordwillexpire', 'auth', $days2expire), $passwordchangeurl, $urltogo);
print_footer();
exit;
} elseif (intval($days2expire) < 0 ) {
- print_header("$site->fullname: $loginsite", "$site->fullname", $loginsite, $focus, "", true, "<div class=\"langmenu\">$langmenu</div>");
+ print_header("$site->fullname: $loginsite", "$site->fullname", $loginsite, $focus, "", true, "<div class=\"langmenu\">$langmenu</div>");
notice_yesno(get_string('auth_passwordisexpired', 'auth'), $passwordchangeurl, $urltogo);
print_footer();
exit;
}
if (empty($SESSION->wantsurl)) {
- $SESSION->wantsurl = array_key_exists('HTTP_REFERER',$_SERVER) ? $_SERVER["HTTP_REFERER"] : $CFG->wwwroot.'/';
+ $SESSION->wantsurl = array_key_exists('HTTP_REFERER',$_SERVER) ? $_SERVER["HTTP_REFERER"] : $CFG->wwwroot.'/';
}
- if (get_moodle_cookie() == '') {
+ if (get_moodle_cookie() == '') {
set_moodle_cookie('nobody'); // To help search for cookies
}
-
+
if (empty($frm->username)) {
$frm->username = get_moodle_cookie() === 'nobody' ? '' : get_moodle_cookie();
$frm->password = "";
}
-
+
if (!empty($frm->username)) {
$focus = "login.password";
} else {
} else {
$show_instructions = false;
}
-
- print_header("$site->fullname: $loginsite", "$site->fullname", $loginsite, $focus, "", true, "<div align=\"right\">$langmenu</div>");
+
+ print_header("$site->fullname: $loginsite", "$site->fullname", $loginsite, $focus, "", true, "<div align=\"right\">$langmenu</div>");
include($CFG->dirroot.'/auth/cas/index_form.html');
print_footer();
*
* @return bool Authentication success or failure.
*/
- function user_login ($username, $password) {
+ function user_login($username, $password) {
global $CFG;
$extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->extencoding);
$extpassword = $textlib->convert(stripslashes($password), 'utf-8', $this->config->extencoding);
- // Connect to the external database (forcing new connection)
- $authdb = &ADONewConnection($this->config->type);
- if (!empty($this->config->debugauthdb)) {
- $authdb->debug = true;
- ob_start();//start output buffer to allow later use of the page headers
- }
- $authdb->Connect($this->config->host, $this->config->user, $this->config->pass, $this->config->name, true);
- $authdb->SetFetchMode(ADODB_FETCH_ASSOC);
- if (!empty($this->config->setupsql)) {
- $authdb->Execute($this->config->setupsql);
- }
+ $authdb = $this->db_init();
if ($this->config->passtype === 'internal') {
// lookup username externally, but resolve
return false;
}
- if ( $rs->RecordCount() ) {
+ if ($rs->RecordCount()) {
return true;
} else {
return false;
}
}
-
- /**
- * Reads any other information for a user from external database,
- * then returns it in an array
- *
- * @param string $username (with system magic quotes)
- */
- function get_userinfo($username) {
-
- global $CFG;
-
- $textlib = textlib_get_instance();
- $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->extencoding);
-
+ function db_init() {
// Connect to the external database (forcing new connection)
$authdb = &ADONewConnection($this->config->type);
if (!empty($this->config->debugauthdb)) {
$authdb->Execute($this->config->setupsql);
}
+ return $authdb;
+ }
+ /**
+ * retuns user attribute mappings between moodle and ldap
+ *
+ * @return array
+ */
+ function db_attributes() {
$fields = array("firstname", "lastname", "email", "phone1", "phone2",
"department", "address", "city", "country", "description",
- "idnumber", "lang");
-
-
- //Array to map local fieldnames we want, to external fieldnames
- $selectfields = array();
+ "idnumber", "lang" );
+ $moodleattributes = array();
foreach ($fields as $field) {
- if (!empty($this->config->{'field_map_' . $field})) {
- $selectfields[$field] = $this->config->{'field_map_' . $field};
+ if (!empty($this->config->{"field_map_$field"})) {
+ $moodleattributes[$field] = $this->config->{"field_map_$field"};
}
}
+ $moodleattributes['username'] = $this->config->fielduser;
+ return $moodleattributes;
+ }
+
+ /**
+ * Reads any other information for a user from external database,
+ * then returns it in an array
+ *
+ * @param string $username (with system magic quotes)
+ *
+ * @return array without magic quotes
+ */
+ function get_userinfo($username) {
+
+ global $CFG;
+
+ $textlib = textlib_get_instance();
+ $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->extencoding);
+
+ $authdb = $this->db_init();
+
+ //Array to map local fieldnames we want, to external fieldnames
+ $selectfields = $this->db_attributes();
+
$result = array();
//If at least one field is mapped from external db, get that mapped data:
if ($selectfields) {
global $CFG;
if ($this->config->passtype === 'internal') {
- update_internal_user_password($user, $newpassword, true);
+ update_internal_user_password($user, $newpassword);
} else {
// we should have never been called!
return false;
* This implementation is simpler but less scalable than the one found in the LDAP module.
*
*/
- function sync_users ($do_updates=false) {
+ function sync_users($do_updates=false) {
global $CFG;
$pcfg = get_config('auth/db');
- ///
- /// list external users
- ///
+/// list external users
$userlist = $this->get_userlist();
$quoteduserlist = implode("', '", addslashes_recursive($userlist));
$quoteduserlist = "'$quoteduserlist'";
- ///
- /// delete obsolete internal users
- ///
-
- // find obsolete users
- if (count($userlist)) {
- $sql = 'SELECT u.id, u.username
- FROM ' . $CFG->prefix .'user u
- WHERE u.auth=\'db\' AND u.deleted=\'0\' AND u.username NOT IN (' . $quoteduserlist . ')';
- } else {
- $sql = 'SELECT u.id, u.username
- FROM ' . $CFG->prefix .'user u
- WHERE u.auth=\'db\' AND u.deleted=\'0\' ';
- }
- $remove_users = get_records_sql($sql);
-
- if (!empty($remove_users)) {
- print_string('auth_dbuserstoremove','auth', count($remove_users));
- echo "\n";
+/// delete obsolete internal users
+ if (!empty($this->config->removeuser)) {
- begin_sql();
- foreach ($remove_users as $user) {
- //following is copy pasted from admin/user.php
- //maybe this should moved to function in lib/datalib.php
- $updateuser = new object();
- $updateuser->id = $user->id;
- $updateuser->deleted = 1;
- $updateuser->timemodified = time();
- if (update_record('user', $updateuser)) {
- echo "\t";
- print_string('auth_dbdeleteuser', 'auth', array($user->username, $user->id));
- echo "\n";
- } else {
- echo "\t";
- print_string('auth_dbdeleteusererror', 'auth', $user->username);
- echo "\n";
+ // find obsolete users
+ if (count($userlist)) {
+ $sql = "SELECT u.id, u.username, u.email
+ FROM {$CFG->prefix}user u
+ WHERE u.auth='db' AND u.deleted=0 AND u.username NOT IN ($quoteduserlist)";
+ } else {
+ $sql = "SELECT u.id, u.username, u.email
+ FROM {$CFG->prefix}user u
+ WHERE u.auth='db' AND u.deleted=0";
+ }
+ $remove_users = get_records_sql($sql);
+
+ if (!empty($remove_users)) {
+ print_string('auth_dbuserstoremove','auth', count($remove_users)); echo "\n";
+
+ begin_sql();
+ foreach ($remove_users as $user) {
+ if ($this->config->removeuser == 2) {
+ //following is copy pasted from admin/user.php
+ //maybe this should moved to function in lib/datalib.php
+ $updateuser = new object();
+ $updateuser->id = $user->id;
+ $updateuser->deleted = 1;
+ $updateuser->username = addslashes("$user->email.".time()); // Remember it just in case
+ $updateuser->email = ''; // Clear this field to free it up
+ $updateuser->idnumber = ''; // Clear this field to free it up
+ $updateuser->timemodified = time();
+ if (update_record('user', $updateuser)) {
+ delete_records('role_assignments', 'userid', $user->id); // unassign all roles
+ //copy pasted part ends
+ echo "\t"; print_string('auth_dbdeleteuser', 'auth', array($user->username, $user->id)); echo "\n";
+ } else {
+ echo "\t"; print_string('auth_dbdeleteusererror', 'auth', $user->username); echo "\n";
+ }
+ } else if ($this->config->removeuser == 1) {
+ $updateuser = new object();
+ $updateuser->id = $user->id;
+ $updateuser->auth = 'nologin';
+ if (update_record('user', $updateuser)) {
+ echo "\t"; print_string('auth_dbsuspenduser', 'auth', array($user->username, $user->id)); echo "\n";
+ } else {
+ echo "\t"; print_string('auth_dbsuspendusererror', 'auth', $user->username); echo "\n";
+ }
+ }
}
- //copy pasted part ends
+ commit_sql();
}
- commit_sql();
+ unset($remove_users); // free mem!
}
- unset($remove_users); // free mem!
if (!count($userlist)) {
// exit right here
FROM ' . $CFG->prefix .'user u
WHERE u.auth=\'db\' AND u.deleted=\'0\' AND u.username IN (' . $quoteduserlist . ')';
if ($update_users = get_records_sql($sql)) {
+ print "User entries to update: ". count($update_users). "\n";
foreach ($update_users as $user) {
- $this->db_update_user_record(addslashes($user->username), $updatekeys);
+ echo "\t"; print_string('auth_dbupdatinguser', 'auth', array($user->username, $user->id));
+ if (!$this->update_user_record(addslashes($user->username), $updatekeys)) {
+ echo " - ".get_string('skipped');
+ }
+ echo "\n";
}
unset($update_users); // free memory
}
unset($usernames);
if (!empty($add_users)) {
- print_string('auth_dbuserstoadd','auth',count($add_users));
- echo "\n";
+ print_string('auth_dbuserstoadd','auth',count($add_users)); echo "\n";
begin_sql();
foreach($add_users as $user) {
$username = $user;
if ($old_user = get_record('user', 'username', $user->username, 'deleted', 1, 'mnethostid', $user->mnethostid)) {
$user->id = $old_user->id;
set_field('user', 'deleted', 0, 'username', $user->username);
- echo "\t";
- print_string('auth_dbrevive','auth',array(stripslashes($user->username), $user->id));
- echo "\n";
+ echo "\t"; print_string('auth_dbreviveuser', 'auth', array(stripslashes($user->username), $user->id)); echo "\n";
} elseif ($id = insert_record ('user',$user)) { // it is truly a new user
- echo "\t";
- print_string('auth_dbinsertuser','auth',array(stripslashes($user->username), $id));
- echo "\n";
- $user->id = $id;
+ echo "\t"; print_string('auth_dbinsertuser','auth',array(stripslashes($user->username), $id)); echo "\n";
// if relevant, tag for password generation
if ($this->config->passtype === 'internal') {
set_user_preference('auth_forcepasswordchange', 1, $id);
set_user_preference('create_password', 1, $id);
}
} else {
- echo "\t";
- print_string('auth_dbinsertusererror', 'auth', $user->username);
- echo "\n";
+ echo "\t"; print_string('auth_dbinsertusererror', 'auth', $user->username); echo "\n";
}
}
commit_sql();
return true;
}
- function user_exists ($username) {
+ function user_exists($username) {
$textlib = textlib_get_instance();
$extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->extencoding);
- // Connect to the external database (forcing new connection)
- $authdb = &ADONewConnection($this->config->type);
- if (!empty($this->config->debugauthdb)) {
- $authdb->debug = true;
- ob_start();//start output buffer to allow later use of the page headers
- }
- $authdb->Connect($this->config->host, $this->config->user, $this->config->pass, $this->config->name, true);
- $authdb->SetFetchMode(ADODB_FETCH_ASSOC);
- if (!empty($this->config->setupsql)) {
- $authdb->Execute($this->config->setupsql);
- }
+ $authdb = $this->db_init();
$rs = $authdb->Execute("SELECT * FROM {$this->config->table}
WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' ");
function get_userlist() {
- // Connect to the external database (forcing new connection)
- $authdb = &ADONewConnection($this->config->type);
- if (!empty($this->config->debugauthdb)) {
- $authdb->debug = true;
- ob_start();//start output buffer to allow later use of the page headers
- }
- $authdb->Connect($this->config->host, $this->config->user, $this->config->pass, $this->config->name, true);
- $authdb->SetFetchMode(ADODB_FETCH_ASSOC);
- if (!empty($this->config->setupsql)) {
- $authdb->Execute($this->config->setupsql);
- }
+ $authdb = $this->db_init();
// fetch userlist
$rs = $authdb->Execute("SELECT {$this->config->fielduser} AS username
*
* @param string $username username (with system magic quotes)
*/
- function db_update_user_record($username, $updatekeys=false) {
+ function update_user_record($username, $updatekeys=false) {
global $CFG;
- $pcfg = get_config('auth/db');
-
//just in case check text case
$username = trim(moodle_strtolower($username));
// Ensure userid is not overwritten
$userid = $user->id;
- // TODO: this had a function_exists() - now we have a $this
if ($newinfo = $this->get_userinfo($username)) {
$newinfo = truncate_userinfo($newinfo);
}
if (!empty($this->config->{'field_updatelocal_' . $key})) {
- if ($user->{$key} != $value) { // only update if it's changed
- set_field('user', $key, addslashes($value), 'id', $userid);
- }
+ if ($user->{$key} != $value) { // only update if it's changed
+ set_field('user', $key, addslashes($value), 'id', $userid);
+ }
}
}
}
- return get_record_select("user", "id = '$userid' AND deleted <> '1'");
+ return get_record_select('user', "id = $userid AND deleted = 0");
+ }
+
+ /**
+ * Called when the user record is updated.
+ * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
+ * conpares information saved modified information to external db.
+ *
+ * @param mixed $olduser Userobject before modifications (without system magic quotes)
+ * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
+ * @return boolean result
+ *
+ */
+ function user_update($olduser, $newuser) {
+ if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
+ error_log("ERROR:User renaming not allowed in ext db");
+ return false;
+ }
+
+ if (isset($olduser->auth) and $olduser->auth != 'db') {
+ return true; // just change auth and skip update
+ }
+
+ $curruser = $this->get_userinfo($olduser->username);
+ if (empty($curruser)) {
+ error_log("ERROR:User $olduser->username found in ext db");
+ return false;
+ }
+
+ $textlib = textlib_get_instance();
+ $extusername = $textlib->convert($olduser->username, 'utf-8', $this->config->extencoding);
+
+ $authdb = $this->db_init();
+
+ $update = array();
+ foreach($curruser as $key=>$value) {
+ if ($key == 'username') {
+ continue; // skip this
+ }
+ if (empty($this->config->{"field_updateremote_$key"})) {
+ continue; // remote update not requested
+ }
+ if (!isset($newuser->$key)) {
+ continue;
+ }
+ $nuvalue = stripslashes($newuser->$key);
+ if ($nuvalue != $value) {
+ $update[] = $this->config->{"field_map_$key"}."='".$this->ext_addslashes($textlib->convert($nuvalue, 'utf-8', $this->config->extencoding))."'";
+ }
+ }
+ if (!empty($update)) {
+ $authdb->Execute("UPDATE {$this->config->table}
+ SET ".implode(',', $update)."
+ WHERE {$this->config->fielduser}='".$this->ext_addslashes($extusername)."'");
+ }
+ $authdb->Close();
+ return true;
}
/**
/**
* Returns true if this authentication plugin is 'internal'.
*
- * @returns bool
+ * @return bool
*/
function is_internal() {
return false;
* Returns true if this authentication plugin can change the user's
* password.
*
- * @returns bool
+ * @return bool
*/
function can_change_password() {
return ($this->config->passtype === 'internal');
* Returns the URL for changing the user's pw, or false if the default can
* be used.
*
- * @returns bool
+ * @return bool
*/
function change_password_url() {
return $this->config->changepasswordurl;
*
* @param array $page An object containing all the data for this page.
*/
- function config_form($config, $err) {
+ function config_form($config, $err, $user_fields) {
include 'config.html';
}
if (!isset($config->debugauthdb)) {
$config->debugauthdb = 0;
}
+ if (!isset($config->removeuser)) {
+ $config->removeuser = 0;
+ }
if (!isset($config->changepasswordurl)) {
$config->changepasswordurl = '';
}
set_config('fieldpass', $config->fieldpass, 'auth/db');
set_config('passtype', $config->passtype, 'auth/db');
set_config('extencoding', trim($config->extencoding), 'auth/db');
- set_config('setupsql', trim($config->setupsql), 'auth/db');
+ set_config('setupsql', trim($config->setupsql),'auth/db');
set_config('debugauthdb', $config->debugauthdb, 'auth/db');
+ set_config('removeuser', $config->removeuser, 'auth/db');
set_config('changepasswordurl', trim($config->changepasswordurl), 'auth/db');
return true;
/** auth_db_sync_users.php
*
* This script is meant to be called from a system cronjob to
- * sync moodle user accounts with external database
- * when using internal passwords (== passwords not defined in external database).
+ * sync moodle user accounts with external database.
+ * It is required when using internal passwords (== passwords not defined in external database).
*
* Recommended cron entry:
* # 5 minutes past 4am
require_once(dirname(dirname(dirname(__FILE__))).'/config.php'); // global moodle config file.
require_once($CFG->libdir.'/blocklib.php');
-require_once($CFG->libdir.'/moodlelib.php');
require_once($CFG->dirroot.'/course/lib.php');
require_once($CFG->dirroot.'/mod/resource/lib.php');
require_once($CFG->dirroot.'/mod/forum/lib.php');
+
+if (!is_enabled_auth('db')) {
+ echo "Plugin not enabled!";
+ die;
+}
+
$dbauth = get_auth_plugin('db');
$dbauth->sync_users(true);
// set to defaults if undefined
if (!isset($config->host)) {
- $config->host = "localhost";
+ $config->host = 'localhost';
}
if (!isset($config->type)) {
- $config->type = "mysql";
+ $config->type = 'mysql';
}
if (!isset($config->sybasequoting)) {
$config->sybasequoting = 0;
}
if (!isset($config->name)) {
- $config->name = "";
+ $config->name = '';
}
if (!isset($config->user)) {
- $config->user = "";
+ $config->user = '';
}
if (!isset($config->pass)) {
- $config->pass = "";
+ $config->pass = '';
}
if (!isset($config->table)) {
- $config->table = "";
+ $config->table = '';
}
if (!isset($config->fielduser)) {
- $config->fielduser = "";
+ $config->fielduser = '';
}
if (!isset($config->fieldpass)) {
- $config->fieldpass = "";
+ $config->fieldpass = '';
}
if (!isset($config->passtype)) {
- $config->passtype = "plaintext";
+ $config->passtype = 'plaintext';
}
if (!isset($config->changepasswordurl)) {
$config->changepasswordurl = '';
if (!isset($config->setupsql)) {
$config->setupsql = '';
}
+ if (!isset($config->removeuser)) {
+ $config->removeuser = 0;
+ }
- $pluginconfig = get_config('auth/db');
+ $yesno = array( get_string('no'), get_string('yes') );
?>
<table cellspacing="0" cellpadding="5" border="0" align="center">
</td>
<td>
- <?php print_string("auth_dbtype","auth") ?>
+ <?php print_string("auth_dbtype","auth") ?>
</td>
</tr>
<tr valign="top" class="required">
- <td align="right"><label for="sybasequoting"><?php print_string("auth_dbsybasequoting", "auth") ?></label></td>
+ <td align="right"><label for="menusybasequoting"><?php print_string("auth_dbsybasequoting", "auth") ?></label></td>
<td>
- <select id="sybasequoting" name="sybasequoting">
- <option value="0" <?php echo ($config->sybasequoting ? '' : 'selected="yes"') ?> >
- <?php print_string('no') ?></option>
- <option value="1" <?php echo ($config->sybasequoting ? 'selected="yes"' : '') ?> >
- <?php print_string('yes') ?></option>
- </select>
+ <?php choose_from_menu($yesno, 'sybasequoting', $config->sybasequoting, ''); ?>
</td>
<td><?php print_string("auth_dbsybasequotinghelp", "auth") ?></td>
</tr>
<td align="right"><label for="menupasstype"><?php print_string("auth_dbpasstype_key", "auth") ?></label></td>
<td>
<?php
-
+ $passtype = array();
$passtype["plaintext"] = get_string("plaintext", "auth");
$passtype["md5"] = get_string("md5", "auth");
$passtype["sha1"] = get_string("sha1", "auth");
</tr>
<tr valign="top">
- <td align="right"><label for="debugauthdb"><?php print_string("auth_dbdebugauthdb", "auth") ?></label></td>
+ <td align="right"><label for="menudebugauthdb"><?php print_string("auth_dbdebugauthdb", "auth") ?></label></td>
<td>
- <select id="debugauthdb" name="debugauthdb">
- <option value="0" <?php echo ($config->debugauthdb ? '' : 'selected="yes"') ?> >
- <?php print_string('no') ?></option>
- <option value="1" <?php echo ($config->debugauthdb ? 'selected="yes"' : '') ?> >
- <?php print_string('yes') ?></option>
- </select>
+ <?php choose_from_menu($yesno, 'debugauthdb', $config->debugauthdb, ''); ?>
</td>
<td><?php print_string("auth_dbdebugauthdbhelp", "auth") ?></td>
</tr>
</td>
<td><?php print_string('changepasswordhelp', 'auth') ?></td>
</tr>
+
+<tr>
+ <td colspan="2">
+ <h4><?php print_string('auth_sync_script', 'auth') ?> </h4>
+ </td>
+</tr>
+
+<tr valign="top">
+ <td align="right"><label for="menuremoveuser"><?php print_string('auth_remove_user_key','auth') ?></label></td>
+ <td>
+ <?php
+ $deleteopt = array();
+ $deleteopt['0'] = get_string('auth_remove_keep','auth');
+ $deleteopt['1'] = get_string('auth_remove_suspend','auth');
+ $deleteopt['2'] = get_string('auth_remove_delete','auth');
+ choose_from_menu($deleteopt, 'removeuser', $config->removeuser, '');
+ ?>
+ </td>
+ <td>
+ <?php print_string('auth_remove_user','auth') ?>
+ </td>
+</tr>
+
<?php
-global $user_fields;
-print_auth_lock_options('db', $user_fields, get_string('auth_dbextrafields', 'auth'), true, false);
+print_auth_lock_options('db', $user_fields, get_string('auth_dbextrafields', 'auth'), true, true);
?>
</table>
* 2006-08-28 File created.
*/
-// This page cannot be called directly
-if (!isset($CFG)) exit;
+if (!defined('MOODLE_INTERNAL')) {
+ die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
+}
/**
* Error codes for user confirm
*
* @param string $username The username
* @param string $password The password
- * @returns bool Authentication success or failure.
+ * @return bool Authentication success or failure.
*/
function user_login ($username, $password) {
global $CFG;
$emailconfirm = get_string('emailconfirm');
print_header($emailconfirm, $emailconfirm, $emailconfirm);
notice(get_string('emailconfirmsent', '', $user->email), "$CFG->wwwroot/index.php");
- }
+ }
}
/*
/**
* Returns true if this authentication plugin is 'internal'.
*
- * @returns bool
+ * @return bool
*/
function is_internal() {
return true;
}
-
+
/**
* Returns true if this authentication plugin can change the user's
* password.
*
- * @returns bool
+ * @return bool
*/
function can_change_password() {
return true;
}
-
+
/**
* Returns the URL for changing the user's pw, or false if the default can
* be used.
*
- * @returns bool
+ * @return bool
*/
function change_password_url() {
return false;
}
-
+
/**
* Prints a form for configuring this authentication plugin.
*
*
* @param array $page An object containing all the data for this page.
*/
- function config_form($config, $err) {
+ function config_form($config, $err, $user_fields) {
include "config.html";
}
function process_config($config) {
return true;
}
-
+
}
?>
<div align="center"><?php print_string('none'); ?></div>
<table cellspacing="0" cellpadding="5" border="0" align="center">
-<?php
+<?php
-global $user_fields;
print_auth_lock_options('email', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
Moodle - FirstClass authentication module
-----------------------------------------
This module uses the FirstClass Flexible Provisining Protocol (FPP) to communicate between the FirstClass server
-and the Moodle host.
+and the Moodle host.
Installation
------------
1. Enable FPP on the FirstClass server
FPP is not doumented in the FirstClass documentation and is not enable by default.
To enable the protocol you need to edit the file \FCPO\Server\Netinfo. Open the file and insert the
-following lines.
+following lines.
// TCP port for Flexible Provisioning Protocol (FPP).
TCPFPPPORT = 3333
3. Check that the FPP protocoll is working by running a Telnet session. If everyting is working you
-should get a "+0" answer from the server.
+should get a "+0" answer from the server.
> telnet yourhost.domain.com 3333
+0
4. On the Moodle host go to the directory where you have installed Moodle.
Open the folder "auth", where all other authentication modules are installed,
- and create a new directory with the name "fc".
+ and create a new directory with the name "fc".
Copy the files "config.html", "fcFPP.php" and "lib.php" to the "auth" directory.
* 2006-08-28 File created.
*/
-// This page cannot be called directly
-if (!isset($CFG)) exit;
+if (!defined('MOODLE_INTERNAL')) {
+ die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
+}
-require_once 'fcFPP.php';\r
+require_once 'fcFPP.php';
/**
* FirstClass authentication plugin.
*
* @param string $username The username
* @param string $password The password
- * @returns bool Authentication success or failure.
+ * @return bool Authentication success or failure.
*/
function user_login ($username, $password) {
global $CFG;
}
}
$fpp->close();
-
+
return $retval;
}
country -
lang -
timezone 8030 (Not used yet. Need to figure out how FC codes timezones)
-
+
description Get data from users resume. Pictures will be removed.
-
+
*/
$userinfo = array();
-
+
$fpp = new fcFPP($this->config->host, $this->config->port);
if ($fpp->open()) {
if ($fpp->login($this->config->userid, $this->config->passwd)) {
}
}
$fpp->close();
-
+
foreach($userinfo as $key => $value) {
if (!$value) {
unset($userinfo[$key]);
return $userinfo;
}
-
+
/**
* Get users group membership from the FirstClass server user and check if
* user is member of one of the groups of creators.
*/
function iscreator($username = 0) {
global $USER;
-
+
if (! $this->config->creators) {
return false;
}
if (! $username) {
$username = $USER->username;
}
-
+
$fcgroups = array();
-
+
$fpp = new fcFPP($this->config->host, $this->config->port);
if ($fpp->open()) {
if ($fpp->login($this->config->userid, $this->config->passwd)) {
}
}
$fpp->close();
-
+
if ((! $fcgroups)) {
return false;
}
-
+
$creators = explode(";", $this->config->creators);
-
+
foreach($creators as $creator) {
If (in_array($creator, $fcgroups)) return true;
}
-
+
return false;
}
/**
* Returns true if this authentication plugin is 'internal'.
*
- * @returns bool
+ * @return bool
*/
function is_internal() {
return false;
* Returns true if this authentication plugin can change the user's
* password.
*
- * @returns bool
+ * @return bool
*/
function can_change_password() {
return false;
*
* @param array $page An object containing all the data for this page.
*/
- function config_form($config, $err) {
+ function config_form($config, $err, $user_fields) {
include "config.html";
}
}
if (!isset($config->creators)) {
$config->creators = "";
- }
+ }
if (!isset($config->changepasswordurl)) {
$config->changepasswordurl = '';
- }
+ }
if (!isset($config->changepasswordurl)) {
$config->changepasswordurl = '';
}
<td><?php print_string('changepasswordhelp', 'auth') ?></td>
</tr>
-<?php
+<?php
-global $user_fields;
print_auth_lock_options('fc', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
*/
class fcFPP
-{
+{
var $_hostname; // hostname of FirstClass server we are connection to
var $_port; // port on which fpp is running
var $_conn = 0; // socket we are connecting on
var $_debug = FALSE; // set to true to see some debug info
-
+
// class constructor
function fcFPP($host="localhost", $port="3333")
{
$this->_hostname = $host;
$this->_port = $port;
$this->_user = "";
- $this->_pwd = "";
+ $this->_pwd = "";
}
-
+
// open a connection to the FirstClass server
function open()
{
print_error('auth_fcconnfail','auth', array($errno, $errstr));
return false;
}
-
+
// We are connected
if ($this->_debug) echo "connected!";
-
+
// Read connection message.
$line = fgets ($conn); //+0
$line = fgets ($conn); //new line
// close any open connections
function close()
- {
+ {
// get the current connection
$conn = &$this->_conn;
}
return;
}
-
-
+
+
// Authenticate to the FirstClass server
function login($userid, $passwd)
{
$line = fgets ($this->_conn); //new line
$line = fgets ($this->_conn); //+0
$line = fgets ($this->_conn); //new line
-
+
# Send password
fputs($this->_conn,"$passwd\r\n");
$line = fgets ($this->_conn); //new line
$line = fgets ($this->_conn); //+0
$line = fgets ($this->_conn); //+0 or message
-
+
if ($this->_debug) echo $line;
-
+
if (preg_match ("/^\+0/", $line)) { //+0, user with subadmin privileges
$this->_user = $userid;
- $this->_pwd = $passwd;
- return TRUE;
+ $this->_pwd = $passwd;
+ return TRUE;
} elseif (strpos($line, 'You are not allowed')) { // Denied access but a valid user and password
// "Sorry. You are not allowed to login with the FPP interface"
return TRUE;
} else { //Invalid user or password
return FALSE;
}
-
+
}
return FALSE;
}
- // Get the list of groups the user is a member of
+ // Get the list of groups the user is a member of
function getGroups($userid) {
-
+
$groups = array();
-
- // we must be logged in as a user with subadmin privileges
+
+ // we must be logged in as a user with subadmin privileges
if ($this->_conn AND $this->_user) {
# Send BA-command to get groups
fputs($this->_conn,"GET USER '" . $userid . "' 4 -1\r");
}
if ($this->_debug) echo "getGroups:" . implode(",",$groups);
}
-
+
return $groups;
}
// Check if the user is member of any of the groups.
// Return the list of groups the user is member of.
function isMemberOf($userid, $groups) {
-
+
$usergroups = array_map("strtolower",$this->getGroups($userid));
$groups = array_map("strtolower",$groups);
-
+
$result = array_intersect($groups,$usergroups);
-
+
if ($this->_debug) echo "isMemberOf:" . implode(",",$result);
-
+
return $result;
}
-
+
function getUserInfo($userid, $field) {
-
+
$userinfo = "";
-
+
if ($this->_conn AND $this->_user) {
# Send BA-command to get data
fputs($this->_conn,"GET USER '" . $userid . "' " . $field . "\r");
}
if ($this->_debug) echo "getUserInfo:" . $userinfo;
}
-
+
return str_replace('\r',' ',trim($userinfo,'"'));
}
function getResume($userid) {
-
+
$resume = "";
$pattern = "/\[.+:.+\..+\]/"; // Remove references to pictures in resumes
-
+
if ($this->_conn AND $this->_user) {
# Send BA-command to get data
fputs($this->_conn,"GET RESUME '" . $userid . "' 6\r");
$resume .= preg_replace($pattern,"",str_replace('\r',"\n",trim($line,'6 ')));
$line = trim(fgets ($this->_conn));
//print $line;
-
+
}
if ($this->_debug) echo "getResume:" . $resume;
}
-
+
return $resume;
}
-
-
+
+
}
-
+
?>
* 2006-08-31 File created.
*/
-// This page cannot be called directly
-if (!isset($CFG)) exit;
+if (!defined('MOODLE_INTERNAL')) {
+ die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
+}
/**
* IMAP authentication plugin.
*
* @param string $username The username
* @param string $password The password
- * @returns bool Authentication success or failure.
+ * @return bool Authentication success or failure.
*/
function user_login ($username, $password) {
if (! function_exists('imap_open')) {
print_error('auth_imapnotinstalled','mnet');
return false;
}
-
+
global $CFG;
$hosts = split(';', $this->config->host); // Could be multiple hosts
case 'imapssl':
$host = '{'.$host.":{$this->config->port}/imap/ssl}";
break;
-
+
case 'imapcert':
$host = '{'.$host.":{$this->config->port}/imap/ssl/novalidate-cert}";
break;
-
+
case 'imaptls':
$host = '{'.$host.":{$this->config->port}/imap/tls}";
break;
-
+
default:
$host = '{'.$host.":{$this->config->port}/imap}";
}
error_reporting(0);
$connection = imap_open($host, $username, $password, OP_HALFOPEN);
- error_reporting($CFG->debug);
+ error_reporting($CFG->debug);
if ($connection) {
imap_close($connection);
/**
* Returns true if this authentication plugin is 'internal'.
*
- * @returns bool
+ * @return bool
*/
function is_internal() {
return false;
* Returns true if this authentication plugin can change the user's
* password.
*
- * @returns bool
+ * @return bool
*/
function can_change_password() {
return false;
}
-
+
/**
* Returns the URL for changing the user's pw, or false if the default can
* be used.
*
- * @returns bool
+ * @return bool
*/
function change_password_url() {
return $CFG->changepasswordurl; // TODO: will this be global?
//return $this->config->changepasswordurl;
}
-
+
/**
* Prints a form for configuring this authentication plugin.
*
*
* @param array $page An object containing all the data for this page.
*/
- function config_form($config, $err) {
+ function config_form($config, $err, $user_fields) {
include "config.html";
}
<td><?php print_string('changepasswordhelp', 'auth') ?></td>
</tr>
-<?php
+<?php
-global $user_fields;
print_auth_lock_options('imap', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
LDAP-module README
-Please read comments from lib.php
+Please read comments from lib.php
* 2006-08-28 File created.
*/
-// This page cannot be called directly
-if (!isset($CFG)) exit;
-
-// LDAP functions are reused by other auth libs
-if (!defined('AUTH_LDAP_NAME')) {
- define('AUTH_LDAP_NAME', 'ldap');
+if (!defined('MOODLE_INTERNAL')) {
+ die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
/**
var $config;
/**
- * Constructor.
+ * Constructor with initialisation.
*/
function auth_plugin_ldap() {
$this->config = get_config('auth/ldap');
+ if (empty($this->config->ldapencoding)) {
+ $this->config->ldapencoding = 'utf-8';
+ }
+ if (empty($this->config->user_type)) {
+ $this->config->user_type = 'default';
+ }
+
+ $default = $this->ldap_getdefaults();
+
+ //use defaults if values not given
+ foreach ($default as $key => $value) {
+ // watch out - 0, false are correct values too
+ if (!isset($this->config->{$key}) or $this->config->{$key} == '') {
+ $this->config->{$key} = $value[$this->config->user_type];
+ }
+ }
+ //hack prefix to objectclass
+ if ('objectClass=' != substr($this->config->objectclass, 0, 12)) {
+ $this->config->objectclass = 'objectClass='.$this->config->objectclass;
+ }
}
/**
* Returns true if the username and password work and false if they are
* wrong or don't exist.
*
- * @param string $username The username
- * @param string $password The password
- * @returns bool Authentication success or failure.
+ * @param string $username The username (with system magic quotes)
+ * @param string $password The password (with system magic quotes)
+ *
+ * @return bool Authentication success or failure.
*/
function user_login($username, $password) {
if (! function_exists('ldap_bind')) {
return false;
}
- global $CFG;
-
if (!$username or !$password) { // Don't allow blank usernames or passwords
return false;
}
-
- // CAS-supplied auth tokens override LDAP auth
- if ($CFG->auth == "cas" and !empty($CFG->cas_enabled)) {
- return cas_ldap_auth_user_login($username, $password);
- }
+
+ $textlib = textlib_get_instance();
+ $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
+ $extpassword = $textlib->convert(stripslashes($password), 'utf-8', $this->config->ldapencoding);
$ldapconnection = $this->ldap_connect();
if ($ldapconnection) {
- $ldap_user_dn = $this->ldap_find_userdn($ldapconnection, $username);
-
+ $ldap_user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
+
//if ldap_user_dn is empty, user does not exist
if (!$ldap_user_dn) {
ldap_close($ldapconnection);
}
// Try to bind with current username and password
- $ldap_login = @ldap_bind($ldapconnection, $ldap_user_dn, stripslashes($password));
+ $ldap_login = @ldap_bind($ldapconnection, $ldap_user_dn, $extpassword);
ldap_close($ldapconnection);
if ($ldap_login) {
return true;
* Function should return all information available. If you are saving
* this information to moodle user-table you should honor syncronization flags
*
- * @param string $username username
- * @return array
+ * @param string $username username (with system magic quotes)
+ *
+ * @return mixed array with no magic quotes or false on error
*/
function get_userinfo($username) {
- global $CFG;
+ $textlib = textlib_get_instance();
+ $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
+
$ldapconnection = $this->ldap_connect();
- $config = (array)$CFG;
$attrmap = $this->ldap_attributes();
-
+
$result = array();
$search_attribs = array();
-
+
foreach ($attrmap as $key=>$values) {
if (!is_array($values)) {
$values = array($values);
foreach ($values as $value) {
if (!in_array($value, $search_attribs)) {
array_push($search_attribs, $value);
- }
+ }
}
}
- $user_dn = $this->ldap_find_userdn($ldapconnection, $username);
+ $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
if (empty($this->config->objectclass)) { // Can't send empty filter
$this->config->objectclass="objectClass=*";
}
-
- $user_info_result = ldap_read($ldapconnection, $user_dn, $this->config->objectclass, $search_attribs);
- if ($user_info_result) {
- $user_entry = $this->ldap_get_entries($ldapconnection, $user_info_result);
- foreach ($attrmap as $key=>$values) {
- if (!is_array($values)) {
- $values = array($values);
+ if (!$user_info_result = ldap_read($ldapconnection, $user_dn, $this->config->objectclass, $search_attribs)) {
+ return false; // error!
+ }
+ $user_entry = $this->ldap_get_entries($ldapconnection, $user_info_result);
+ if (empty($user_entry)) {
+ return false; // entry not found
+ }
+
+ foreach ($attrmap as $key=>$values) {
+ if (!is_array($values)) {
+ $values = array($values);
+ }
+ $ldapval = NULL;
+ foreach ($values as $value) {
+ if (!array_key_exists($value, $user_entry[0])) {
+ continue; // wrong data mapping!
}
- $ldapval = NULL;
- foreach ($values as $value) {
- if (is_array($user_entry[0][strtolower($value)])) {
- if (!empty($CFG->unicodedb)) {
- $newval = addslashes(stripslashes($user_entry[0][strtolower($value)][0]));
- }
- else {
- $newval = addslashes(stripslashes(utf8_decode($user_entry[0][strtolower($value)][0])));
- }
- }
- else {
- if (!empty($CFG->unicodedb)) {
- $newval = addslashes(stripslashes($user_entry[0][strtolower($value)]));
- }
- else {
- $newval = addslashes(stripslashes(utf8_decode($user_entry[0][strtolower($value)])));
- }
- }
- if (!empty($newval)) { // favour ldap entries that are set
- $ldapval = $newval;
- }
+ if (is_array($user_entry[0][$value])) {
+ $newval = $textlib->convert($user_entry[0][$value][0], $this->config->ldapencoding, 'utf-8');
+ } else {
+ $newval = $textlib->convert($user_entry[0][$value], $this->config->ldapencoding, 'utf-8');
}
- if (!is_null($ldapval)) {
- $result[$key] = $ldapval;
+ if (!empty($newval)) { // favour ldap entries that are set
+ $ldapval = $newval;
}
}
+ if (!is_null($ldapval)) {
+ $result[$key] = $ldapval;
+ }
}
@ldap_close($ldapconnection);
-
return $result;
}
/**
* reads userinformation from ldap and return it in an object
*
- * @param string $username username
- * @return array
+ * @param string $username username (with system magic quotes)
+ * @return mixed object or false on error
*/
function get_userinfo_asobj($username) {
- $user_array = truncate_userinfo($this->get_userinfo($username));
- $user = new object;
+ $user_array = $this->get_userinfo($username);
+ if ($user_array == false) {
+ return false; //error or not found
+ }
+ $user_array = truncate_userinfo($user_array);
+ $user = new object();
foreach ($user_array as $key=>$value) {
$user->{$key} = $value;
}
*
* get_userlist returns all usernames from external database
*
- * @return array
+ * @return array
*/
function get_userlist() {
- global $CFG;
- $this->ldap_init();
return $this->ldap_get_userlist("({$this->config->user_attribute}=*)");
}
/**
* checks if user exists on external db
+ *
+ * @param string $username (with system magic quotes)
*/
function user_exists($username) {
- global $CFG;
- $this->ldap_init();
- //returns true if given usernname exist on ldap
- $users = $this->ldap_get_userlist("({$this->config->user_attribute}=$username)");
- return count($users);
+
+ $textlib = textlib_get_instance();
+ $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
+
+ //returns true if given username exist on ldap
+ $users = $this->ldap_get_userlist("({$this->config->user_attribute}=".$this->filter_addslashes($extusername).")");
+ return count($users);
}
/**
- * creates new user on external database
- *
- * user_create() creates new user on external database
+ * Creates a new user on external database.
* By using information in userobject
* Use user_exists to prevent dublicate usernames
*
- * @param mixed $userobject Moodle userobject
- * @param mixed $plainpass Plaintext password
+ * @param mixed $userobject Moodle userobject (with system magic quotes)
+ * @param mixed $plainpass Plaintext password (with system magic quotes)
*/
function user_create($userobject, $plainpass) {
- global $CFG;
+ $textlib = textlib_get_instance();
+ $extusername = $textlib->convert(stripslashes($userobject->username), 'utf-8', $this->config->ldapencoding);
+ $extpassword = $textlib->convert(stripslashes($plainpass), 'utf-8', $this->config->ldapencoding);
+
$ldapconnection = $this->ldap_connect();
$attrmap = $this->ldap_attributes();
-
+
$newuser = array();
-
+
foreach ($attrmap as $key => $values) {
if (!is_array($values)) {
$values = array($values);
}
foreach ($values as $value) {
if (!empty($userobject->$key) ) {
- if (!empty($CFG->unicodedb)) {
- $newuser[$value] = $userobject->$key;
- }
- else {
- $newuser[$value] = utf8_encode($userobject->$key);
- }
+ $newuser[$value] = $textlib->convert(stripslashes($userobject->$key), 'utf-8', $this->config->ldapencoding);
}
}
}
-
+
//Following sets all mandatory and other forced attribute values
//User should be creted as login disabled untill email confirmation is processed
- //Feel free to add your user type and send patches to paca@sci.fi to add them
+ //Feel free to add your user type and send patches to paca@sci.fi to add them
//Moodle distribution
switch ($this->config->user_type) {
case 'edir':
- $newuser['objectClass']= array("inetOrgPerson","organizationalPerson","person","top");
- $newuser['uniqueId']= $userobject->username;
- $newuser['logindisabled']="TRUE";
- $newuser['userpassword']=$plainpass;
+ $newuser['objectClass'] = array("inetOrgPerson","organizationalPerson","person","top");
+ $newuser['uniqueId'] = $extusername;
+ $newuser['logindisabled'] = "TRUE";
+ $newuser['userpassword'] = $extpassword;
break;
default:
print_error('auth_ldap_unsupportedusertype','auth',$this->config->user_type);
}
- $uadd = $this->ldap_add($ldapconnection, "{$this->config->user_attribute}={$userobject->username},{$this->config->create_context}", $newuser);
+ $uadd = $this->ldap_add($ldapconnection, $this->config->user_attribute.'="'.$this->ldap_addslashes($userobject->username).','.$this->config->create_context.'"', $newuser);
ldap_close($ldapconnection);
return $uadd;
-
- }
-
- /**
- *
- * get_users() returns userobjects from external database
- *
- * Function returns users from external databe as Moodle userobjects
- * If filter is not present it should return ALL users in external database
- *
- * @param mixed $filter substring of username
- * @returns array of userobjects
- */
- function get_users($filter = '*', $dontlistcreated = false) {
- global $CFG;
-
- $ldapconnection = $this->ldap_connect();
- $fresult = array();
- if ($filter=="*") {
- $filter = "(&(".$this->config->user_attribute."=*)(".$this->config->objectclass."))";
- }
-
- $contexts = explode(";",$this->config->contexts);
-
- if (!empty($this->config->create_context) and empty($dontlistcreated)) {
- array_push($contexts, $this->config->create_context);
- }
-
- $attrmap = $this->ldap_attributes();
-
- $search_attribs = array();
-
- foreach ($attrmap as $key=>$values) {
- if (!is_array($values)) {
- $values = array($values);
- }
- foreach ($values as $value) {
- if (!in_array($value, $search_attribs)) {
- array_push($search_attribs, $value);
- }
- }
- }
-
-
- foreach ($contexts as $context) {
-
- $context = trim($context);
- if (empty($context)) {
- continue;
- }
-
- if ($this->config->search_sub) {
- //use ldap_search to find first user from subtree
- $ldap_result = ldap_search($ldapconnection, $context,
- $filter,
- $search_attribs);
- }
- else {
- //search only in this context
- $ldap_result = ldap_list($ldapconnection, $context,
- $filter,
- $search_attribs);
- }
-
- $users = $this->ldap_get_entries($ldapconnection, $ldap_result);
-
- //add found users to list
- foreach ($users as $ldapuser=>$attribs) {
- $user = new object();
- foreach ($attrmap as $key=>$value) {
- if (isset($users[$ldapuser][$value][0])) {
- $user->$key=$users[$ldapuser][$value][0];
- }
- }
- //quick way to get around binarystrings
- $user->guid=bin2hex($user->guid);
- //add authentication source stamp
- $user->auth = AUTH_LDAP_NAME;
- //add MNET host id
- $user->mnethostid = $CFG->mnet_localhost_id;
- $fresult[$user->username]=$user;
-
- }
- }
-
- return $fresult;
}
/**
* @return integer
*/
function password_expire($username) {
- global $CFG ;
$result = false;
-
+
+ $textlib = textlib_get_instance();
+ $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
+
$ldapconnection = $this->ldap_connect();
- $user_dn = $this->ldap_find_userdn($ldapconnection, $username);
+ $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
$search_attribs = array($this->config->expireattr);
$sr = ldap_read($ldapconnection, $user_dn, 'objectclass=*', $search_attribs);
if ($sr) {
- $info=$this->ldap_get_entries($ldapconnection, $sr);
- if ( empty($info[0][strtolower($this->config->expireattr)][0])) {
+ $info = $this->ldap_get_entries($ldapconnection, $sr);
+ if (empty ($info) or empty($info[0][$this->config->expireattr][0])) {
//error_log("ldap: no expiration value".$info[0][$this->config->expireattr]);
// no expiration attribute, password does not expire
$result = 0;
}
else {
$now = time();
- $expiretime = $this->ldap_expirationtime2unix($info[0][strtolower($this->config->expireattr)][0]);
+ $expiretime = $this->ldap_expirationtime2unix($info[0][$this->config->expireattr][0]);
if ($expiretime > $now) {
$result = ceil(($expiretime - $now) / DAYSECS);
}
else {
$result = floor(($expiretime - $now) / DAYSECS);
- }
+ }
}
- }
- else {
+ } else {
error_log("ldap: password_expire did't find expiration time.");
}
/**
* syncronizes user fron external db to moodle user table
*
- * Sync shouid be done by using idnumber attribute, not username.
- * You need to pass firstsync parameter to function to fill in
- * idnumbers if they dont exists in moodle user table.
- *
- * Syncing users removes (disables) users that dont exists anymore in external db.
- * Creates new users and updates coursecreator status of users.
- *
- * @param mixed $firstsync Optional: set to true to fill idnumber fields if not filled yet
+ * Sync is now using username attribute.
+ *
+ * Syncing users removes or suspends users that dont exists anymore in external db.
+ * Creates new users and updates coursecreator status of users.
+ *
+ * @param int $bulk_insert_records will insert $bulkinsert_records per insert statement
+ * valid only with $unsafe. increase to a couple thousand for
+ * blinding fast inserts -- but test it: you may hit mysqld's
+ * max_allowed_packet limit.
+ * @param bool $do_updates will do pull in data updates from ldap if relevant
*/
- function sync_users ($bulk_insert_records = 1000, $do_updates = 1) {
- //Syncronizes userdb with ldap
- //This will add, rename
- /// OPTIONAL PARAMETERS
- /// $bulk_insert_records = 1 // will insert $bulkinsert_records per insert statement
- /// valid only with $unsafe. increase to a couple thousand for
- /// blinding fast inserts -- but test it: you may hit mysqld's
- /// max_allowed_packet limit.
- /// $do_updates = 1 // will do pull in data updates from ldap if relevant
-
+ function sync_users ($bulk_insert_records = 1000, $do_updates = true) {
global $CFG;
+ $textlib = textlib_get_instance();
+
$droptablesql = array(); /// sql commands to drop the table (because session scope could be a problem for
/// some persistent drivers like ODBTP (mssql) or if this function is invoked
/// from within a PHP application using persistent connections
- // configure a temp table
- print "Configuring temp table\n";
+ // configure a temp table
+ print "Configuring temp table\n";
switch (strtolower($CFG->dbfamily)) {
case 'mysql':
$temptable = $CFG->prefix . 'extuser';
$droptablesql[] = 'DROP TEMPORARY TABLE ' . $temptable; // sql command to drop the table (because session scope could be a problem)
execute_sql_arr($droptablesql, true, false); /// Drop temp table to avoid persistence problems later
echo "Creating temp table $temptable\n";
- execute_sql('CREATE TEMPORARY TABLE ' . $temptable . ' (idnumber VARCHAR(64), PRIMARY KEY (idnumber)) TYPE=MyISAM', false);
+ execute_sql('CREATE TEMPORARY TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username)) TYPE=MyISAM', false);
break;
case 'postgres':
$temptable = $CFG->prefix . 'extuser';
execute_sql_arr($droptablesql, true, false); /// Drop temp table to avoid persistence problems later
echo "Creating temp table $temptable\n";
$bulk_insert_records = 1; // no support for multiple sets of values
- execute_sql('CREATE TEMPORARY TABLE '. $temptable . ' (idnumber VARCHAR(64), PRIMARY KEY (idnumber))', false);
+ execute_sql('CREATE TEMPORARY TABLE '. $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))', false);
break;
case 'mssql':
$temptable = '#'.$CFG->prefix . 'extuser'; /// MSSQL temp tables begin with #
execute_sql_arr($droptablesql, true, false); /// Drop temp table to avoid persistence problems later
echo "Creating temp table $temptable\n";
$bulk_insert_records = 1; // no support for multiple sets of values
- execute_sql('CREATE TABLE ' . $temptable . ' (idnumber VARCHAR(64), PRIMARY KEY (idnumber))', false);
+ execute_sql('CREATE TABLE ' . $temptable . ' (username VARCHAR(64), PRIMARY KEY (username))', false);
break;
case 'oracle':
$temptable = $CFG->prefix . 'extuser';
execute_sql_arr($droptablesql, true, false); /// Drop temp table to avoid persistence problems later
echo "Creating temp table $temptable\n";
$bulk_insert_records = 1; // no support for multiple sets of values
- execute_sql('CREATE GLOBAL TEMPORARY TABLE '.$temptable.' (idnumber VARCHAR(64), PRIMARY KEY (idnumber)) ON COMMIT PRESERVE ROWS', false);
+ execute_sql('CREATE GLOBAL TEMPORARY TABLE '.$temptable.' (username VARCHAR(64), PRIMARY KEY (username)) ON COMMIT PRESERVE ROWS', false);
break;
}
- print "connecting to ldap\n";
+ print "Connecting to ldap...\n";
$ldapconnection = $this->ldap_connect();
if (!$ldapconnection) {
@ldap_close($ldapconnection);
- notify(get_string('auth_ldap_noconnect','auth',$this->config->host_url));
- return false;
+ print get_string('auth_ldap_noconnect','auth',$this->config->host_url);
+ exit;
}
////
$filter = "(&(".$this->config->user_attribute."=*)(".$this->config->objectclass."))";
$contexts = explode(";",$this->config->contexts);
-
+
if (!empty($this->config->create_context)) {
array_push($contexts, $this->config->create_context);
}
$fresult = array();
- $count = 0;
foreach ($contexts as $context) {
$context = trim($context);
if (empty($context)) {
$ldap_result = ldap_search($ldapconnection, $context,
$filter,
array($this->config->user_attribute));
- }
- else {
+ } else {
//search only in this context
$ldap_result = ldap_list($ldapconnection, $context,
$filter,
if ($entry = ldap_first_entry($ldapconnection, $ldap_result)) {
do {
- $value = ldap_get_values_len($ldapconnection, $entry,$this->config->user_attribute);
- $value = $value[0];
- $count++;
+ $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
+ $value = $textlib->convert($value[0], $this->config->ldapencoding, 'utf-8');
array_push($fresult, $value);
if (count($fresult) >= $bulk_insert_records) {
$this->ldap_bulk_insert($fresult, $temptable);
- //print var_dump($fresult);
- $fresult=array();
- }
- }
- while ($entry = ldap_next_entry($ldapconnection, $entry));
+ $fresult = array();
+ }
+ } while ($entry = ldap_next_entry($ldapconnection, $entry));
}
+ unset($ldap_result); // free mem
// insert any remaining users and release mem
if (count($fresult)) {
$this->ldap_bulk_insert($fresult, $temptable);
- $fresult=array();
+ $fresult = array();
}
commit_sql();
}
- // free mem
- $ldap_results = 0;
/// preserve our user database
/// if the temp table is empty, it probably means that something went wrong, exit
/// so as to avoid mass deletion of users; which is hard to undo
- $count = get_record_sql('SELECT COUNT(idnumber) AS count, 1 FROM ' . $temptable);
+ $count = get_record_sql('SELECT COUNT(username) AS count, 1 FROM ' . $temptable);
$count = $count->{'count'};
if ($count < 1) {
print "Did not get any users from LDAP -- error? -- exiting\n";
exit;
} else {
- print "Got $count records from LDAP\n";
+ print "Got $count records from LDAP\n\n";
}
- ////
- //// User removal
- ////
- // find users in DB that aren't in ldap -- to be removed!
- // this is still not as scalable
- $sql = 'SELECT u.id, u.username
- FROM ' . $CFG->prefix .'user u LEFT JOIN ' . $temptable . ' e
- ON u.idnumber = e.idnumber
- WHERE u.auth=\'' . AUTH_LDAP_NAME . '\' AND u.deleted=\'0\' AND e.idnumber IS NULL';
- //print($sql);
- $remove_users = get_records_sql($sql);
- if (!empty($remove_users)) {
- print "User entries to remove: ". count($remove_users) . "\n";
-
- begin_sql();
- foreach ($remove_users as $user) {
- //following is copy pasted from admin/user.php
- //maybe this should moved to function in lib/datalib.php
- $updateuser = new stdClass();
- $updateuser->id = $user->id;
- $updateuser->deleted = '1';
- //$updateuser->username = "$user->username".time(); // Remember it just in case
- //$updateuser->email = ''; // Clear this field to free it up
- $updateuser->timemodified = time();
- if (update_record("user", $updateuser)) {
- // unenrol_student($user->id); // From all courses
- // remove_teacher($user->id); // From all courses
- // remove_admin($user->id);
- delete_records('role_assignments', 'userid', $user->id); // unassign all roles
- notify(get_string('deletedactivity', '', fullname($user, true)) );
+/// User removal
+ // find users in DB that aren't in ldap -- to be removed!
+ // this is still not as scalable (but how often do we mass delete?)
+ if (!empty($this->config->removeuser)) {
+ $sql = "SELECT u.id, u.username, u.email
+ FROM {$CFG->prefix}user u
+ LEFT JOIN $temptable e ON u.username = e.username
+ WHERE u.auth='ldap'
+ AND u.deleted=0
+ AND e.username IS NULL";
+ $remove_users = get_records_sql($sql);
+
+ if (!empty($remove_users)) {
+ print "User entries to remove: ". count($remove_users) . "\n";
+
+ begin_sql();
+ foreach ($remove_users as $user) {
+ if ($this->config->removeuser == 2) {
+ //following is copy pasted from admin/user.php
+ //maybe this should moved to function in lib/datalib.php
+ $updateuser = new object();
+ $updateuser->id = $user->id;
+ $updateuser->deleted = 1;
+ $updateuser->username = addslashes("$user->email.".time()); // Remember it just in case
+ $updateuser->email = ''; // Clear this field to free it up
+ $updateuser->idnumber = ''; // Clear this field to free it up
+ $updateuser->timemodified = time();
+ if (update_record('user', $updateuser)) {
+ delete_records('role_assignments', 'userid', $user->id); // unassign all roles
+ //copy pasted part ends
+ echo "\t"; print_string('auth_dbdeleteuser', 'auth', array($user->username, $user->id)); echo "\n";
+ } else {
+ echo "\t"; print_string('auth_dbdeleteusererror', 'auth', $user->username); echo "\n";
+ }
+ } else if ($this->config->removeuser == 1) {
+ $updateuser = new object();
+ $updateuser->id = $user->id;
+ $updateuser->auth = 'nologin';
+ if (update_record('user', $updateuser)) {
+ echo "\t"; print_string('auth_dbsuspenduser', 'auth', array($user->username, $user->id)); echo "\n";
+ } else {
+ echo "\t"; print_string('auth_dbsuspendusererror', 'auth', $user->username); echo "\n";
+ }
+ }
}
- else {
- notify(get_string('deletednot', '', fullname($user, true)));
+ commit_sql();
+ } else {
+ print "No user entries to be removed\n";
+ }
+ unset($remove_users); // free mem!
+ }
+
+/// Revive suspended users
+ if (!empty($this->config->removeuser) and $this->config->removeuser == 1) {
+ $sql = "SELECT u.id, u.username
+ FROM $temptable e, {$CFG->prefix}user u
+ WHERE e.username=u.username
+ AND u.auth='nologin'";
+ $revive_users = get_records_sql($sql);
+
+ if (!empty($revive_users)) {
+ print "User entries to be revived: ". count($revive_users) . "\n";
+
+ begin_sql();
+ foreach ($revive_users as $user) {
+ $updateuser = new object();
+ $updateuser->id = $user->id;
+ $updateuser->auth = 'ldap';
+ if (update_record('user', $updateuser)) {
+ echo "\t"; print_string('auth_dbreviveser', 'auth', array($user->username, $user->id)); echo "\n";
+ } else {
+ echo "\t"; print_string('auth_dbreviveusererror', 'auth', $user->username); echo "\n";
+ }
}
- //copy pasted part ends
- }
- commit_sql();
- } else {
- print "No user entries to be removed\n";
+ commit_sql();
+ } else {
+ print "No user entries to be revived\n";
+ }
+
+ unset($revive_users);
}
- $remove_users = 0; // free mem!
- ////
- //// User Updates
- //// (time-consuming, optional)
- ////
+
+/// User Updates - time-consuming (optional)
if ($do_updates) {
// narrow down what fields we need to update
$all_keys = array_keys(get_object_vars($this->config));
foreach ($all_keys as $key) {
if (preg_match('/^field_updatelocal_(.+)$/',$key, $match)) {
// if we have a field to update it from
- // and it must be updated 'onlogin' we
+ // and it must be updated 'onlogin' we
// update it on cron
if ( !empty($this->config->{'field_map_'.$match[1]})
- and $this->config->{$match[0]} === 'onlogin') {
+ and $this->config->{$match[0]} === 'onlogin') {
array_push($updatekeys, $match[1]); // the actual key name
}
}
}
// print_r($all_keys); print_r($updatekeys);
unset($all_keys); unset($key);
-
+
} else {
print "No updates to be done\n";
}
- if ( $do_updates and !(empty($updatekeys)) ) { // run updates only if relevant
- $users = get_records_sql('SELECT u.username, u.id FROM ' . $CFG->prefix . 'user u WHERE u.deleted=0 and u.auth=\'' . AUTH_LDAP_NAME . '\'' );
+ if ( $do_updates and !empty($updatekeys) ) { // run updates only if relevant
+ $users = get_records_sql("SELECT u.username, u.id
+ FROM {$CFG->prefix}user u
+ WHERE u.deleted=0 AND u.auth='ldap'");
if (!empty($users)) {
print "User entries to update: ". count($users). "\n";
+
$sitecontext = get_context_instance(CONTEXT_SYSTEM);
+ if (!empty($this->config->creators) and !empty($this->config->memberattribute)
+ and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
+ $creatorrole = array_shift($roles); // We can only use one, let's use the first one
+ } else {
+ $creatorrole = false;
+ }
- if ($creatorroles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
- $creatorrole = array_shift($creatorroles); // We can only use one, let's use the first one
-
- begin_sql();
- $xcount = 0;
- $maxxcount = 100;
-
- foreach ($users as $user) {
- echo "updating user $user->username \n";
- $this->update_user_record($user->username, $updatekeys);
-
- // update course creators
- if (!empty($this->config->creators) and !empty($this->config->memberattribute) ) {
- if ($this->iscreator($user->username)) { // Following calls will not create duplicates
- role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
- $xcount++;
- } else {
- role_unassign($creatorrole->id, $user->id, 0, $sitecontext->id);
- $xcount++;
- }
- }
+ begin_sql();
+ $xcount = 0;
+ $maxxcount = 100;
- if ($xcount++ > $maxxcount) {
- commit_sql();
- begin_sql();
- $xcount = 0;
+ foreach ($users as $user) {
+ echo "\t"; print_string('auth_dbupdatinguser', 'auth', array($user->username, $user->id));
+ if (!$this->update_user_record(addslashes($user->username), $updatekeys)) {
+ echo " - ".get_string('skipped');
+ }
+ echo "\n";
+ $xcount++;
+
+ // update course creators if needed
+ if ($creatorrole !== false) {
+ if ($this->iscreator($user->username)) {
+ role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
+ } else {
+ role_unassign($creatorrole->id, $user->id, 0, $sitecontext->id);
}
- }
- commit_sql();
- unset($users); // free mem
+ }
+
+ if ($xcount++ > $maxxcount) {
+ commit_sql();
+ begin_sql();
+ $xcount = 0;
+ }
}
+ commit_sql();
+ unset($users); // free mem
}
} else { // end do updates
print "No updates to be done\n";
}
-
- ////
- //// User Additions
- ////
+
+/// User Additions
// find users missing in DB that are in LDAP
// note that get_records_sql wants at least 2 fields returned,
// and gives me a nifty object I don't want.
- $sql = 'SELECT e.idnumber,1
- FROM ' . $temptable . ' e LEFT JOIN ' . $CFG->prefix .'user u
- ON e.idnumber = u.idnumber
- WHERE u.id IS NULL OR (u.id IS NOT NULL AND u.deleted=1)';
- $add_users = get_records_sql($sql); // get rid of the fat
-
+ // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
+ $sql = "SELECT e.username, e.username
+ FROM $temptable e LEFT JOIN {$CFG->prefix}user u ON e.username = u.username
+ WHERE u.id IS NULL";
+ $add_users = get_records_sql($sql); // get rid of the fat
+
if (!empty($add_users)) {
print "User entries to add: ". count($add_users). "\n";
- if ($roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
+ $sitecontext = get_context_instance(CONTEXT_SYSTEM);
+ if (!empty($this->config->creators) and !empty($this->config->memberattribute)
+ and $roles = get_roles_with_capability('moodle/legacy:coursecreator', CAP_ALLOW)) {
$creatorrole = array_shift($roles); // We can only use one, let's use the first one
+ } else {
+ $creatorrole = false;
}
begin_sql();
foreach ($add_users as $user) {
- $user = $this->get_userinfo_asobj($user->idnumber);
- //print $user->username . "\n";
-
+ $user = $this->get_userinfo_asobj(addslashes($user->username));
+
// prep a few params
$user->modified = time();
$user->confirmed = 1;
- $user->auth = AUTH_LDAP_NAME;
+ $user->auth = 'ldap';
$user->mnethostid = $CFG->mnet_localhost_id;
-
- // insert it
- $old_debug=$CFG->debug;
- $CFG->debug=10;
-
- // maybe the user has been deleted before
- if ($old_user = get_record('user', 'idnumber', $user->idnumber, 'deleted', 1, 'mnethostid', $CFG->mnet_localhost_id)) {
- $user->id = $old_user->id;
- set_field('user', 'deleted', 0, 'id', $user->id);
- echo "Revived user $user->username with idnumber $user->idnumber id $user->id\n";
- }
- elseif ($id = insert_record('user',$user)) { // it is truly a new user
- echo "inserted user $user->username with idnumber $user->idnumber id $id\n";
- $user->id = $id;
- }
- else {
- echo "error inserting user $user->username with idnumber $user->idnumber \n";
+ if (empty($user->lang)) {
+ $user->lang = $CFG->lang;
}
- $CFG->debug = $old_debug;
- $userobj = $this->update_user_record($user->username);
- if (isset($this->config->forcechangepassword) and $this->config->forcechangepassword) {
- set_user_preference('auth_forcepasswordchange', 1, $userobj->id);
- }
-
- // update course creators
- if (isset($creatorrole->id) and !empty($this->config->creators) and !empty($this->config->memberattribute)) {
- if ($this->iscreator($user->username)) {
- if (user_has_role_assignment($user->id, $creatorrole->id, $sitecontext->id)) {
- role_unassign($creatorrole->id, $user->id, 0, $sitecontext->id);
- } else {
- role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
- }
+
+ $user = addslashes_recursive($user);
+
+ if ($id = insert_record('user',$user)) {
+ echo "\t"; print_string('auth_dbinsertuser', 'auth', array(stripslashes($user->username), $id)); echo "\n";
+ $userobj = $this->update_user_record($user->username);
+ if (!empty($this->config->forcechangepassword)) {
+ set_user_preference('auth_forcepasswordchange', 1, $userobj->id);
}
+ } else {
+ echo "\t"; print_string('auth_dbinsertusererror', 'auth', $user->username); echo "\n";
+ }
+
+ // add course creators if needed
+ if ($creatorrole !== false and $this->iscreator(stripslashes($user->username))) {
+ role_assign($creatorrole->id, $user->id, 0, $sitecontext->id, 0, 0, 0, 'ldap');
}
}
commit_sql();
return true;
}
- /**
- * Update a local user record from an external source.
- * This is a lighter version of the one in moodlelib -- won't do
+ /**
+ * Update a local user record from an external source.
+ * This is a lighter version of the one in moodlelib -- won't do
* expensive ops such as enrolment.
*
- * If you don't pass $updatekeys, there is a performance hit and
- * values removed from LDAP won't be removed from moodle.
+ * If you don't pass $updatekeys, there is a performance hit and
+ * values removed from LDAP won't be removed from moodle.
+ *
+ * @param string $username username (with system magic quotes)
*/
function update_user_record($username, $updatekeys = false) {
-
global $CFG;
//just in case check text case
$username = trim(moodle_strtolower($username));
-
+
// get the current user record
$user = get_record('user', 'username', $username, 'mnethostid', $CFG->mnet_localhost_id);
if (empty($user)) { // trouble
- error_log("Cannot update non-existent user: $username");
+ error_log("Cannot update non-existent user: ".stripslashes($username));
+ print_error('auth_dbusernotexist','auth',$username);
die;
}
// Protect the userid from being overwritten
$userid = $user->id;
- if (function_exists('auth_get_userinfo')) {
- if ($newinfo = auth_get_userinfo($username)) {
- $newinfo = truncate_userinfo($newinfo);
-
- if (empty($updatekeys)) { // all keys? this does not support removing values
- $updatekeys = array_keys($newinfo);
+ if ($newinfo = $this->get_userinfo($username)) {
+ $newinfo = truncate_userinfo($newinfo);
+
+ if (empty($updatekeys)) { // all keys? this does not support removing values
+ $updatekeys = array_keys($newinfo);
+ }
+
+ foreach ($updatekeys as $key) {
+ if (isset($newinfo[$key])) {
+ $value = $newinfo[$key];
+ } else {
+ $value = '';
}
-
- foreach ($updatekeys as $key) {
- if (isset($newinfo[$key])) {
- $value = addslashes(stripslashes($newinfo[$key]));
- }
- else {
- $value = '';
- }
- if (!empty($this->config->{'field_updatelocal_' . $key})) {
- if ($user->{$key} != $value) { // only update if it's changed
- set_field('user', $key, $value, 'id', $userid);
- }
+
+ if (!empty($this->config->{'field_updatelocal_' . $key})) {
+ if ($user->{$key} != $value) { // only update if it's changed
+ set_field('user', $key, addslashes($value), 'id', $userid);
}
}
}
+ } else {
+ return false;
}
- return get_record_select("user", "id = '$userid' AND deleted <> '1'");
+ return get_record_select('user', "id = $userid AND deleted = 0");
}
-
- // bulk insert in SQL's temp table
- // $users is an array of usernames
+ /**
+ * Bulk insert in SQL's temp table
+ * @param array $users is an array of usernames
+ */
function ldap_bulk_insert($users, $temptable) {
// bulk insert -- superfast with $bulk_insert_records
- $sql = 'INSERT INTO ' . $temptable . ' (idnumber) VALUES ';
+ $sql = 'INSERT INTO ' . $temptable . ' (username) VALUES ';
// make those values safe
- array_map('addslashes', $users);
+ $users = addslashes_recursive($users);
// join and quote the whole lot
- $sql = $sql . '(\'' . join('\'),(\'', $users) . '\')';
- print "+ " . count($users) . " users\n";
- execute_sql($sql, false);
-
+ $sql = $sql . "('" . implode("'),('", $users) . "')";
+ print "\t+ " . count($users) . " users\n";
+ execute_sql($sql, false);
}
- /*
- * user_activate activates user in external db.
- *
+ /**
* Activates (enables) user in external db so user can login to external db
*
- * @param mixed $username username
+ * @param mixed $username username (with system magic quotes)
* @return boolen result
*/
function user_activate($username) {
-
- global $CFG;
-
+ $textlib = textlib_get_instance();
+ $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
+
$ldapconnection = $this->ldap_connect();
- $userdn = $this->ldap_find_userdn($ldapconnection, $username);
+ $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
switch ($this->config->user_type) {
case 'edir':
$newinfo['loginDisabled']="FALSE";
break;
default:
- error ('auth: ldap user_activate() does not support selected usertype:"'.$this->config->user_type.'" (..yet)');
- }
+ error ('auth: ldap user_activate() does not support selected usertype:"'.$this->config->user_type.'" (..yet)');
+ }
$result = ldap_modify($ldapconnection, $userdn, $newinfo);
ldap_close($ldapconnection);
return $result;
}
- /*
- * user_disables disables user in external db.
- *
+ /**
* Disables user in external db so user can't login to external db
*
* @param mixed $username username
* @return boolean result
*/
- function user_disable($username) {
- global $CFG;
+/* function user_disable($username) {
+ $textlib = textlib_get_instance();
+ $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
$ldapconnection = $this->ldap_connect();
- $userdn = $this->ldap_find_userdn($ldapconnection, $username);
+ $userdn = $this->ldap_find_userdn($ldapconnection, $extusername);
switch ($this->config->user_type) {
case 'edir':
$newinfo['loginDisabled']="TRUE";
break;
default:
- error ('auth: ldap user_disable() does not support selected usertype (..yet)');
- }
+ error ('auth: ldap user_disable() does not support selected usertype (..yet)');
+ }
$result = ldap_modify($ldapconnection, $userdn, $newinfo);
ldap_close($ldapconnection);
return $result;
- }
+ }*/
- /*
+ /**
* Returns true if user should be coursecreator.
*
- * @param mixed $username username
+ * @param mixed $username username (with system magic quotes)
* @return boolean result
*/
function iscreator($username = false) {
- ///if user is member of creator group return true
- global $USER, $CFG;
- $this->ldap_init();
- if (! $username) {
- $username = $USER->username;
+ global $USER;
+
+ if (empty($this->config->creators) or empty($this->config->memberattribute)) {
+ return false;
}
- if ((! $this->config->creators) or (! $this->config->memberattribute)) {
- return null;
+
+ if ($username === false) {
+ $username = $USER->username;
+ } else {
+ $username = stripslashes($username);
}
- return $this->ldap_isgroupmember($username, $this->config->creators);
+
+ $textlib = textlib_get_instance();
+ $extusername = $textlib->convert($username, 'utf-8', $this->config->ldapencoding);
+
+ return $this->ldap_isgroupmember($extusername, $this->config->creators);
}
- /*
- * user_update saves userinformation from moodle to external db
- *
+ /**
* Called when the user record is updated.
- * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
+ * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
* conpares information saved modified information to external db.
*
- * @param mixed $olduser Userobject before modifications
- * @param mixed $newuser Userobject new modified userobject
+ * @param mixed $olduser Userobject before modifications (without system magic quotes)
+ * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
* @return boolean result
*
*/
function user_update($olduser, $newuser) {
- global $USER, $CFG;
+ global $USER;
+
+ if (isset($olduser->username) and isset($newuser->username) and $olduser->username != $newuser->username) {
+ error_log("ERROR:User renaming not allowed in LDAP");
+ return false;
+ }
+
+ if (isset($olduser->auth) and $olduser->auth == 'ldap') {
+ return true; // just change auth and skip update
+ }
+
+ $textlib = textlib_get_instance();
+ $extoldusername = $textlib->convert($olduser->username, 'utf-8', $this->config->ldapencoding);
$ldapconnection = $this->ldap_connect();
-
- $result = array();
+
$search_attribs = array();
- $attrmap = $this->ldap_attributes();
+ $attrmap = $this->ldap_attributes();
foreach ($attrmap as $key => $values) {
if (!is_array($values)) {
$values = array($values);
if (!in_array($value, $search_attribs)) {
array_push($search_attribs, $value);
}
- }
+ }
}
- $user_dn = $this->ldap_find_userdn($ldapconnection, $olduser->username);
+ $user_dn = $this->ldap_find_userdn($ldapconnection, $extoldusername);
$user_info_result = ldap_read($ldapconnection, $user_dn,
$this->config->objectclass, $search_attribs);
if ($user_info_result) {
$user_entry = $this->ldap_get_entries($ldapconnection, $user_info_result);
- if (count($user_entry) > 1) {
+ if (empty($user_entry)) {
+ return false; // old user not found!
+ } else if (count($user_entry) > 1) {
trigger_error("ldap: Strange! More than one user record found in ldap. Only using the first one.");
+ return false;
}
$user_entry = $user_entry[0];
//error_log(var_export($user_entry) . 'fpp' );
-
- foreach ($attrmap as $key => $ldapkeys) {
+ foreach ($attrmap as $key => $ldapkeys) {
// only process if the moodle field ($key) has changed and we
// are set to update LDAP with it
- if ($olduser->$key !== $newuser->$key and
- !empty($this->config->{'field_updateremote_'. $key})) {
-
- // for ldap values that could be in more than one
- // ldap key, we will do our best to match
+ if (isset($olduser->$key) and isset($newuser->$key)
+ and $olduser->$key !== $newuser->$key
+ and !empty($this->config->{'field_updateremote_'. $key})) {
+ // for ldap values that could be in more than one
+ // ldap key, we will do our best to match
// where they came from
$ambiguous = true;
$changed = false;
if (count($ldapkeys) < 2) {
$ambiguous = false;
}
-
+
+ $nuvalue = $textlib->convert($newuser->$key, 'utf-8', $this->config->ldapencoding);
+ $ouvalue = $textlib->convert($olduser->$key, 'utf-8', $this->config->ldapencoding);
+
foreach ($ldapkeys as $ldapkey) {
- $ldapkey = strtolower($ldapkey);
+ $ldapkey = $ldapkey;
$ldapvalue = $user_entry[$ldapkey][0];
if (!$ambiguous) {
// skip update if the values already match
- if ( !($newuser->$key === $ldapvalue) ) {
- ldap_modify($ldapconnection, $user_dn, array($ldapkey => $newuser->$key));
- }
- else {
- error_log("Skip updating field $key for entry $user_dn: it seems to be already same on LDAP.
- old moodle value: '{$olduser->$key}'
- new value: '{$newuser->$key}'
- current value in ldap entry: '{$ldapvalue}'");
+ if ($nuvalue !== $ldapvalue) {
+ //this might fail due to schema validation
+ if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
+ continue;
+ } else {
+ error_log('Error updating LDAP record. Error code: '
+ . ldap_errno($ldapconnection) . '; Error string : '
+ . ldap_err2str(ldap_errno($ldapconnection))
+ . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
+ continue;
+ }
}
- }
- else {
+ } else {
// ambiguous
// value empty before in Moodle (and LDAP) - use 1st ldap candidate field
// no need to guess
- if (empty($olduser->$key)) { // value empty before - use 1st ldap candidate
- if (ldap_modify($ldapconnection, $user_dn, array($ldapkey => $newuser->$key))) {
+ if ($ouvalue === '') { // value empty before - use 1st ldap candidate
+ //this might fail due to schema validation
+ if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
$changed = true;
- last;
- }
- else {
- error ('Error updating LDAP record. Error code: '
- . ldap_errno($ldapconnection) . '; Error string : '
- . ldap_err2str(ldap_errno($ldapconnection)));
+ continue;
+ } else {
+ error_log('Error updating LDAP record. Error code: '
+ . ldap_errno($ldapconnection) . '; Error string : '
+ . ldap_err2str(ldap_errno($ldapconnection))
+ . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
+ continue;
}
}
- // we found which ldap key to update!
- if (!empty($ldapvalue) and $olduser->$key === $ldapvalue ) {
- // error_log("Matched: ". $olduser->$key . " === " . $ldapvalue);
- if (ldap_modify($ldapconnection, $user_dn, array($ldapkey => $newuser->$key))) {
+ // we found which ldap key to update!
+ if ($ouvalue !== '' and $ouvalue === $ldapvalue ) {
+ //this might fail due to schema validation
+ if (@ldap_modify($ldapconnection, $user_dn, array($ldapkey => $nuvalue))) {
$changed = true;
- last;
- }
- else {
- error ('Error updating LDAP record. Error code: '
+ continue;
+ } else {
+ error_log('Error updating LDAP record. Error code: '
. ldap_errno($ldapconnection) . '; Error string : '
- . ldap_err2str(ldap_errno($ldapconnection)));
+ . ldap_err2str(ldap_errno($ldapconnection))
+ . "\nKey ($key) - old moodle value: '$ouvalue' new value: '$nuvalue'");
+ continue;
}
}
}
}
-
+
if ($ambiguous and !$changed) {
- error_log("Failed to update LDAP with ambiguous field $key".
- " old moodle value: '" . $olduser->$key .
- "' new value '" . $newuser->$key );
+ error_log("Failed to update LDAP with ambiguous field $key".
+ " old moodle value: '" . $ouvalue .
+ "' new value '" . $nuvalue );
}
}
}
-
-
- }
- else {
+ } else {
error_log("ERROR:No user found in LDAP");
@ldap_close($ldapconnection);
return false;
}
@ldap_close($ldapconnection);
-
+
return true;
}
* called when the user password is updated.
* changes userpassword in external db
*
- * @param object $user User table object
- * @param mixed $newpassword Plaintext password
+ * @param object $user User table object (with system magic quotes)
+ * @param string $newpassword Plaintext password (with system magic quotes)
* @return boolean result
*
*/
/// or that you've otherwise checked the user's credentials
/// IMPORTANT: $newpassword must be cleartext, not crypted/md5'ed
- global $CFG, $USER;
+ global $USER;
$result = false;
$username = $user->username;
-
+
+ $textlib = textlib_get_instance();
+ $extusername = $textlib->convert(stripslashes($username), 'utf-8', $this->config->ldapencoding);
+ $extpassword = $textlib->convert(stripslashes($newpassword), 'utf-8', $this->config->ldapencoding);
+
$ldapconnection = $this->ldap_connect();
- $user_dn = $this->ldap_find_userdn($ldapconnection, $username);
-
+ $user_dn = $this->ldap_find_userdn($ldapconnection, $extusername);
+
if (!$user_dn) {
- error_log('LDAP Error in user_update_password(). No DN for: ' . $username);
+ error_log('LDAP Error in user_update_password(). No DN for: ' . stripslashes($user->username));
return false;
}
switch ($this->config->user_type) {
case 'edir':
//Change password
- $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $newpassword));
+ $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
if (!$result) {
error_log('LDAP Error in user_update_password(). Error code: '
. ldap_errno($ldapconnection) . '; Error string : '
if (!empty($info[0][$this->config->expireattr][0])) {
//Set expiration time only if passwordExpirationInterval is defined
if (!empty($info[0]['passwordExpirationInterval'][0])) {
- $expirationtime = time() + $info[0]['passwordExpirationInterval'][0];
+ $expirationtime = time() + $info[0]['passwordExpirationInterval'][0];
$ldapexpirationtime = $this->ldap_unix2expirationtime($expirationtime);
$newattrs['passwordExpirationTime'] = $ldapexpirationtime;
- }
+ }
//set gracelogin count
if (!empty($info[0]['loginGraceLimit'][0])) {
- $newattrs['loginGraceRemaining']= $info[0]['loginGraceLimit'][0];
+ $newattrs['loginGraceRemaining']= $info[0]['loginGraceLimit'][0];
}
-
+
//Store attribute changes to ldap
$result = ldap_modify($ldapconnection, $user_dn, $newattrs);
if (!$result) {
error_log('LDAP Error in user_update_password() when reading password expiration time. Error code: '
. ldap_errno($ldapconnection) . '; Error string : '
. ldap_err2str(ldap_errno($ldapconnection)));
- }
+ }
break;
-
+
default:
$usedconnection = &$ldapconnection;
// send ldap the password in cleartext, it will md5 it itself
- $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $newpassword));
+ $result = ldap_modify($ldapconnection, $user_dn, array('userPassword' => $extpassword));
if (!$result) {
- error_log('LDAP Error in user_update_password(). Error code: '
+ error_log('LDAP Error in user_update_password(). Error code: '
. ldap_errno($ldapconnection) . '; Error string : '
. ldap_err2str(ldap_errno($ldapconnection)));
}
-
+
}
@ldap_close($ldapconnection);
*
* @return array of predefined usertypes
*/
-
function ldap_suppported_usertypes() {
- // returns array of supported usertypes (schemas)
- // If you like to add our own please name and describe it here
- // And then add case clauses in relevant places in functions
- // iauth_ldap_init, auth_user_create, auth_check_expire, auth_check_grace
+ $types = array();
$types['edir']='Novell Edirectory';
$types['rfc2307']='posixAccount (rfc2307)';
$types['rfc2307bis']='posixAccount (rfc2307bis)';
$types['samba']='sambaSamAccount (v.3.0.7)';
- $types['ad']='MS ActiveDirectory';
+ $types['ad']='MS ActiveDirectory';
+ $types['default']=get_string('default');
return $types;
- }
+ }
+
-
/**
- * initializes needed variables for ldap-module
+ * Initializes needed variables for ldap-module
*
* Uses names defined in ldap_supported_usertypes.
* $default is first defined as:
function ldap_getdefaults() {
$default['objectclass'] = array(
'edir' => 'User',
- 'rfc2703' => 'posixAccount',
- 'rfc2703bis' => 'posixAccount',
+ 'rfc2307' => 'posixAccount',
+ 'rfc2307bis' => 'posixAccount',
'samba' => 'sambaSamAccount',
'ad' => 'user',
'default' => '*'
'rfc2307' => 'member',
'rfc2307bis' => 'member',
'samba' => 'member',
- 'ad' => 'member',
+ 'ad' => 'member',
'default' => 'member'
);
$default['memberattribute_isdn'] = array(
'ad' => '', //No support yet
'default' => ''
);
- return $default;
+ return $default;
}
/**
* @return array
*/
function ldap_getbinaryfields () {
- global $CFG;
$binaryfields = array (
'edir' => array('guid'),
- 'rfc2703' => array(),
- 'rfc2703bis' => array(),
+ 'rfc2307' => array(),
+ 'rfc2307bis' => array(),
'samba' => array(),
'ad' => array(),
- 'default' => '*'
+ 'default' => array()
);
if (!empty($this->config->user_type)) {
- return $binaryfields[$this->config->user_type];
+ return $binaryfields[$this->config->user_type];
}
else {
return $binaryfields['default'];
- }
+ }
}
function ldap_isbinary ($field) {
- if (!isset($field)) {
- return null ;
- }
- return array_search($field, $this->ldap_getbinaryfields());
- }
-
- /**
- * set $CFG-values for ldap_module
- *
- * Get default configuration values with ldap_getdefaults()
- * and by using this information $CFG-> values are set
- * If $CFG->value is alredy set current value is honored.
- *
- *
- */
- function ldap_init () {
- global $CFG;
-
- $default = $this->ldap_getdefaults();
-
- // TODO: do we need set_config calls here?
-
- foreach ($default as $key => $value) {
- //set defaults if overriding fields not set
- if (empty($this->config->{$key})) {
- if (!empty($this->config->user_type) and !empty($default[$key][$this->config->user_type])) {
- $this->config->{$key} = $default[$key][$this->config->user_type];
- }
- else {
- //use default value if user_type not set
- if (!empty($default[$key]['default'])) {
- $this->config->{$key} = $default[$key]['default'];
- }
- else {
- unset($this->config->{$key});
- }
- }
- }
- }
- //hack prefix to objectclass
- if ('objectClass=' != substr($this->config->objectclass, 0, 12)) {
- $this->config->objectclass = 'objectClass='.$this->config->objectclass;
+ if (empty($field)) {
+ return false;
}
-
- //all chages go in $CFG , no need to return value
+ return array_search($field, $this->ldap_getbinaryfields());
}
/**
* take expirationtime and return it as unixseconds
- *
+ *
* takes expriration timestamp as readed from ldap
* returns it as unix seconds
- * depends on $config->user_type variable
+ * depends on $this->config->user_type variable
*
* @param mixed time Time stamp readed from ldap as it is.
* @return timestamp
*/
function ldap_expirationtime2unix ($time) {
-
- global $CFG;
$result = false;
switch ($this->config->user_type) {
case 'edir':
$hr=substr($time,8,2);
$min=substr($time,10,2);
$sec=substr($time,12,2);
- $result = mktime($hr,$min,$sec,$mo,$dt,$yr);
+ $result = mktime($hr,$min,$sec,$mo,$dt,$yr);
break;
case 'posix':
$result = $time * DAYSECS; //The shadowExpire contains the number of DAYS between 01/01/1970 and the actual expiration date
break;
- default:
+ default:
print_error('auth_ldap_usertypeundefined', 'auth');
}
return $result;
* @param integer unix time stamp
*/
function ldap_unix2expirationtime($time) {
- global $CFG;
$result = false;
switch ($this->config->user_type) {
case 'edir':
- $result=date('YmdHis', $time).'Z';
+ $result=date('YmdHis', $time).'Z';
break;
case 'posix':
$result = $time ; //Already in correct format
break;
- default:
+ default:
print_error('auth_ldap_usertypeundefined2', 'auth');
- }
+ }
return $result;
}
- /*
+ /**
* checks if user belong to specific group(s)
*
* Returns true if user belongs group in grupdns string.
* @param mixed $groupdns string of group dn separated by ;
*
*/
- function ldap_isgroupmember($username='', $groupdns='') {
+ function ldap_isgroupmember($extusername='', $groupdns='') {
// Takes username and groupdn(s) , separated by ;
// Returns true if user is member of any given groups
- global $CFG ;
$result = false;
$ldapconnection = $this->ldap_connect();
-
+
if (empty($username) or empty($groupdns)) {
return $result;
}
}
$groups = explode(";",$groupdns);
-
+
foreach ($groups as $group) {
$group = trim($group);
if (empty($group)) {
continue;
}
//echo "Checking group $group for member $username\n";
- $search = @ldap_read($ldapconnection, $group, '('.$this->config->memberattribute.'='.$username.')', array($this->config->memberattribute));
+ $search = @ldap_read($ldapconnection, $group, '('.$this->config->memberattribute.'='.$this->filter_addslashes($username).')', array($this->config->memberattribute));
if (!empty($search) and ldap_count_entries($ldapconnection, $search)) {$info = $this->ldap_get_entries($ldapconnection, $search);
-
+
if (count($info) > 0 ) {
// user is member of group
$result = true;
* @return connection result
*/
function ldap_connect($binddn='',$bindpwd='') {
- /// connects and binds to ldap-server
- /// Returns connection result
-
- global $CFG;
- $this->ldap_init();
-
//Select bind password, With empty values use
//ldap_bind_* variables or anonymous bind if ldap_bind_* are empty
if ($binddn == '' and $bindpwd == '') {
$bindpwd = $this->config->bind_pw;
}
}
-
+
$urls = explode(";",$this->config->host_url);
-
+
foreach ($urls as $server) {
$server = trim($server);
if (empty($server)) {
$connresult = ldap_connect($server);
//ldap_connect returns ALWAYS true
-
+
if (!empty($this->config->version)) {
ldap_set_option($connresult, LDAP_OPT_PROTOCOL_VERSION, $this->config->version);
}
if (!empty($binddn)) {
//bind with search-user
- //$debuginfo .= 'Using bind user'.$binddn.'and password:'.$bindpwd;
+ //$debuginfo .= 'Using bind user'.$binddn.'and password:'.$bindpwd;
$bindresult=ldap_bind($connresult, $binddn,$bindpwd);
}
else {
- //bind anonymously
+ //bind anonymously
$bindresult=@ldap_bind($connresult);
- }
-
+ }
+
if (!empty($this->config->opt_deref)) {
ldap_set_option($connresult, LDAP_OPT_DEREF, $this->config->opt_deref);
}
if ($bindresult) {
return $connresult;
}
-
+
$debuginfo .= "<br/>Server: '$server' <br/> Connection: '$connresult'<br/> Bind result: '$bindresult'</br>";
}
* like: cn=username,ou=suborg,o=org
*
* @param mixed $ldapconnection $ldapconnection result
- * @param mixed $username username
+ * @param mixed $username username (external encoding no slashes)
*
*/
- function ldap_find_userdn ($ldapconnection, $username) {
-
- global $CFG;
+ function ldap_find_userdn ($ldapconnection, $extusername) {
//default return value
$ldap_user_dn = FALSE;
//get all contexts and look for first matching user
$ldap_contexts = explode(";",$this->config->contexts);
-
+
if (!empty($this->config->create_context)) {
array_push($ldap_contexts, $this->config->create_context);
}
-
+
foreach ($ldap_contexts as $context) {
$context = trim($context);
if ($this->config->search_sub) {
//use ldap_search to find first user from subtree
- $ldap_result = ldap_search($ldapconnection, $context, "(".$this->config->user_attribute."=".$username.")",array($this->config->user_attribute));
+ $ldap_result = ldap_search($ldapconnection, $context, "(".$this->config->user_attribute."=".$this->filter_addslashes($extusername).")",array($this->config->user_attribute));
}
else {
//search only in this context
- $ldap_result = ldap_list($ldapconnection, $context, "(".$this->config->user_attribute."=".$username.")",array($this->config->user_attribute));
+ $ldap_result = ldap_list($ldapconnection, $context, "(".$this->config->user_attribute."=".$this->filter_addslashes($extusername).")",array($this->config->user_attribute));
}
-
+
$entry = ldap_first_entry($ldapconnection,$ldap_result);
if ($entry) {
*/
function ldap_attributes () {
- $fields = array("firstname", "lastname", "email", "phone1", "phone2",
- "department", "address", "city", "country", "description",
+ $fields = array("firstname", "lastname", "email", "phone1", "phone2",
+ "department", "address", "city", "country", "description",
"idnumber", "lang" );
$moodleattributes = array();
foreach ($fields as $field) {
function ldap_get_userlist($filter="*") {
/// returns all users from ldap servers
- global $CFG;
-
$fresult = array();
$ldapconnection = $this->ldap_connect();
}
$contexts = explode(";",$this->config->contexts);
-
+
if (!empty($this->config->create_context)) {
array_push($contexts, $this->config->create_context);
}
$filter,
array($this->config->user_attribute));
}
-
+
$users = $this->ldap_get_entries($ldapconnection, $ldap_result);
//add found users to list
array_push($fresult, ($users[$i][$this->config->user_attribute][0]) );
}
}
-
+
return $fresult;
}
*
* @return array ldap-entries
*/
-
+
function ldap_get_entries($conn, $searchresult) {
//Returns values like ldap_get_entries but is
//binary compatible
else {
$fresult[$i][$attributes[$j]] = array($values);
}
- }
- $i++;
+ }
+ $i++;
}
while ($entry = @ldap_next_entry($conn, $entry));
//were done
/**
* Returns true if this authentication plugin is 'internal'.
*
- * @returns bool
+ * @return bool
*/
function is_internal() {
return false;
* Returns true if this authentication plugin can change the user's
* password.
*
- * @returns bool
+ * @return bool
*/
function can_change_password() {
return true;
}
-
+
/**
* Returns the URL for changing the user's pw, or false if the default can
* be used.
*
- * @returns bool
+ * @return string url
*/
function change_password_url() {
- return $CFG->changepasswordurl; // TODO: will this be global?
+ if (empty($this->config->stdchangepassword)) {
+ return $this->config->changepasswordurl;
+ } else {
+ return false;
+ }
}
-
+
/**
* Prints a form for configuring this authentication plugin.
*
*
* @param array $page An object containing all the data for this page.
*/
- function config_form($config, $err) {
- include "config.html";
+ function config_form($config, $err, $user_fields) {
+ include 'config.html';
}
/**
*/
function process_config($config) {
// set to defaults if undefined
- if (!isset($config->host_url))
+ if (!isset($config->host_url))
{ $config->host_url = ''; }
- if (!isset($config->contexts))
+ if (empty($config->ldapencoding))
+ { $config->ldapencoding = 'utf-8'; }
+ if (!isset($config->contexts))
{ $config->contexts = ''; }
- if (!isset($config->user_type))
- { $config->user_type = ''; }
- if (!isset($config->user_attribute))
+ if (!isset($config->user_type))
+ { $config->user_type = 'default'; }
+ if (!isset($config->user_attribute))
{ $config->user_attribute = ''; }
- if (!isset($config->search_sub))
+ if (!isset($config->search_sub))
{ $config->search_sub = ''; }
- if (!isset($config->opt_deref))
+ if (!isset($config->opt_deref))
{ $config->opt_deref = ''; }
- if (!isset($config->preventpassindb))
- { $config->preventpassindb = 0; }
- if (!isset($config->bind_dn))
+ if (!isset($config->preventpassindb))
+ { $config->preventpassindb = 0; }
+ if (!isset($config->bind_dn))
{$config->bind_dn = ''; }
- if (!isset($config->bind_pw))
+ if (!isset($config->bind_pw))
{$config->bind_pw = ''; }
- if (!isset($config->version))
+ if (!isset($config->version))
{$config->version = '2'; }
- if (!isset($config->objectclass))
+ if (!isset($config->objectclass))
{$config->objectclass = ''; }
- if (!isset($config->memberattribute))
+ if (!isset($config->memberattribute))
{$config->memberattribute = ''; }
- if (!isset($config->creators))
+ if (!isset($config->creators))
{$config->creators = ''; }
- if (!isset($config->create_context))
+ if (!isset($config->create_context))
{$config->create_context = ''; }
- if (!isset($config->expiration))
+ if (!isset($config->expiration))
{$config->expiration = ''; }
- if (!isset($config->expiration_warning))
+ if (!isset($config->expiration_warning))
{$config->expiration_warning = '10'; }
- if (!isset($config->expireattr))
+ if (!isset($config->expireattr))
{$config->expireattr = ''; }
- if (!isset($config->gracelogins))
+ if (!isset($config->gracelogins))
{$config->gracelogins = ''; }
- if (!isset($config->graceattr))
+ if (!isset($config->graceattr))
{$config->graceattr = ''; }
- if (!isset($config->auth_user_create))
+ if (!isset($config->auth_user_create))
{$config->auth_user_create = ''; }
- if (!isset($config->forcechangepassword))
- {$config->forcechangepassword = false; }
+ if (!isset($config->forcechangepassword))
+ {$config->forcechangepassword = 0; }
if (!isset($config->stdchangepassword))
- {$config->stdchangepassword = false; }
+ {$config->stdchangepassword = 0; }
if (!isset($config->changepasswordurl))
{$config->changepasswordurl = ''; }
+ if (!isset($config->removeuser))
+ {$config->removeuser = 0; }
// save settings
set_config('host_url', $config->host_url, 'auth/ldap');
+ set_config('ldapencoding', $config->ldapencoding, 'auth/ldap');
+ set_config('host_url', $config->host_url, 'auth/ldap');
set_config('contexts', $config->contexts, 'auth/ldap');
set_config('user_type', $config->user_type, 'auth/ldap');
set_config('user_attribute', $config->user_attribute, 'auth/ldap');
set_config('forcechangepassword', $config->forcechangepassword, 'auth/ldap');
set_config('stdchangepassword', $config->stdchangepassword, 'auth/ldap');
set_config('changepasswordurl', $config->changepasswordurl, 'auth/ldap');
+ set_config('removeuser', $config->removeuser, 'auth/ldap');
return true;
}
+ /**
+ * Quote control characters in texts used in ldap filters - see rfc2254.txt
+ *
+ * @param string
+ */
+ function filter_addslashes($text) {
+ $text = str_replace('\\', '\\5c', $text);
+ $text = str_replace(array('*', '(', ')', "\0"),
+ array('\\2a', '\\28', '\\29', '\\00'), $text);
+ return $text;
+ }
+
+ /**
+ * Quote control characters in quoted "texts" used in ldap
+ *
+ * @param string
+ */
+ function ldap_addslashes($text) {
+ $text = str_replace('\\', '\\\\', $text);
+ $text = str_replace(array('"', "\0"),
+ array('\\"', '\\00'), $text);
+ return $text;
+ }
}
?>
<?php
/** auth_ldap_sync_users.php
- *
- * This script is meant to be called from a cronjob to sync moodle with the LDAP
+ *
+ * This script is meant to be called from a cronjob to sync moodle with the LDAP
* backend in those setups where the LDAP backend acts as 'master'.
- *
+ *
* Recommended cron entry:
* # 5 minutes past 4am
* 5 4 * * * /usr/bin/php -c /etc/php4/cli/php.ini /var/www/moodle/auth/ldap/auth_ldap_sync_users.php
- *
- * Notes:
+ *
+ * Notes:
* - If you have a large number of users, you may want to raise the memory limits
* by passing -d momory_limit=256M
* - For debugging & better logging, you are encouraged to use in the command line:
* -d log_errors=1 -d error_reporting=E_ALL -d display_errors=0 -d html_errors=0
- *
+ *
* Performance notes:
* We have optimized it as best as we could for Postgres and mySQL, with 27K students
- * we have seen this take 10 minutes.
- *
+ * we have seen this take 10 minutes.
+ *
*/
-if (!empty($_SERVER['GATEWAY_INTERFACE'])) {
- error_log("should not be called from apache!");
+if (isset($_SERVER['REMOTE_ADDR'])) {
+ error_log("should not be called from web server!");
exit;
}
+$nomoodlecookie = true; // cookie not needed
+
require_once(dirname(dirname(dirname(__FILE__))).'/config.php'); // global moodle config file.
+require_once($CFG->libdir.'/blocklib.php');
require_once($CFG->dirroot.'/course/lib.php');
-require_once($CFG->dirroot.'/lib/blocklib.php');
require_once($CFG->dirroot.'/mod/resource/lib.php');
require_once($CFG->dirroot.'/mod/forum/lib.php');
-$CFG->debug=10;
-require_once($CFG->dirroot.'/lib/moodlelib.php');
+if (!is_enabled_auth('ldap')) {
+ echo "Plugin not enabled!";
+ die;
+}
+
$ldapauth = get_auth_plugin('ldap');
$ldapauth->sync_users(1000, true);
<?php
- $createoptions[0] = get_string("no");
- $createoptions[1] = get_string("yes");
-
// set to defaults if undefined
- if (!isset($config->host_url))
+ if (!isset($config->host_url))
{ $config->host_url = ''; }
- if (!isset($config->contexts))
+ if (empty($config->ldapencoding))
+ { $config->ldapencoding = 'utf-8'; }
+ if (!isset($config->contexts))
{ $config->contexts = ''; }
- if (!isset($config->user_type))
- { $config->user_type = ''; }
- if (!isset($config->user_attribute))
+ if (!isset($config->user_type))
+ { $config->user_type = 'default'; }
+ if (!isset($config->user_attribute))
{ $config->user_attribute = ''; }
- if (!isset($config->search_sub))
+ if (!isset($config->search_sub))
{ $config->search_sub = ''; }
- if (!isset($config->opt_deref))
- { $config->opt_deref = ''; }
- if (!isset($config->preventpassindb))
- { $config->preventpassindb = 0; }
- if (!isset($config->bind_dn))
+ if (!isset($config->opt_deref))
+ { $config->opt_deref = LDAP_DEREF_NEVER; }
+ if (!isset($config->preventpassindb))
+ { $config->preventpassindb = 0; }
+ if (!isset($config->bind_dn))
{$config->bind_dn = ''; }
- if (!isset($config->bind_pw))
+ if (!isset($config->bind_pw))
{$config->bind_pw = ''; }
- if (!isset($config->version))
+ if (!isset($config->version))
{$config->version = '2'; }
- if (!isset($config->objectclass))
+ if (!isset($config->objectclass))
{$config->objectclass = ''; }
- if (!isset($config->memberattribute))
+ if (!isset($config->memberattribute))
{$config->memberattribute = ''; }
- if (!isset($config->creators))
+ if (!isset($config->creators))
{$config->creators = ''; }
- if (!isset($config->create_context))
+ if (!isset($config->create_context))
{$config->create_context = ''; }
- if (!isset($config->expiration))
+ if (!isset($config->expiration))
{$config->expiration = ''; }
- if (!isset($config->expiration_warning))
+ if (!isset($config->expiration_warning))
{$config->expiration_warning = '10'; }
- if (!isset($config->expireattr))
+ if (!isset($config->expireattr))
{$config->expireattr = ''; }
- if (!isset($config->gracelogins))
+ if (!isset($config->gracelogins))
{$config->gracelogins = ''; }
- if (!isset($config->graceattr))
+ if (!isset($config->graceattr))
{$config->graceattr = ''; }
- if (!isset($config->auth_user_create))
+ if (!isset($config->auth_user_create))
{$config->auth_user_create = ''; }
- if (!isset($config->forcechangepassword))
- {$config->forcechangepassword = false; }
+ if (!isset($config->forcechangepassword))
+ {$config->forcechangepassword = 0; }
if (!isset($config->stdchangepassword))
- {$config->stdchangepassword = false; }
+ {$config->stdchangepassword = 0; }
if (!isset($config->changepasswordurl))
{$config->changepasswordurl = ''; }
+ if (!isset($config->removeuser))
+ {$config->removeuser = 0; }
$yesno = array( get_string('no'), get_string('yes') );
-
+
if (!function_exists('ldap_connect')) { // Is php4-ldap really there?
notify(get_string('auth_ldap_noextension','auth'));
}
-
+
?>
<table cellspacing="0" cellpadding="5" border="0" align="center">
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_host_url_key','auth') ?>:</td>
+ <td align="right"><label for="host_url"><?php print_string('auth_ldap_host_url_key','auth') ?></label></td>
<td>
- <input name="host_url" type="text" size="30" value="<?php echo $config->host_url?>" />
+ <input name="host_url" id="host_url" type="text" size="30" value="<?php echo $config->host_url?>" />
<?php if (isset($err['host_url'])) formerr($err['host_url']); ?>
</td>
<td>
- <?php print_string('auth_ldap_host_url','auth') ?>
+ <?php print_string('auth_ldap_host_url','auth') ?>
</td>
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_version_key','auth') ?>:</td>
+ <td align="right"><label for="menuversion"><?php print_string('auth_ldap_version_key','auth') ?></label></td>
<td>
<?php
+ $varsions = array();
$versions[2] = '2';
$versions[3] = '3';
choose_from_menu($versions, 'version', $config->version, '');
- if (isset($err['version'])) formerr($err['version']);
+ if (isset($err['version'])) formerr($err['version']);
?>
</td>
<td>
- <?php print_string('auth_ldap_version','auth') ?>
+ <?php print_string('auth_ldap_version','auth') ?>
+ </td>
+</tr>
+
+<tr valign="top" class="required">
+ <td align="right"><label for="ldapencoding"><?php print_string("auth_ldap_ldap_encoding_key", "auth") ?></label></td>
+ <td>
+ <input id="ldapencoding" name="ldapencoding" type="text" value="<?php echo $config->ldapencoding ?>" />
+ <?php
+
+ if (isset($err['ldapencoding'])) {
+ formerr($err['ldapencoding']);
+ }
+
+ ?>
</td>
+ <td><?php print_string('auth_ldap_ldap_encoding', 'auth') ?></td>
</tr>
<tr>
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_preventpassindb_key','auth') ?>:</td>
+ <td align="right"><label for="menupreventpassindb"><?php print_string('auth_ldap_preventpassindb_key','auth') ?></label></td>
<td>
- <?php
- $choices = array();
- $choices['0'] = get_string('no');
- $choices['1'] = get_string('yes');
- choose_from_menu ($choices, 'preventpassindb', $config->preventpassindb, '');
- ?>
+ <?php choose_from_menu($yesno, 'preventpassindb', $config->preventpassindb, ''); ?>
</td><td>
- <?php print_string('auth_ldap_preventpassindb','auth') ?>
+ <?php print_string('auth_ldap_preventpassindb','auth') ?>
</td>
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_bind_dn_key','auth') ?>:</td>
+ <td align="right"><label for="bind_dn"><?php print_string('auth_ldap_bind_dn_key','auth') ?></label></td>
<td>
- <input name="bind_dn" type="text" size="30" value="<?php echo $config->bind_dn?>" />
+ <input name="bind_dn" id="bind_dn" type="text" size="30" value="<?php echo $config->bind_dn?>" />
<?php if (isset($err['bind_dn'])) formerr($err['bind_dn']); ?>
</td><td>
- <?php print_string('auth_ldap_bind_dn','auth') ?>
+ <?php print_string('auth_ldap_bind_dn','auth') ?>
</td>
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_bind_pw_key','auth') ?>:</td>
+ <td align="right"><label for="bind_pw"><?php print_string('auth_ldap_bind_pw_key','auth') ?></label></td>
<td>
- <input name="bind_pw" type="password" size="30" value="<?php echo $config->bind_pw?>" />
+ <input name="bind_pw" id="bind_pw" type="password" size="30" value="<?php echo $config->bind_pw?>" />
<?php if (isset($err['bind_pw'])) formerr($err['bind_pw']); ?>
</td><td>
- <?php print_string('auth_ldap_bind_pw','auth') ?>
+ <?php print_string('auth_ldap_bind_pw','auth') ?>
</td>
</tr>
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_user_type_key','auth') ?>:</td>
+ <td align="right"><label for="menuuser_type"><?php print_string('auth_ldap_user_type_key','auth') ?></label></td>
<td>
<?php choose_from_menu($this->ldap_suppported_usertypes(), 'user_type', $config->user_type, ''); ?>
<?php if (isset($err['user_type'])) formerr($err['user_type']); ?>
</td>
<td>
- <?php print_string('auth_ldap_user_type', 'auth') ?>
+ <?php print_string('auth_ldap_user_type', 'auth') ?>
</td>
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_contexts_key','auth') ?>:</td>
+ <td align="right"><label for="contexts"><?php print_string('auth_ldap_contexts_key','auth') ?></label></td>
<td>
- <input name="contexts" type="text" size="30" value="<?php echo $config->contexts?>" />
+ <input name="contexts" id="contexts" type="text" size="30" value="<?php echo $config->contexts?>" />
<?php if (isset($err['contexts'])) formerr($err['contexts']); ?>
</td>
<td>
- <?php print_string('auth_ldap_contexts', 'auth') ?>
+ <?php print_string('auth_ldap_contexts', 'auth') ?>
</td>
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_search_sub_key','auth') ?>:</td>
+ <td align="right"><label for="menusearch_sub"><?php print_string('auth_ldap_search_sub_key','auth') ?></label></td>
<td>
-<?php
- $choices = array();
- $choices['0'] = get_string('no');
- $choices['1'] = get_string('yes');
- choose_from_menu ($choices, 'search_sub', $config->search_sub, '');
-?>
- <?php if (isset($err['search_sub'])) formerr($err['search_sub']); ?>
+ <?php choose_from_menu($yesno, 'search_sub', $config->search_sub, ''); ?>
</td>
<td>
- <?php print_string('auth_ldap_search_sub','auth') ?>
+ <?php print_string('auth_ldap_search_sub','auth') ?>
</td>
</tr>
+
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_opt_deref_key','auth') ?>:</td>
+ <td align="right"><label for="menuopt_deref"><?php print_string('auth_ldap_opt_deref_key','auth') ?></label></td>
<td>
<?php
+ $opt_deref = array();
$opt_deref[LDAP_DEREF_NEVER] = get_string('no');
$opt_deref[LDAP_DEREF_ALWAYS] = get_string('yes');
- choose_from_menu($opt_deref, 'opt_deref', $config->opt_deref, LDAP_DEREF_NEVER);
- if (isset($err['opt_deref'])) formerr($err['opt_deref']);
+ choose_from_menu($opt_deref, 'opt_deref', $config->opt_deref, LDAP_DEREF_NEVER, '');
+ if (isset($err['opt_deref'])) formerr($err['opt_deref']);
?>
</td>
<td>
- <?php print_string('auth_ldap_opt_deref','auth') ?>
+ <?php print_string('auth_ldap_opt_deref','auth') ?>
</td>
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_user_attribute_key','auth') ?>:</td>
+ <td align="right"><label for="user_attribute"><?php print_string('auth_ldap_user_attribute_key','auth') ?></label></td>
<td>
- <input name="user_attribute" type="text" size="30" value="<?php echo $config->user_attribute?>" />
+ <input name="user_attribute" id="user_attribute" type="text" size="30" value="<?php echo $config->user_attribute?>" />
<?php if (isset($err['user_attribute'])) formerr($err['user_attribute']); ?>
</td>
<td>
- <?php print_string('auth_ldap_user_attribute','auth') ?>
+ <?php print_string('auth_ldap_user_attribute','auth') ?>
</td>
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_memberattribute_key','auth') ?>:</td>
+ <td align="right"><label for="memberattribute"><?php print_string('auth_ldap_memberattribute_key','auth') ?></label></td>
<td>
- <input name="memberattribute" type="text" size="30" value="<?php echo $config->memberattribute?>" />
+ <input name="memberattribute" id="memberattribute" type="text" size="30" value="<?php echo $config->memberattribute?>" />
<?php if (isset($err['memberattribute'])) formerr($err['memberattribute']); ?>
</td><td>
- <?php print_string('auth_ldap_memberattribute','auth') ?>
+ <?php print_string('auth_ldap_memberattribute','auth') ?>
</td>
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_objectclass_key','auth') ?>:</td>
+ <td align="right"><label for="objectclass"><?php print_string('auth_ldap_objectclass_key','auth') ?></label></td>
<td>
- <input name="objectclass" type="text" size="30" value="<?php echo $config->objectclass?>" />
+ <input name="objectclass" id="objectclass" type="text" size="30" value="<?php echo $config->objectclass?>" />
<?php if (isset($err['objectclass'])) formerr($err['objectclass']); ?>
</td>
<td>
- <?php print_string('auth_ldap_objectclass','auth') ?>
+ <?php print_string('auth_ldap_objectclass','auth') ?>
</td>
</tr>
</tr>
<tr valign="top" class="required">
- <td align="right" valign="top"><?php print_string('forcechangepassword', 'auth') ?>:</td>
+ <td align="right" valign="top"><label for="menuforcechangepassword"><?php print_string('forcechangepassword', 'auth') ?></label></td>
<td>
-
- <select name="forcechangepassword">
- <option value="0" <?php echo ($config->forcechangepassword ? '' : 'selected="yes"') ?> >
- <?php print_string('no') ?></option>
- <option value="1" <?php echo ($config->forcechangepassword ? 'selected="yes"' : '') ?> >
- <?php print_string('yes') ?></option>
- </select><br />
-
+ <?php choose_from_menu($yesno, 'forcechangepassword', $config->forcechangepassword, ''); ?>
</td>
<td align="left" valign="top">
- <p><?php print_string('forcechangepasswordfirst_help', 'auth') ?></p>
+ <p><?php print_string('forcechangepasswordfirst_help', 'auth') ?></p>
</td>
</tr>
<tr valign="top" class="required">
- <td align="right" valign="top"><?php print_string('stdchangepassword', 'auth') ?>:</td>
+ <td align="right" valign="top"><label for="menustdchangepassword"><?php print_string('stdchangepassword', 'auth') ?></label></td>
<td>
-
- <select name="stdchangepassword">
- <option value='0' <?php echo ($config->stdchangepassword ? '' : 'selected="yes"') ?> >
- <?php print_string('no') ?></option>
- <option value='1' <?php echo ($config->stdchangepassword ? 'selected="yes"' : '') ?> >
- <?php print_string('yes') ?></option>
- </select><br />
-
+ <?php choose_from_menu($yesno, 'stdchangepassword', $config->stdchangepassword, ''); ?>
</td>
<td align="left" valign="top">
- <p><?php print_string('stdchangepassword_expl', 'auth') ?></p>
- <p><?php print_string('stdchangepassword_explldap', 'auth') ?></p>
+ <p><?php print_string('stdchangepassword_expl', 'auth') ?></p>
+ <p><?php print_string('stdchangepassword_explldap', 'auth') ?></p>
</td>
</tr>
<tr valign="top">
- <td align="right"><?php print_string('auth_ldap_changepasswordurl_key','auth') ?>: </td>
+ <td align="right"><label for="changepasswordurl"><?php print_string('auth_ldap_changepasswordurl_key','auth') ?></label></td>
<td>
- <input name="changepasswordurl" type="text" value="<?php echo $config->changepasswordurl ?>" />
+ <input name="changepasswordurl" id="changepasswordurl" type="text" value="<?php echo $config->changepasswordurl ?>" />
<?php
if (isset($err['changepasswordurl'])) {
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_expiration_key','auth') ?>:</td>
+ <td align="right"><label for="menuexpiration"><?php print_string('auth_ldap_expiration_key','auth') ?></label></td>
<td>
<?php
+ $expiration = array();
$expiration['0'] = 'no';
$expiration['1'] = 'LDAP';
choose_from_menu($expiration, 'expiration', $config->expiration, '');
- if (isset($err['expiration'])) formerr($err['expiration']);
+ if (isset($err['expiration'])) formerr($err['expiration']);
?>
</td>
<td>
- <?php print_string('auth_ldap_expiration_desc','auth') ?>
+ <?php print_string('auth_ldap_expiration_desc','auth') ?>
</td>
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_expiration_warning_key','auth') ?>:</td>
+ <td align="right"><label for="expiration_warning"><?php print_string('auth_ldap_expiration_warning_key','auth') ?></label></td>
<td>
- <input name="expiration_warning" type="text" size="2" value="<?php echo $config->expiration_warning?>" />
- <?php if (isset($err['expiration_warning'])) formerr($err['expiration_warning']);
+ <input name="expiration_warning" id="expiration_warning" type="text" size="2" value="<?php echo $config->expiration_warning?>" />
+ <?php if (isset($err['expiration_warning'])) formerr($err['expiration_warning']);
?>
</td>
<td>
- <?php print_string('auth_ldap_expiration_warning_desc','auth') ?>
+ <?php print_string('auth_ldap_expiration_warning_desc','auth') ?>
</td>
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_expireattr_key','auth') ?>:</td>
+ <td align="right"><label for="expireattr"><?php print_string('auth_ldap_expireattr_key','auth') ?></label></td>
<td>
- <input name="expireattr" type="text" size="30" value="<?php echo $config->expireattr?>" />
- <?php if (isset($err['expireattr'])) formerr($err['expireattr']);
+ <input name="expireattr" id="expireattr" type="text" size="30" value="<?php echo $config->expireattr?>" />
+ <?php if (isset($err['expireattr'])) formerr($err['expireattr']);
?>
</td>
<td>
- <?php print_string('auth_ldap_expireattr_desc','auth') ?>
+ <?php print_string('auth_ldap_expireattr_desc','auth') ?>
</td>
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_gracelogins_key','auth') ?>:</td>
+ <td align="right"><label for="menugracelogins"><?php print_string('auth_ldap_gracelogins_key','auth') ?></label></td>
<td>
- <?php
- $grace['0'] = get_string('no');
- $grace['1'] = get_string('yes');
- choose_from_menu($grace, 'gracelogins', $config->gracelogins, '');
- if (isset($err['expiration'])) formerr($err['expiration']);
- ?>
+ <?php choose_from_menu($yesno, 'gracelogins', $config->gracelogins, ''); ?>
</td>
<td>
- <?php print_string('auth_ldap_gracelogins_desc','auth') ?>
+ <?php print_string('auth_ldap_gracelogins_desc','auth') ?>
</td>
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_gracelogin_key','auth') ?>:</td>
+ <td align="right"><label for="graceattr"><?php print_string('auth_ldap_gracelogin_key','auth') ?></label></td>
<td>
- <input name="graceattr" type="text" size="30" value="<?php echo $config->graceattr?>" />
- <?php if (isset($err['graceattr'])) formerr($err['graceattr']);
+ <input name="graceattr" id="graceattr" type="text" size="30" value="<?php echo $config->graceattr?>" />
+ <?php if (isset($err['graceattr'])) formerr($err['graceattr']);
?>
</td>
<td>
- <?php print_string('auth_ldap_graceattr_desc','auth') ?>
+ <?php print_string('auth_ldap_graceattr_desc','auth') ?>
</td>
</tr>
</tr>
<tr valign="top">
- <td align="right"><?php print_string('auth_ldap_auth_user_create_key','auth') ?>: </td>
+ <td align="right"><label for="menuauth_user_create"><?php print_string('auth_ldap_auth_user_create_key','auth') ?></label></td>
<td>
- <?php
-
- choose_from_menu($createoptions, 'auth_user_create', $config->auth_user_create, '');
- if (isset($err['auth_user_create'])) {
- formerr($err['auth_user_create']);
- }
-
- ?>
+ <?php choose_from_menu($yesno, 'auth_user_create', $config->auth_user_create, ''); ?>
</td>
<td>
<?php print_string("auth_user_creation","auth"); ?>
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_create_context_key','auth') ?>:</td>
+ <td align="right"><label for="create_context"><?php print_string('auth_ldap_create_context_key','auth') ?></label></td>
<td>
- <input name="create_context" type="text" size="30" value="<?php echo $config->create_context?>" />
+ <input name="create_context" id="create_context" type="text" size="30" value="<?php echo $config->create_context?>" />
<?php if (isset($err['create_context'])) formerr($err['create_context']); ?>
</td><td>
- <?php print_string('auth_ldap_create_context','auth') ?>
+ <?php print_string('auth_ldap_create_context','auth') ?>
</td>
</tr>
</tr>
<tr valign="top" class="required">
- <td align="right"><?php print_string('auth_ldap_creators_key','auth') ?>:</td>
+ <td align="right"><label for="creators"><?php print_string('auth_ldap_creators_key','auth') ?></label></td>
<td>
- <input name="creators" type="text" size="30" value="<?php echo $config->creators?>" />
+ <input name="creators" id="creators" type="text" size="30" value="<?php echo $config->creators?>" />
<?php if (isset($err['creators'])) formerr($err['creators']); ?>
</td><td>
- <?php print_string('auth_ldap_creators','auth') ?>
+ <?php print_string('auth_ldap_creators','auth') ?>
</td>
</tr>
-<?php
+<tr>
+ <td colspan="2">
+ <h4><?php print_string('auth_sync_script', 'auth') ?> </h4>
+ </td>
+</tr>
+
+<tr valign="top">
+ <td align="right"><label for="menuremoveuser"><?php print_string('auth_remove_user_key','auth') ?></label></td>
+ <td>
+ <?php
+ $deleteopt = array();
+ $deleteopt['0'] = get_string('auth_remove_keep','auth');
+ $deleteopt['1'] = get_string('auth_remove_suspend','auth');
+ $deleteopt['2'] = get_string('auth_remove_delete','auth');
+ choose_from_menu($deleteopt, 'removeuser', $config->removeuser, '');
+ ?>
+ </td>
+ <td>
+ <?php print_string('auth_remove_user','auth') ?>
+ </td>
+</tr>
+
+<?php
$help = get_string('auth_ldapextrafields','auth');
$help .= get_string('auth_updatelocal_expl','auth');
$help .= '<hr />';
$help .= get_string('auth_updateremote_ldap','auth');
-global $user_fields;
-print_auth_lock_options('ldap', $user_fields, $help, true, true);
+print_auth_lock_options('ldap', $user_fields, $help, true, true);
?>
* 2006-08-28 File created.
*/
-// This page cannot be called directly
-if (!isset($CFG)) exit;
+if (!defined('MOODLE_INTERNAL')) {
+ die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
+}
/**
* Manual authentication plugin.
* Returns true if the username and password work and false if they are
* wrong or don't exist.
*
- * @param string $username The username
- * @param string $password The password
- * @returns bool Authentication success or failure.
+ * @param string $username The username (with system magic quotes)
+ * @param string $password The password (with system magic quotes)
+ *
+ * @return bool Authentication success or failure.
*/
function user_login ($username, $password) {
global $CFG;
*
* called when the user password is updated.
*
- * @param object $user User
- * @param string $newpassword Plaintext password
+ * @param object $user User table object (with system magic quotes)
+ * @param string $newpassword Plaintext password (with system magic quotes)
* @return boolean result
*
*/
/**
* Returns true if this authentication plugin is 'internal'.
*
- * @returns bool
+ * @return bool
*/
function is_internal() {
return true;
}
-
+
/**
* Returns true if this authentication plugin can change the user's
* password.
*
- * @returns bool
+ * @return bool
*/
function can_change_password() {
return true;
}
-
+
/**
* Returns the URL for changing the user's pw, or false if the default can
* be used.
*
- * @returns bool
+ * @return bool
*/
function change_password_url() {
return false;
}
-
+
/**
* Prints a form for configuring this authentication plugin.
*
*
* @param array $page An object containing all the data for this page.
*/
- function config_form($config, $err) {
- include "config.html";
+ function config_form($config, $err, $user_fields) {
+ include 'config.html';
}
/**
function process_config($config) {
return true;
}
-
+
}
?>
<div align="center"><?php print_string('none'); ?></div>
<table cellspacing="0" cellpadding="5" border="0" align="center">
-<?php
+<?php
-global $user_fields;
print_auth_lock_options('manual', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
* 2006-11-01 File created.
*/
-// This page cannot be called directly
-if (!isset($CFG)) {
- exit;
+if (!defined('MOODLE_INTERNAL')) {
+ die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
}
/**
$sso_idp = array();
$sso_idp['name'] = 'sso_idp'; // Name & Description go in lang file
$sso_idp['apiversion'] = 1;
- $sso_idp['methods'] = array('user_authorise','keepalive_server', 'kill_children',
- 'refresh_log', 'fetch_user_image', 'fetch_theme_info',
+ $sso_idp['methods'] = array('user_authorise','keepalive_server', 'kill_children',
+ 'refresh_log', 'fetch_user_image', 'fetch_theme_info',
'update_enrolments');
$sso_sp = array();
*
* @param string $username The username
* @param string $password The password
- * @returns bool Authentication success or failure.
+ * @return bool Authentication success or failure.
*/
function user_login($username, $password) {
return false; // error("Remote MNET users cannot login locally.");
h.wwwroot,
h.id as hostid,
count(c.id) as count
- FROM
+ FROM
{$CFG->prefix}mnet_enrol_course c,
{$CFG->prefix}mnet_enrol_assignments a,
{$CFG->prefix}mnet_host h
$mnet_peer->set_id($mnethostid);
// set up the session
- $mnet_session = get_record('mnet_session',
- 'userid', $USER->id,
- 'mnethostid', $mnethostid,
+ $mnet_session = get_record('mnet_session',
+ 'userid', $USER->id,
+ 'mnethostid', $mnethostid,
'useragent', sha1($_SERVER['HTTP_USER_AGENT']));
if ($mnet_session == false) {
$mnet_session = new object();
*
* @param string $token The random session token.
* @param string $remotewwwroot The ID provider wwwroot.
- * @returns array The local user record.
+ * @return array The local user record.
*/
function confirm_mnet_session($token, $remotewwwroot) {
global $CFG, $MNET, $SESSION;
$count = clean_param($rhost['count'], PARAM_INT);
$url_is_local = stristr($url , $CFG->wwwroot);
if (!empty($name) && !empty($count) && empty($url_is_local)) {
- $localuser->mnet_foreign_host_array[] = array('name' => $name,
- 'url' => $url,
+ $localuser->mnet_foreign_host_array[] = array('name' => $name,
+ 'url' => $url,
'count' => $count);
}
}
}
// set up the session
- $mnet_session = get_record('mnet_session',
- 'userid', $localuser->id,
- 'mnethostid', $remotepeer->id,
+ $mnet_session = get_record('mnet_session',
+ 'userid', $localuser->id,
+ 'mnethostid', $remotepeer->id,
'useragent', sha1($_SERVER['HTTP_USER_AGENT']));
if ($mnet_session == false) {
$mnet_session = new object();
if (!$firsttime) {
// repeat customer! let the IDP know about enrolments
- // we have for this user.
+ // we have for this user.
// set up the RPC request
$mnetrequest = new mnet_xmlrpc_client();
$mnetrequest->set_method('auth/mnet/auth.php/update_enrolments');
// pass username and an assoc array of "my courses"
// with info so that the IDP can maintain mnet_enrol_assignments
$mnetrequest->add_param($remoteuser->username);
- $fields = 'id, category, sortorder, fullname, shortname, idnumber, summary,
+ $fields = 'id, category, sortorder, fullname, shortname, idnumber, summary,
startdate, cost, currency, defaultrole, visible';
$courses = get_my_courses($localuser->id, 'visible DESC,sortorder ASC', $fields);
if (is_array($courses) && !empty($courses)) {
// Second request to do the JOINs that we'd have done
// inside get_my_courses() if we had been allowed
- $sql = "SELECT c.id,
+ $sql = "SELECT c.id,
cc.name AS cat_name, cc.description AS cat_description,
r.shortname as defaultrolename
FROM {$CFG->prefix}course c
} else {
// if the array is empty, send it anyway
// we may be clearing out stale entries
- $courses = array();
+ $courses = array();
}
$mnetrequest->add_param($courses);
*
* @param string $username The username
* @param string $courses Assoc array of courses following the structure of mnet_enrol_course
- * @returns bool
+ * @return bool
*/
function update_enrolments($username, $courses) {
global $MNET_REMOTE_CLIENT, $CFG;
}
// make sure it is a user we have an in active session
// with that host...
- $userid = get_field('mnet_session', 'userid',
- 'username', addslashes($username),
+ $userid = get_field('mnet_session', 'userid',
+ 'username', addslashes($username),
'mnethostid', (int)$MNET_REMOTE_CLIENT->id);
if (!$userid) {
return false;
}
if (empty($courses)) { // no courses? clear out quickly
- delete_records('mnet_enrol_assignments',
+ delete_records('mnet_enrol_assignments',
'hostid', (int)$MNET_REMOTE_CLIENT->id,
'userid', $userid);
return true;
if ($saveflag) {
update_record('mnet_enrol_course', $currentcourse);
}
-
+
if (isset($currentcourse->assignmentid) && is_numeric($currentcourse->assignmentid)) {
$userisregd = true;
}
/**
* Returns true if this authentication plugin is 'internal'.
*
- * @returns bool
+ * @return bool
*/
function is_internal() {
return false;
* Returns true if this authentication plugin can change the user's
* password.
*
- * @returns bool
+ * @return bool
*/
function can_change_password() {
return false;
* Returns the URL for changing the user's pw, or false if the default can
* be used.
*
- * @returns bool
+ * @return bool
*/
function change_password_url() {
return false;
*
* @param array $page An object containing all the data for this page.
*/
- function config_form($config, $err) {
+ function config_form($config, $err, $user_fields) {
global $CFG;
$query = "
$id_providers[]= array('id' => $hostservice->id, 'name' => $hostservice->hostname, 'wwwroot' => $hostservice->wwwroot);
}
}
-
+
include "config.html";
}
} elseif ($mnet_request->response['code'] > 0) {
debugging($mnet_request->response['message']);
}
-
+
if (!isset($mnet_request->response['last log id'])) {
debugging("Server side error has occured on host $mnethostid\nNo log ID was received.");
continue;
}
} else {
- debugging("Server side error has occured on host $mnethostid: " .
+ debugging("Server side error has occured on host $mnethostid: " .
join("\n", $mnet_request->error));
break;
}
$mnetsessions = get_records_sql($sql);
- $ignore = delete_records('mnet_session',
- 'username', $username,
- 'useragent', $useragent,
+ $ignore = delete_records('mnet_session',
+ 'username', $username,
+ 'useragent', $useragent,
'mnethostid', $USER->mnethostid);
if (false != $mnetsessions) {
$mnet_request->add_param($useragent);
if ($mnet_request->send($mnet_peer) === false) {
debugging(join("\n", $mnet_request->error));
- return false;
+ return false;
}
}
$mnet_request->add_param($username);
$mnet_request->add_param($useragent);
if ($mnet_request->send($mnet_peer) === false) {
- debugging("Server side error has occured on host $mnethostid: " .
+ debugging("Server side error has occured on host $mnethostid: " .
join("\n", $mnet_request->error));
}
}
- $ignore = delete_records('mnet_session',
- 'useragent', $useragent,
+ $ignore = delete_records('mnet_session',
+ 'useragent', $useragent,
'userid', $userid);
if (isset($MNET_REMOTE_CLIENT) && isset($MNET_REMOTE_CLIENT->id)) {
<td align="right"><?php echo $host['name']; ?>: </td>
<td colspan="2"><?php echo $host['wwwroot']; ?> </td>
</tr>
-<?php
+<?php
endforeach;
?>
<tr valign="top" class="required">
<td align="right"><?php echo $host['name']; ?>: </td>
<td colspan="2"><?php echo $host['wwwroot']; ?> </td>
</tr>
-<?php
+<?php
endforeach;
-// global $user_fields;
// print_auth_lock_options('mnet', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
require_once dirname(dirname(dirname(__FILE__))) . '/config.php';
+if (!is_enabled_auth('mnet')) {
+ error('mnet is disabled');
+}
+
// grab the GET params - wantsurl could be anything - take it
// with PARAM_RAW
$hostid = required_param('hostid', PARAM_INT);
-$wantsurl = optional_param('wantsurl', '/', PARAM_RAW);
+$wantsurl = optional_param('wantsurl', '/', PARAM_RAW);
// start the mnet session and redirect browser to remote URL
$mnetauth = get_auth_plugin('mnet');
print_error('mnet_session_prohibited', 'mnet', '', '');
}
+if (!is_enabled_auth('mnet')) {
+ error('mnet is disabled');
+}
// grab the GET params
$token = required_param('token', PARAM_BASE64);
$remotewwwroot = required_param('idp', PARAM_URL);
$localuser = $mnetauth->confirm_mnet_session($token, $remotewwwroot);
// log in
-$CFG->auth = 'mnet';
$USER = get_complete_user_data('id', $localuser->id, $localuser->mnethostid);
load_all_capabilities();
* 2006-08-31 File created.
*/
-// This page cannot be called directly
-if (!isset($CFG)) exit;
+if (!defined('MOODLE_INTERNAL')) {
+ die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
+}
/**
* NNTP authentication plugin.
*
* @param string $username The username
* @param string $password The password
- * @returns bool Authentication success or failure.
+ * @return bool Authentication success or failure.
*/
function user_login ($username, $password) {
if (! function_exists('imap_open')) {
print_error('auth_nntpnotinstalled','auth');
exit;
}
-
+
global $CFG;
-
+
// try each multiple host
$hosts = split(';', $this->config->host);
foreach ($hosts as $host) {
error_reporting(0);
$connection = imap_open($host, $username, $password, OP_HALFOPEN);
- error_reporting($CFG->debug);
+ error_reporting($CFG->debug);
if ($connection) {
imap_close($connection);
/**
* Returns true if this authentication plugin is 'internal'.
*
- * @returns bool
+ * @return bool
*/
function is_internal() {
return false;
* Returns true if this authentication plugin can change the user's
* password.
*
- * @returns bool
+ * @return bool
*/
function can_change_password() {
return false;
}
-
+
/**
* Prints a form for configuring this authentication plugin.
*
*
* @param array $page An object containing all the data for this page.
*/
- function config_form($config, $err) {
+ function config_form($config, $err, $user_fields) {
include "config.html";
}
<td>
<input name="host" type="text" size="30" value="<?php echo $config->host ?>" />
<?php
-
+
if (isset($err["host"])) {
formerr($err["host"]);
}
-
+
?>
</td>
<td>
<?php
-
+
print_string("auth_nntphost", "auth");
print_string("auth_multiplehosts", "auth");
if (isset($err["port"])) {
formerr($err["port"]);
}
-
+
?>
</td>
<td><?php print_string("auth_nntpport", "auth") ?></td>
<td><?php print_string('changepasswordhelp', 'auth') ?></td>
</tr>
-<?php
+<?php
-global $user_fields;
print_auth_lock_options('nntp', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
--- /dev/null
+<?php
+
+/**
+ * @author Martin Dougiamas
+ * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
+ * @package moodle multiauth
+ *
+ * Authentication Plugin: No Authentication
+ *
+ * No authentication at all. This method approves everything!
+ *
+ * 2007-02-18 File created.
+ */
+
+if (!defined('MOODLE_INTERNAL')) {
+ die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
+}
+
+/**
+ * Plugin for no authentication.
+ */
+class auth_plugin_nologin {
+
+
+ /**
+ * Constructor.
+ */
+ function auth_plugin_nologin() {
+ }
+
+ /**
+ * Do not allow any login
+ *
+ */
+ function user_login ($username, $password) {
+ return false;
+ }
+
+ /**
+ * No password updates.
+ */
+ function user_update_password($user, $newpassword) {
+ return false;
+ }
+
+ /**
+ * Returns true if this authentication plugin is 'internal'.
+ *
+ * @return bool
+ */
+ function is_internal() {
+ //we do not know if it was internal or external originally
+ return false;
+ }
+
+ /**
+ * Returns true if this authentication plugin can change the user's
+ * password.
+ *
+ * @return bool
+ */
+ function can_change_password() {
+ return false;
+ }
+
+ /**
+ * Returns the URL for changing the user's pw, or false if the default can
+ * be used.
+ *
+ * @return bool
+ */
+ function change_password_url() {
+ return false;
+ }
+
+ /**
+ * Prints a form for configuring this authentication plugin.
+ *
+ * This function is called from admin/auth.php, and outputs a full page with
+ * a form for configuring this plugin.
+ *
+ * @param array $page An object containing all the data for this page.
+ */
+ function config_form($config, $err, $user_fields) {
+ }
+
+ /**
+ * Processes and stores configuration data for this authentication plugin.
+ */
+ function process_config($config) {
+ return true;
+ }
+
+}
+
+?>
* 2006-08-31 File created.
*/
-// This page cannot be called directly
-if (!isset($CFG)) exit;
+if (!defined('MOODLE_INTERNAL')) {
+ die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
+}
/**
* Plugin for no authentication.
*
* @param string $username The username
* @param string $password The password
- * @returns bool Authentication success or failure.
+ * @return bool Authentication success or failure.
*/
function user_login ($username, $password) {
global $CFG;
/**
* Returns true if this authentication plugin is 'internal'.
*
- * @returns bool
+ * @return bool
*/
function is_internal() {
return true;
* Returns true if this authentication plugin can change the user's
* password.
*
- * @returns bool
+ * @return bool
*/
function can_change_password() {
return true;
}
-
+
/**
* Returns the URL for changing the user's pw, or false if the default can
* be used.
*
- * @returns bool
+ * @return bool
*/
function change_password_url() {
return false;
}
-
+
/**
* Prints a form for configuring this authentication plugin.
*
*
* @param array $page An object containing all the data for this page.
*/
- function config_form($config, $err) {
+ function config_form($config, $err, $user_fields) {
include "config.html";
}
<div align="center"><?php print_string('none'); ?></div>
<table cellspacing="0" cellpadding="5" border="0" align="center">
-<?php
+<?php
-global $user_fields;
print_auth_lock_options('none', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
*
* Authentication Plugin: PAM Authentication
*
- * PAM (Pluggable Authentication Modules) for Moodle
- *
+ * PAM (Pluggable Authentication Modules) for Moodle
+ *
* Description:
* Authentication by using the PHP4 PAM module:
* http://www.math.ohio-state.edu/~ccunning/pam_auth/
- *
+ *
* Version 0.3 2006/09/07 by Jonathan Harker (plugin class)
* Version 0.2: 2004/09/01 by Martin V�geli (stable version)
* Version 0.1: 2004/08/30 by Martin V�geli (first draft)
- *
+ *
* Contact: martinvoegeli@gmx.ch
* Website 1: http://elearning.zhwin.ch/
* Website 2: http://birdy1976.com/
* 2006-08-31 File created.
*/
-// This page cannot be called directly
-if (!isset($CFG)) exit;
+if (!defined('MOODLE_INTERNAL')) {
+ die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
+}
/**
* PAM authentication plugin.
* The configuration details for the plugin.
*/
var $config;
-
+
/**
* Store error messages from pam authentication attempts.
*/
*
* @param string $username The username
* @param string $password The password
- * @returns bool Authentication success or failure.
+ * @return bool Authentication success or failure.
*/
function user_login ($username, $password) {
// variable to store possible errors during authentication
$errormessage = str_repeat(' ', 2048);
-
+
// just for testing and debugging
// error_reporting(E_ALL);
else {
$this->lasterror = $errormessage;
return false;
- }
+ }
}
/**
* Returns true if this authentication plugin is 'internal'.
*
- * @returns bool
+ * @return bool
*/
function is_internal() {
return false;
* Returns true if this authentication plugin can change the user's
* password.
*
- * @returns bool
+ * @return bool
*/
function can_change_password() {
return false;
}
-
+
/**
* Prints a form for configuring this authentication plugin.
*
*
* @param array $page An object containing all the data for this page.
*/
- function config_form($config, $err) {
+ function config_form($config, $err, $user_fields) {
include "config.html";
}
<div align="center"><?php print_string('none'); ?></div>
<table cellspacing="0" cellpadding="5" border="0" align="center">
-<?php
+<?php
-global $user_fields;
print_auth_lock_options('pam', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
* 2006-08-31 File created.
*/
-// This page cannot be called directly
-if (!isset($CFG)) exit;
+if (!defined('MOODLE_INTERNAL')) {
+ die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
+}
/**
* POP3 authentication plugin.
*
* @param string $username The username
* @param string $password The password
- * @returns bool Authentication success or failure.
+ * @return bool Authentication success or failure.
*/
function user_login($username, $password) {
if (! function_exists('imap_open')) {
print_error('auth_pop3notinstalled','auth');
exit;
}
-
+
global $CFG;
$hosts = split(';', $this->config->host); // Could be multiple hosts
foreach ($hosts as $host) { // Try each host in turn
error_reporting(0);
$connection = imap_open($host, $username, $password);
- error_reporting($CFG->debug);
-
+ error_reporting($CFG->debug);
+
if ($connection) {
imap_close($connection);
return true;
/**
* Returns true if this authentication plugin is 'internal'.
*
- * @returns bool
+ * @return bool
*/
function is_internal() {
return false;
* Returns true if this authentication plugin can change the user's
* password.
*
- * @returns bool
+ * @return bool
*/
function can_change_password() {
return false;
}
-
+
/**
* Returns the URL for changing the user's pw, or false if the default can
* be used.
*
- * @returns bool
+ * @return bool
*/
function change_password_url() {
return $CFG->changepasswordurl; // TODO: will this be global?
//return $this->config->changepasswordurl;
}
-
+
/**
* Prints a form for configuring this authentication plugin.
*
*
* @param array $page An object containing all the data for this page.
*/
- function config_form($config, $err) {
+ function config_form($config, $err, $user_fields) {
include "config.html";
}
}
// save settings
- set_config('host', $config->host, 'auth/pop3');
- set_config('type', $config->type, 'auth/pop3');
+ set_config('host', $config->host, 'auth/pop3');
+ set_config('type', $config->type, 'auth/pop3');
set_config('port', $config->port, 'auth/pop3');
set_config('mailbox', $config->mailbox, 'auth/pop3');
set_config('changepasswordurl', $config->changepasswordurl, 'auth/pop3');
</td>
<td>
<?php
-
+
print_string('auth_pop3host', 'auth');
print_string('auth_multiplehosts', 'auth');
-
+
?>
</td>
</tr>
<td><?php print_string('changepasswordhelp', 'auth') ?></td>
</tr>
-<?php
+<?php
-global $user_fields;
print_auth_lock_options('pop3', $user_fields, get_string('auth_fieldlocks_help', 'auth'), false, false);
?>
* 2006-08-31 File created.
*/
-// This page cannot be called directly
-if (!isset($CFG)) exit;
+if (!defined('MOODLE_INTERNAL')) {
+ die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
+}
/**
* RADIUS authentication plugin.
*
* @param string $username The username
* @param string $password The password
- * @returns bool Authentication success or failure.
+ * @return bool Authentication success or failure.
*/
function user_login ($username, $password) {
require_once 'Auth/RADIUS.php';
-
+
// Added by Clive on 7th May for test purposes
// printf("Username: $username <br/>");
// printf("Password: $password <br/>");
// printf("host: $this->config->host <br/>");
// printf("nasport: $this->config->nasport <br/>");
// printf("secret: $this->config->secret <br/>");
-
+
$rauth = new Auth_RADIUS_PAP($username, $password);
$rauth->addServer($this->config->host, $this->config->nasport, $this->config->secret);
-
+
if (!$rauth->start()) {
printf("Radius start: %s<br/>\n", $rauth->getError());
exit;
}
-
+
$result = $rauth->send();
if (PEAR::isError($result)) {
printf("Radius send failed: %s<br/>\n", $result->getMessage());
// printf("Radius Auth rejected<br/>\n");
return false;
}
-
+
// get attributes, even if auth failed
if (!$rauth->getAttributes()) {
printf("Radius getAttributes: %s<br/>\n", $rauth->getError());
} else {
$rauth->dumpAttributes();
}
-
+
$rauth->close();
}
/**
* Returns true if this authentication plugin is 'internal'.
*
- * @returns bool
+ * @return bool
*/
function is_internal() {
return false;
* Returns true if this authentication plugin can change the user's
* password.
*
- * @returns bool
+ * @return bool
*/
function can_change_password() {
return false;
}
-
+
/**
* Prints a form for configuring this authentication plugin.
*
*
* @param array $page An object containing all the data for this page.
*/
- function config_form($config, $err) {
+ function config_form($config, $err, $user_fields) {
include "config.html";
}
// Is Auth/RADIUS really there?
if ((!include_once('Auth/RADIUS.php')) or (!class_exists(Auth_RADIUS_PAP))) {
print '<p align="center"><font color="red"><strong>Warning: The Auth_RADIUS module does not seem to be present. Please ensure it is installed and enabled.</strong></font></p>';
-}
+}
// set to defaults if undefined
if (!isset($config->host)) {
<td>
<input name="nasport" type="text" size="6" value="<?php echo $config->nasport ?>" />
<?php
-
+
if (isset($err['nasport'])) {
formerr($err['nasport']);
}
-
+
?>
</td>
<td><?php print_string('auth_radiusnasport', 'auth') ?></td>
<td>
<input name="secret" type="text" size="6" value="<?php echo $config->secret ?>" />
<?php
-
+
if (isset($err['secret'])) {
formerr($err['secret']);
}
-------------------------------------------------------------------------------
Requirements:
-- Shibboleth target 1.1 or later. See documentation for your Shibboleth
+- Shibboleth target 1.1 or later. See documentation for your Shibboleth
federation on how to set up Shibboleth.
Changes:
Moodle Configuration with Dual login
-------------------------------------------------------------------------------
1. Protect the directory moodle/auth/shibboleth/ with Shibboleth.
- The page index.php in that directory actually logs in a Shibboleth user.
+ The page index.php in that directory actually logs in a Shibboleth user.
For Apache you have to define a rule like the following in the Apache config:
--
</Location>
--
- To restrict access to Moodle, replace the access rule 'require valid-user'
+ To restrict access to Moodle, replace the access rule 'require valid-user'
with something that fits your needs, e.g. 'require affiliation student'.
- For IIS you have protect the auth/shibboleth directory directly in the
+ For IIS you have protect the auth/shibboleth directory directly in the
RequestMap of the Shibboleth configuration file (shibboleth.xml). See
https://authdev.it.ohio-state.edu/twiki/bin/view/Shibboleth/xmlaccesscontrol?topic=XMLAccessControl
-2. As Moodle admin, go to the 'Administrations >> Users >> Authentication
+2. As Moodle admin, go to the 'Administrations >> Users >> Authentication
Options' and select the 'Shibboleth' authentication method from the pop-up.
-
-3. Fill in the fields of the form. The fields 'Username', 'First name',
- 'Surname', etc should contain the name of the environment variables of the
- Shibboleth attributes that you want to map onto the corresponding Moodle
- variable (e.g. 'HTTP_SHIB_PERSON_SURNAME' for the person's last name, refer
+
+3. Fill in the fields of the form. The fields 'Username', 'First name',
+ 'Surname', etc should contain the name of the environment variables of the
+ Shibboleth attributes that you want to map onto the corresponding Moodle
+ variable (e.g. 'HTTP_SHIB_PERSON_SURNAME' for the person's last name, refer
the Shibboleth documentation or the documentation of your Shibboleth
federation for information on which attributes are available).
- Especially the 'Username' field is of great importance because
+ Especially the 'Username' field is of great importance because
this attribute is used for the Moodle authentication of Shibboleth users.
-
+
#############################################################################
Shibboleth Attributes needed by Moodle:
For Moodle to work properly Shibboleth should at least provide the attributes
lengths for each field in the user profile.
#############################################################################
-4. The large text field 'Instructions' must contain a link to the
- moodle/auth/shibboleth/index.php file which is protected by
- Shibboleth (see step 1) and causes the Shibboleth login procedure to start.
- You could also use HTML code in that field, e.g. to create your own
+4. The large text field 'Instructions' must contain a link to the
+ moodle/auth/shibboleth/index.php file which is protected by
+ Shibboleth (see step 1) and causes the Shibboleth login procedure to start.
+ You could also use HTML code in that field, e.g. to create your own
Shibboleth login button.
5. Save the changes for the Shibboleth authentication method.
If you want Shibboleth as your only authentication method, configure Moodle as
described in the dual login section above and do the following steps:
-4.a On the Moodle Shibboleth settings page, set the 'Alternate Login URL' to
+4.a On the Moodle Shibboleth settings page, set the 'Alternate Login URL' to
the URL of the file 'moodle/auth/shibboleth/index.php'
This will enforce Shibboleth login.
How the Shibboleth authentication works
--------------------------------------------------------------------------------
-To get Shibboleth authenticated in Moodle a user basically must access the
-Shibboleth-protected page /auth/shibboleth/index.php. If Shibboleth is the only
-authentication method (see 4.a), this happens automatically when a user wants to
-login in Moodle. Otherwise, the user has to click on the link on the login page
+To get Shibboleth authenticated in Moodle a user basically must access the
+Shibboleth-protected page /auth/shibboleth/index.php. If Shibboleth is the only
+authentication method (see 4.a), this happens automatically when a user wants to
+login in Moodle. Otherwise, the user has to click on the link on the login page
you provided in step 4.
Moodle basically checks whether the Shibboleth attribute that you mapped
-as the username is present. This attribute should only be present if a user is
+as the username is present. This attribute should only be present if a user is
Shibboleth authenticated.
If the user's Moodle account has not existed yet, it gets automatically created.
To prevent that every Shibboleth user can access your Moodle site you have to
-adapt the 'require valid-user' line in your webserver's config (see step 1) to
+adapt the 'require valid-user' line in your webserver's config (see step 1) to
allow only specific users. If you defined some authorization rules in step 1,
-these are checked by Shibboleth itself. Only users who met these rules
+these are checked by Shibboleth itself. Only users who met these rules
actually can access /auth/shibboleth/index.php and get logged in.
-You can use Shibboleth AND another authentication method (it was tested with
-manual login). So, if there are a few users that don't have a Shibboleth
-login, you could create manual accounts for them and they could use the manual
-login. For other authentication methods you first have to configure them and
-then set Shibboleth as your authentication method. Users can log in only via one
+You can use Shibboleth AND another authentication method (it was tested with
+manual login). So, if there are a few users that don't have a Shibboleth
+login, you could create manual accounts for them and they could use the manual
+login. For other authentication methods you first have to configure them and
+then set Shibboleth as your authentication method. Users can log in only via one
authentication method unless they have two accounts in Moodle.
Shibboleth dual login with custom login page
--------------------------------------------------------------------------------
-Of course you can create a dual login page that better fits your needs. For this
-to work, you have to set up the two authentication methods (e.g. 'Manual' and
-'Shibboleth') and specify an alternate login link to your own dual login page.
+Of course you can create a dual login page that better fits your needs. For this
+to work, you have to set up the two authentication methods (e.g. 'Manual' and
+'Shibboleth') and specify an alternate login link to your own dual login page.
On that page you basically need a link to the Shibboleth-protected page
-('/auth/shibboleth/index.php') for the Shibboleth login and a
+('/auth/shibboleth/index.php') for the Shibboleth login and a
form that sends 'username' and 'password' to moodle/login/index.php.
Consult the Moodle documentation for further instructions and requirements.
Among the Shibboleth settings in Moodle there is a field that should contain a
path to a php file that can be used as data manipulation hook.
You can use this if you want to further process the way your Shibboleth
-attributes are used in Moodle.
+attributes are used in Moodle.
-Example 1: Your Shibboleth federation uses an attribute that specifies the
+Example 1: Your Shibboleth federation uses an attribute that specifies the
user's preferred language, but the content of this attribute is not
compatible with the Moodle data representation, e.g. the Shibboleth
- attribute contains 'German' but Moodle needs a two letter value like
+ attribute contains 'German' but Moodle needs a two letter value like
'de'.
Example 2: The country, city and street are provided in one Shibboleth attribute
and you want these values to be used in the Moodle user profile. So
You have to parse the corresponding attribute to fill the user fields.
-If you want to use this hook you have to be a skilled PHP programmer. It is
-strongly recommended that you take a look at the file
-moodle/auth/shibboleth/auth.php, especially the function 'get_userinfo'
-where this file is included.
+If you want to use this hook you have to be a skilled PHP programmer. It is
+strongly recommended that you take a look at the file
+moodle/auth/shibboleth/auth.php, especially the function 'get_userinfo'
+where this file is included.
The context of the file is the same as within this login function. So you
can directly edit the object $result.
if ($_SERVER[$pluginconfig->field_map_address] != '')
{
// $address contains something like 'SWITCH$Limmatquai 138$CH-8021 Zurich'
- // We want to split this up to get:
+ // We want to split this up to get:
// institution, street, zipcode, city and country
$address = $_SERVER[$pluginconfig->field_map_address];
list($institution, $street, $zip_city) = split('\$', $address);
ereg(' (.+)',$zip_city, $regs);
$city = $regs[1];
-
+
ereg('(.+)-',$zip_city, $regs);
$country = $regs[1];
-
+
$result["address"] = $street;
$result["city"] = $city;
$result["country"] = $country;
--
--------------------------------------------------------------------------------
-In case of problems and questions with Shibboleth authentication, contact
+In case of problems and questions with Shibboleth authentication, contact
Lukas Haemmerle <haemmerle@switch.ch> or Markus Hagman <hagman@hytti.uku.fi>
* 2006-10-27 Upstream 1.7 changes merged in, added above credits from lib.php :-)
*/
-// This page cannot be called directly
-if (!isset($CFG)) exit;
+if (!defined('MOODLE_INTERNAL')) {
+ die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
+}
/**
* Shibboleth authentication plugin.
*
* @param string $username The username
* @param string $password The password
- * @returns bool Authentication success or failure.
+ * @return bool Authentication success or failure.
*/
function user_login($username, $password) {
// If we are in the shibboleth directory then we trust the server var
$result = array();
$search_attribs = array();
-
+
foreach ($attrmap as $key=>$value) {
if (!empty($CFG->unicodedb)) {
$result[$key] = $this->get_first_string($_SERVER[$value]);
// Provide an API to modify the information to fit the Moodle internal
// data representation
- if (
- $config->convert_data
+ if (
+ $config->convert_data
&& $config->convert_data != ''
&& is_readable($config->convert_data)
) {
-
+
// Include a custom file outside the Moodle dir to
// modify the variable $moodleattributes
include($config->convert_data);
}
-
+
return $result;
}
function get_attributes() {
$configarray = (array) $this->config;
- $fields = array("firstname", "lastname", "email", "phone1", "phone2",
- "department", "address", "city", "country", "description",
+ $fields = array("firstname", "lastname", "email", "phone1", "phone2",
+ "department", "address", "city", "country", "description",
"idnumber", "lang", "guid");
$moodleattributes = array();
/**
* Returns true if this authentication plugin is 'internal'.
*
- * @returns bool
+ * @return bool
*/
function is_internal() {
return false;
* Returns true if this authentication plugin can change the user's
* password.
*
- * @returns bool
+ * @return bool
*/
function can_change_password() {
return false;
}
-
+
/**
* Prints a form for configuring this authentication plugin.
*
*
* @param array $page An object containing all the data for this page.
*/
- function config_form($config, $err) {
+ function config_form($config, $err, $user_fields) {
include "config.html";
}
<tr valign="top">
<td align="right"><?php print_string("instructions", "auth") ?>:</td>
<td>
- <textarea name="auth_instructions" cols="30" rows="10" wrap="virtual"><?php p($config->auth_instructions) ?></textarea>
+ <textarea name="auth_instructions" cols="30" rows="10" wrap="virtual"><?php p($config->auth_instructions) ?></textarea>
</td>
<td>
<?php
<tr valign="top">
<td align="right"><?php print_string("auth_shib_convert_data", "auth") ?>:</td>
<td>
- <input name="convert_data" type="text" size="30" value="<?php echo $config->convert_data?>">
- <?php
+ <input name="convert_data" type="text" size="30" value="<?php echo $config->convert_data?>">
+ <?php
if ($config->convert_data and $config->convert_data != '' and !is_readable($config->convert_data)) {
echo '<br/><font color="red">';
<td><?php print_string('changepasswordhelp', 'auth') ?></td>
</tr>
-<?php
+<?php
-global $user_fields;
print_auth_lock_options('shibboleth', $user_fields, '<!-- empty help -->', true, false);
?>
$urltogo = $CFG->wwwroot.'/'; /// Go to the standard home page
unset($SESSION->wantsurl); /// Just in case
}
-
+
redirect($urltogo);
}
$frm->username = $_SERVER[$pluginconfig->user_attribute];
$frm->password = substr(base64_encode($_SERVER[$pluginconfig->user_attribute]),0,8);
// The random password consists of the first 8 letters of the base 64 encoded user ID
- // This password is never used unless the user account is converted to manual
+ // This password is never used unless the user account is converted to manual
/// Check if the user has actually submitted login data to us
-
+
if ($user = authenticate_user_login($frm->username, $frm->password)) {
// Let's get them all set up.
update_user_login_times();
set_moodle_cookie($USER->username);
set_login_session_preferences();
-
+
if (user_not_fully_set_up($USER)) {
$urltogo = $CFG->wwwroot.'/user/edit.php?id='.$USER->id.'&course='.SITEID;
// We don't delete $SESSION->wantsurl yet, so we get there later
$urltogo = $CFG->wwwroot.'/'; /// Go to the standard home page
unset($SESSION->wantsurl); /// Just in case
}
-
+
/// Go to my-moodle page instead of homepage if mymoodleredirect enabled
if (!has_capability('moodle/site:config',get_context_instance(CONTEXT_SYSTEM, SITEID)) and !empty($CFG->mymoodleredirect) and !isguest()) {
if ($urltogo == $CFG->wwwroot or $urltogo == $CFG->wwwroot.'/' or $urltogo == $CFG->wwwroot.'/index.php') {
$urltogo = $CFG->wwwroot.'/my/';
}
}
-
+
load_all_capabilities(); /// This is what lets the user do anything on the site :-)
redirect($urltogo);
}
}
-
- // If we can find any (user independent) Shibboleth attributes but no user
+
+ // If we can find any (user independent) Shibboleth attributes but no user
// attributes we probably didn't receive any user attributes
elseif (!empty($_SERVER['HTTP_SHIB_APPLICATION_ID'])) {
error(get_string( 'shib_no_attributes_error', 'auth' , '\''.$pluginconfig->user_attribute.'\', \''.$pluginconfig->field_map_firstname.'\', \''.$pluginconfig->field_map_lastname.'\' and \''.$pluginconfig->field_map_email.'\''));