]> git.mjollnir.org Git - moodle.git/commitdiff
MDL-8590 auth cleanup - part 1
authorskodak <skodak>
Tue, 20 Feb 2007 17:03:36 +0000 (17:03 +0000)
committerskodak <skodak>
Tue, 20 Feb 2007 17:03:36 +0000 (17:03 +0000)
44 files changed:
auth/README
auth/README2
auth/cas/README-CAS
auth/cas/auth.php
auth/cas/auth_ldap_sync_users.php
auth/cas/config.html
auth/cas/index_form.html
auth/cas/login.php
auth/db/auth.php
auth/db/auth_db_sync_users.php
auth/db/config.html
auth/email/auth.php
auth/email/config.html
auth/fc/Readme.txt
auth/fc/auth.php
auth/fc/config.html
auth/fc/fcFPP.php
auth/imap/auth.php
auth/imap/config.html
auth/ldap/README-LDAP
auth/ldap/auth.php
auth/ldap/auth_ldap_sync_users.php
auth/ldap/config.html
auth/manual/auth.php
auth/manual/config.html
auth/mnet/auth.php
auth/mnet/config.html
auth/mnet/jump.php
auth/mnet/land.php
auth/nntp/auth.php
auth/nntp/config.html
auth/nologin/auth.php [new file with mode: 0644]
auth/none/auth.php
auth/none/config.html
auth/pam/auth.php
auth/pam/config.html
auth/pop3/auth.php
auth/pop3/config.html
auth/radius/auth.php
auth/radius/config.html
auth/shibboleth/README.txt
auth/shibboleth/auth.php
auth/shibboleth/config.html
auth/shibboleth/index.php

index 72944542ee71c8c2c992c197122b49eccca5170c..ac074c2b234cd137aebf32021428c9b8e01bf393 100644 (file)
@@ -1,9 +1,9 @@
 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
@@ -22,18 +22,18 @@ part of the enabled plugin sequence).
 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
@@ -81,7 +81,7 @@ nntp  - Uses an external NNTP server
 
 
 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
@@ -203,14 +203,14 @@ AUTHENTICATION
 
 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.
 
@@ -225,7 +225,7 @@ Optional:
     Query other userinformation from database.
 
     Returns:
-    Userinformation in array ( name => value, .... 
+    Userinformation in array ( name => value, ....
     or false in case of error
 
 
@@ -251,9 +251,9 @@ USER CREATION
 
 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
 
@@ -261,7 +261,7 @@ from moodle to external database
     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.
@@ -270,7 +270,7 @@ from moodle to external database
     True on success otherwise false
 
 
-    user_activate ($username) 
+    user_activate ($username)
 
     activate new user after email-address is confirmed
 
@@ -297,11 +297,3 @@ USER INFORMATION AND SYNCRONIZATION
     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
-
-
index 40ba27490d02b51a773270cb14c64320c95d6504..2934800fa148f1248a968810377612610e69e697 100644 (file)
@@ -11,9 +11,6 @@ get_auth_plugin() that does the work for you:
 
    $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
@@ -63,6 +60,7 @@ user_login($username, $password)
    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
@@ -79,9 +77,10 @@ change_password_url()
 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
 -----------------------------
index 64bfdfcb17f35ea78a1042973075896761a7fb69..8b133052b151e638e043f8d49e2b926605b481f1 100644 (file)
@@ -2,6 +2,6 @@ CAS-module README
 
 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
 
 
index 55b5b99e7b15f59b65aa88cd559191533dd8c301..af55197908fb7e4c221eae20d3cf11b6b1c99f24 100644 (file)
@@ -11,8 +11,9 @@
  * 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.
@@ -38,21 +39,21 @@ class auth_plugin_cas {
      *
      * @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') {
@@ -72,7 +73,7 @@ class auth_plugin_cas {
 
         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);
@@ -205,7 +206,7 @@ class auth_plugin_cas {
     /**
      * Returns true if this authentication plugin is 'internal'.
      *
-     * @returns bool
+     * @return bool
      */
     function is_internal() {
         return false;
@@ -215,7 +216,7 @@ class auth_plugin_cas {
      * Returns true if this authentication plugin can change the user's
      * password.
      *
-     * @returns bool
+     * @return bool
      */
     function can_change_password() {
         return false;
@@ -229,7 +230,7 @@ class auth_plugin_cas {
      *
      * @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';
     }
 
@@ -237,7 +238,7 @@ class auth_plugin_cas {
      * 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;
@@ -288,7 +289,7 @@ class auth_plugin_cas {
         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);
 
index 2e7316151cff17ba55412116e2ce02bf925c6bfa..e4caec4b45db13a9c1442278a0bece9b7fde7997 100644 (file)
@@ -2,31 +2,33 @@
 /** 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');
@@ -34,7 +36,12 @@ require_once($CFG->dirroot.'/lib/blocklib.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);
 
index 22250ff1a20d6f33856db32ac306d820ca7d962a..d666ce1283e2b708a3212b8526160da985947640 100644 (file)
@@ -52,7 +52,7 @@
         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>
index 78ee639482be81ca38a0c7bc1e01fe15255ecf1d..2e1fa1ca69f0a575c17450cfe71476434303883a 100644 (file)
@@ -12,7 +12,7 @@
   <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">
@@ -41,7 +41,7 @@
     $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>
index c0940bf59d5014fc8803d38bdc6ed80f8b4e12ed..d2148b6011564301bf01a8e8c54482d839de7c23 100644 (file)
@@ -70,8 +70,8 @@ defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
         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();
@@ -91,7 +91,7 @@ defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
                 $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");
             }
@@ -111,7 +111,7 @@ defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
             $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)) {
@@ -122,7 +122,7 @@ defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
                 }
             }
 
-            
+
             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)) {
@@ -143,12 +143,12 @@ defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
             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;
@@ -162,7 +162,7 @@ defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
             redirect($urltogo);
 
             exit;
-    
+
         } else {
           if ($CFG->auth == "cas" ) { /// CAS error login
             $errormsg = get_string("invalidcaslogin");
@@ -174,8 +174,8 @@ defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
     }
     $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();
@@ -226,7 +226,7 @@ defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
             }
         }
 
-        
+
         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)) {
@@ -247,12 +247,12 @@ defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
         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;
@@ -278,18 +278,18 @@ defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
     }
 
     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 {
@@ -301,8 +301,8 @@ defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
     } 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();
 
index bb370dc28be8de2b5c43dab3b78cb5a2647539ec..27f0574187e4f6f68573dc03a01be2213d3fdcbb 100644 (file)
@@ -45,7 +45,7 @@ class auth_plugin_db {
      *
      * @return bool Authentication success or failure.
      */
-    function user_login ($username, $password) {
+    function user_login($username, $password) {
 
         global $CFG;
 
@@ -53,17 +53,7 @@ class auth_plugin_db {
         $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
@@ -108,7 +98,7 @@ class auth_plugin_db {
                 return false;
             }
 
-            if ( $rs->RecordCount() ) {
+            if ($rs->RecordCount()) {
                 return true;
             } else {
                 return false;
@@ -117,20 +107,7 @@ class auth_plugin_db {
         }
     }
 
-
-    /**
-     * 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)) {
@@ -143,18 +120,47 @@ class auth_plugin_db {
             $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) {
@@ -193,7 +199,7 @@ class auth_plugin_db {
 
         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;
@@ -215,60 +221,68 @@ class auth_plugin_db {
      * 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
@@ -300,9 +314,14 @@ class auth_plugin_db {
                         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
                 }
@@ -332,8 +351,7 @@ class auth_plugin_db {
         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;
@@ -354,23 +372,16 @@ class auth_plugin_db {
                 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();
@@ -379,22 +390,12 @@ class auth_plugin_db {
         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)."' ");
@@ -417,17 +418,7 @@ class auth_plugin_db {
 
     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
@@ -475,11 +466,9 @@ class auth_plugin_db {
      *
      * @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));
 
@@ -494,7 +483,6 @@ class auth_plugin_db {
         // 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);
 
@@ -510,13 +498,69 @@ class auth_plugin_db {
                 }
 
                 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;
     }
 
     /**
@@ -534,7 +578,7 @@ class auth_plugin_db {
     /**
      * Returns true if this authentication plugin is 'internal'.
      *
-     * @returns bool
+     * @return bool
      */
     function is_internal() {
         return false;
@@ -544,7 +588,7 @@ class auth_plugin_db {
      * 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');
@@ -554,7 +598,7 @@ class auth_plugin_db {
      * 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;
@@ -568,7 +612,7 @@ class auth_plugin_db {
      *
      * @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';
     }
 
@@ -616,6 +660,9 @@ class auth_plugin_db {
         if (!isset($config->debugauthdb)) {
             $config->debugauthdb = 0;
         }
+        if (!isset($config->removeuser)) {
+            $config->removeuser = 0;
+        }
         if (!isset($config->changepasswordurl)) {
             $config->changepasswordurl = '';
         }
@@ -633,8 +680,9 @@ class auth_plugin_db {
         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;
index 264df1916eb33f0ef4206c266a8bbc1c42ff0311..b4e22aa4b829e969db306f05d19922bedfbd8177 100644 (file)
@@ -2,8 +2,8 @@
 /** 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
@@ -32,10 +32,15 @@ $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->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);
 
index 52a15b90b60cb15620a2914cbe2f1b7572fd6ee2..0712137cda8cdd2939eecec06a265f026417850d 100644 (file)
@@ -2,34 +2,34 @@
 
     // 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>
index 78d3882d9d20e168d576be8b698e2f00c3f5da51..140fc2195b120789e92eb978d8ef311242396ab7 100644 (file)
@@ -12,8 +12,9 @@
  * 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
@@ -48,7 +49,7 @@ class auth_plugin_email {
      *
      * @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;
@@ -89,7 +90,7 @@ class auth_plugin_email {
             $emailconfirm = get_string('emailconfirm');
             print_header($emailconfirm, $emailconfirm, $emailconfirm);
             notice(get_string('emailconfirmsent', '', $user->email), "$CFG->wwwroot/index.php");
-        }        
+        }
     }
 
     /*
@@ -117,32 +118,32 @@ class auth_plugin_email {
     /**
      * 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.
      *
@@ -151,7 +152,7 @@ class auth_plugin_email {
      *
      * @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";
     }
 
@@ -161,7 +162,7 @@ class auth_plugin_email {
     function process_config($config) {
         return true;
     }
-        
+
 }
 
 ?>
index b15015800003649e8990f49775a78d3c654c68c3..da2b148f554ea36d0b7cc9c5dd1179f1ba90d665 100644 (file)
@@ -2,9 +2,8 @@
 <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);
 
 ?>
index da49241c65a622401d5ac8144b96eaa9a69031fb..c40e7ffe976f2e198767f34608401948dee6ebc9 100644 (file)
@@ -1,7 +1,7 @@
 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
 ------------
@@ -9,7 +9,7 @@ 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
@@ -23,7 +23,7 @@ Default account name is "fcMoodle".
 
 
 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
@@ -47,7 +47,7 @@ Get user some_user_id 1201
 
 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.
 
index 0308bb2991675d65e733d438ff54d37db39e915d..f61b25c8f7da77c6968736375c88f187f42d8ef8 100644 (file)
  * 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.
@@ -39,7 +40,7 @@ class auth_plugin_fc {
      *
      * @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;
@@ -57,7 +58,7 @@ class auth_plugin_fc {
             }
         }
         $fpp->close();
-    
+
         return $retval;
     }
 
@@ -82,13 +83,13 @@ class auth_plugin_fc {
         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)) {
@@ -101,7 +102,7 @@ class auth_plugin_fc {
             }
         }
         $fpp->close();
-    
+
         foreach($userinfo as $key => $value) {
             if (!$value) {
                 unset($userinfo[$key]);
@@ -110,23 +111,23 @@ class auth_plugin_fc {
 
         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)) {
@@ -134,24 +135,24 @@ class auth_plugin_fc {
             }
         }
         $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;
@@ -161,7 +162,7 @@ class auth_plugin_fc {
      * Returns true if this authentication plugin can change the user's
      * password.
      *
-     * @returns bool
+     * @return bool
      */
     function can_change_password() {
         return false;
@@ -175,7 +176,7 @@ class auth_plugin_fc {
      *
      * @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";
     }
 
index e99b1188ba2b6b342023c86df9cc6ab8dd4feb77..12787bd4a6e83a3d572330e35c3e14f2af4df72c 100644 (file)
     }
     if (!isset($config->creators)) {
         $config->creators = "";
-    }    
+    }
     if (!isset($config->changepasswordurl)) {
         $config->changepasswordurl = '';
-    }   
+    }
     if (!isset($config->changepasswordurl)) {
         $config->changepasswordurl = '';
     }
@@ -95,9 +95,8 @@
     <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);
 
 ?>
index 1e6351bef42cc620d21f1dd8afeb3776d8872f68..57a2ef1848cfdba49ac088026d6ed422d1d7cf0c 100644 (file)
  */
 
 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()
     {
@@ -53,10 +53,10 @@ class fcFPP
         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
@@ -69,7 +69,7 @@ class fcFPP
 
     // close any open connections
     function close()
-    {        
+    {
     // get the current connection
     $conn = &$this->_conn;
 
@@ -84,8 +84,8 @@ class fcFPP
     }
     return;
     }
-    
-    
+
+
     // Authenticate to the FirstClass server
     function login($userid, $passwd)
     {
@@ -98,37 +98,37 @@ class fcFPP
         $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");
@@ -143,29 +143,29 @@ class fcFPP
         }
             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");
@@ -180,17 +180,17 @@ class fcFPP
         }
         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");
@@ -203,17 +203,17 @@ class fcFPP
             $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;
 
     }
-    
-    
+
+
 }
-   
+
 
 ?>
index 0e91e8249a8e891e6385f5bd236ff259360d5aa0..448c3ad13f6e86aec8e673616e13c35490fcac99 100644 (file)
@@ -12,8 +12,9 @@
  * 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.
@@ -38,14 +39,14 @@ class auth_plugin_imap {
      *
      * @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
 
@@ -56,22 +57,22 @@ class auth_plugin_imap {
                 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);
@@ -85,7 +86,7 @@ class auth_plugin_imap {
     /**
      * Returns true if this authentication plugin is 'internal'.
      *
-     * @returns bool
+     * @return bool
      */
     function is_internal() {
         return false;
@@ -95,23 +96,23 @@ class auth_plugin_imap {
      * 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.
      *
@@ -120,7 +121,7 @@ class auth_plugin_imap {
      *
      * @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";
     }
 
index 658107675ef90c2fd354cf5e4c756875355b4000..e2b2311fd964e9998ad02b3b89da63b29e28e48b 100644 (file)
@@ -85,9 +85,8 @@ if (!isset($config->changepasswordurl)) {
     <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);
 
 ?>
index 698294d63e6c5f20f4a320dc197b2ede9afbdc0e..11efdf50d41fd09382b73d98a156e9ecd95ba57a 100644 (file)
@@ -1,3 +1,3 @@
 LDAP-module README
 
-Please read comments from lib.php 
+Please read comments from lib.php
index 88d95da9382574bc90826b63d44cf14e0689094d..daf3c7ce06620aba5afa8692d0f80b59fad18549 100644 (file)
  * 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
 }
 
 /**
@@ -31,19 +27,40 @@ class auth_plugin_ldap {
     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')) {
@@ -51,22 +68,19 @@ class auth_plugin_ldap {
             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);
@@ -74,7 +88,7 @@ class auth_plugin_ldap {
             }
 
             // 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;
@@ -94,18 +108,20 @@ class auth_plugin_ldap {
      * 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);
@@ -113,66 +129,64 @@ class auth_plugin_ldap {
             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;
         }
@@ -184,163 +198,75 @@ class auth_plugin_ldap {
      *
      * 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;
     }
 
     /**
@@ -353,32 +279,33 @@ class auth_plugin_ldap {
      * @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.");
         }
 
@@ -389,41 +316,36 @@ class auth_plugin_ldap {
     /**
      * 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';
@@ -431,7 +353,7 @@ class auth_plugin_ldap {
                 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 #
@@ -439,7 +361,7 @@ class auth_plugin_ldap {
                 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';
@@ -448,17 +370,17 @@ class auth_plugin_ldap {
                 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;
         }
 
         ////
@@ -472,13 +394,12 @@ class auth_plugin_ldap {
         $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)) {
@@ -490,8 +411,7 @@ class auth_plugin_ldap {
                 $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,
@@ -500,88 +420,122 @@ class auth_plugin_ldap {
 
             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));
@@ -589,124 +543,118 @@ class auth_plugin_ldap {
             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();
@@ -717,168 +665,182 @@ class auth_plugin_ldap {
         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);
@@ -887,10 +849,10 @@ class auth_plugin_ldap {
                 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);
@@ -898,22 +860,24 @@ class auth_plugin_ldap {
         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;
@@ -923,72 +887,77 @@ class auth_plugin_ldap {
                     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;
 
     }
@@ -999,8 +968,8 @@ class auth_plugin_ldap {
      * 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
      *
      */
@@ -1009,23 +978,27 @@ class auth_plugin_ldap {
     /// 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 : '
@@ -1040,16 +1013,16 @@ class auth_plugin_ldap {
                     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) {
@@ -1063,19 +1036,19 @@ class auth_plugin_ldap {
                     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);
@@ -1090,23 +1063,20 @@ class auth_plugin_ldap {
      *
      * @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:
@@ -1121,8 +1091,8 @@ class auth_plugin_ldap {
     function ldap_getdefaults() {
         $default['objectclass'] = array(
                             'edir' => 'User',
-                            'rfc2703' => 'posixAccount',
-                            'rfc2703bis' => 'posixAccount',
+                            'rfc2307' => 'posixAccount',
+                            'rfc2307bis' => 'posixAccount',
                             'samba' => 'sambaSamAccount',
                             'ad' => 'user',
                             'default' => '*'
@@ -1140,7 +1110,7 @@ class auth_plugin_ldap {
                             'rfc2307' => 'member',
                             'rfc2307bis' => 'member',
                             'samba' => 'member',
-                            'ad' => 'member', 
+                            'ad' => 'member',
                             'default' => 'member'
                             );
         $default['memberattribute_isdn'] = array(
@@ -1159,7 +1129,7 @@ class auth_plugin_ldap {
                             'ad' => '', //No support yet
                             'default' => ''
                             );
-        return $default; 
+        return $default;
     }
 
     /**
@@ -1169,84 +1139,40 @@ class auth_plugin_ldap {
      * @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':
@@ -1256,12 +1182,12 @@ class auth_plugin_ldap {
                 $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;
@@ -1273,23 +1199,22 @@ class auth_plugin_ldap {
      * @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.
@@ -1298,14 +1223,13 @@ class auth_plugin_ldap {
      * @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;
             }
@@ -1318,17 +1242,17 @@ class auth_plugin_ldap {
         }
 
         $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;
@@ -1350,12 +1274,6 @@ class auth_plugin_ldap {
      * @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 == '') {
@@ -1366,9 +1284,9 @@ class auth_plugin_ldap {
                $bindpwd = $this->config->bind_pw;
             }
         }
-        
+
         $urls = explode(";",$this->config->host_url);
-            
+
         foreach ($urls as $server) {
             $server = trim($server);
             if (empty($server)) {
@@ -1377,21 +1295,21 @@ class auth_plugin_ldap {
 
             $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);
             }
@@ -1399,7 +1317,7 @@ class auth_plugin_ldap {
             if ($bindresult) {
                 return $connresult;
             }
-            
+
             $debuginfo .= "<br/>Server: '$server' <br/> Connection: '$connresult'<br/> Bind result: '$bindresult'</br>";
         }
 
@@ -1415,24 +1333,22 @@ class auth_plugin_ldap {
      * 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);
@@ -1442,14 +1358,14 @@ class auth_plugin_ldap {
 
             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) {
@@ -1468,8 +1384,8 @@ class auth_plugin_ldap {
      */
 
     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) {
@@ -1492,8 +1408,6 @@ class auth_plugin_ldap {
 
     function ldap_get_userlist($filter="*") {
     /// returns all users from ldap servers
-        global $CFG;
-
         $fresult = array();
 
         $ldapconnection = $this->ldap_connect();
@@ -1503,7 +1417,7 @@ class auth_plugin_ldap {
         }
 
         $contexts = explode(";",$this->config->contexts);
-     
+
         if (!empty($this->config->create_context)) {
               array_push($contexts, $this->config->create_context);
         }
@@ -1525,7 +1439,7 @@ class auth_plugin_ldap {
                                          $filter,
                                          array($this->config->user_attribute));
             }
-            
+
             $users = $this->ldap_get_entries($ldapconnection, $ldap_result);
 
             //add found users to list
@@ -1533,7 +1447,7 @@ class auth_plugin_ldap {
                 array_push($fresult, ($users[$i][$this->config->user_attribute][0]) );
             }
         }
-       
+
         return $fresult;
     }
 
@@ -1545,7 +1459,7 @@ class auth_plugin_ldap {
      *
      * @return array ldap-entries
      */
-       
+
     function ldap_get_entries($conn, $searchresult) {
     //Returns values like ldap_get_entries but is
     //binary compatible
@@ -1562,8 +1476,8 @@ class auth_plugin_ldap {
                 else {
                     $fresult[$i][$attributes[$j]] = array($values);
                 }
-            }         
-            $i++;               
+            }
+            $i++;
         }
         while ($entry = @ldap_next_entry($conn, $entry));
         //were done
@@ -1573,7 +1487,7 @@ class auth_plugin_ldap {
     /**
      * Returns true if this authentication plugin is 'internal'.
      *
-     * @returns bool
+     * @return bool
      */
     function is_internal() {
         return false;
@@ -1583,22 +1497,26 @@ class auth_plugin_ldap {
      * 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.
      *
@@ -1607,8 +1525,8 @@ class auth_plugin_ldap {
      *
      * @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';
     }
 
     /**
@@ -1616,55 +1534,61 @@ class auth_plugin_ldap {
      */
     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');
@@ -1687,10 +1611,34 @@ class auth_plugin_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;
+    }
 }
 
 ?>
index c5d5d16e66b44abdeee77267769adc8569f56366..2e29140b68a6ec424137bd83b29edc302bb32e7b 100755 (executable)
@@ -1,40 +1,45 @@
 <?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);
 
index b7a23fd4c4841439d17f6dcfd101431fff8f8de6..140f1358278ae71cdda00a6dde2b6242b4c4eb93 100644 (file)
@@ -1,62 +1,63 @@
 <?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">
 
@@ -67,29 +68,45 @@ if (!function_exists('ldap_connect')) { // Is php4-ldap really there?
 </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>
@@ -99,36 +116,31 @@ if (!function_exists('ldap_connect')) { // Is php4-ldap really there?
 </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>
 
@@ -139,88 +151,84 @@ if (!function_exists('ldap_connect')) { // Is php4-ldap really there?
 </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>
 
@@ -231,44 +239,30 @@ if (!function_exists('ldap_connect')) { // Is php4-ldap really there?
 </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'])) {
@@ -287,69 +281,65 @@ if (!function_exists('ldap_connect')) { // Is php4-ldap really there?
 </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>
 
@@ -362,16 +352,9 @@ if (!function_exists('ldap_connect')) { // Is php4-ldap really there?
 </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"); ?>
@@ -379,12 +362,12 @@ if (!function_exists('ldap_connect')) { // Is php4-ldap really there?
 </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>
 
@@ -396,16 +379,38 @@ if (!function_exists('ldap_connect')) { // Is php4-ldap really there?
 </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');
@@ -414,8 +419,7 @@ $help .= get_string('auth_updateremote_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);
 
 ?>
 
index 82dcd0f66b7412419c527c5689d6105efda418ac..cd867f4003397f615afdf52077e2cf51f754647e 100644 (file)
@@ -11,8 +11,9 @@
  * 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.
@@ -38,9 +39,10 @@ class auth_plugin_manual
      * 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;
@@ -55,8 +57,8 @@ class auth_plugin_manual
      *
      * 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
      *
      */
@@ -68,32 +70,32 @@ class auth_plugin_manual
     /**
      * 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.
      *
@@ -102,8 +104,8 @@ class auth_plugin_manual
      *
      * @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';
     }
 
     /**
@@ -112,7 +114,7 @@ class auth_plugin_manual
     function process_config($config) {
         return true;
     }
-        
+
 }
 
 ?>
index 59e4bf953ef78251934bce9a48e98e184c40f7ce..14e4de41754f255e402d0ea30eb0e9cf5c55d5ea 100644 (file)
@@ -2,9 +2,8 @@
 <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);
 
 ?>
index f1d98244a28f4d2e838599ed788acb99050df3d8..2d672b8dde4d3942930596e20f84c15201b1adbb 100644 (file)
@@ -12,9 +12,8 @@
  * 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
 }
 
 /**
@@ -44,8 +43,8 @@ class auth_plugin_mnet
         $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();
@@ -63,7 +62,7 @@ class auth_plugin_mnet
      *
      * @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.");
@@ -136,7 +135,7 @@ class auth_plugin_mnet
                     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
@@ -198,9 +197,9 @@ class auth_plugin_mnet
         $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();
@@ -241,7 +240,7 @@ class auth_plugin_mnet
      *
      *   @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;
@@ -359,8 +358,8 @@ class auth_plugin_mnet
                     $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);
                     }
                 }
@@ -379,9 +378,9 @@ class auth_plugin_mnet
         }
 
         // 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();
@@ -404,7 +403,7 @@ class auth_plugin_mnet
 
         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');
@@ -412,13 +411,13 @@ class auth_plugin_mnet
             // 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
@@ -453,7 +452,7 @@ class auth_plugin_mnet
             } else {
                 // if the array is empty, send it anyway
                 // we may be clearing out stale entries
-                $courses = array(); 
+                $courses = array();
             }
             $mnetrequest->add_param($courses);
 
@@ -475,7 +474,7 @@ class auth_plugin_mnet
      *
      *   @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;
@@ -485,15 +484,15 @@ class auth_plugin_mnet
         }
         // 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;
@@ -563,7 +562,7 @@ class auth_plugin_mnet
                 if ($saveflag) {
                     update_record('mnet_enrol_course', $currentcourse);
                 }
-                
+
                 if (isset($currentcourse->assignmentid) && is_numeric($currentcourse->assignmentid)) {
                     $userisregd = true;
                 }
@@ -597,7 +596,7 @@ class auth_plugin_mnet
     /**
      * Returns true if this authentication plugin is 'internal'.
      *
-     * @returns bool
+     * @return bool
      */
     function is_internal() {
         return false;
@@ -607,7 +606,7 @@ class auth_plugin_mnet
      * Returns true if this authentication plugin can change the user's
      * password.
      *
-     * @returns bool
+     * @return bool
      */
     function can_change_password() {
         return false;
@@ -617,7 +616,7 @@ class auth_plugin_mnet
      * 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;
@@ -631,7 +630,7 @@ class auth_plugin_mnet
      *
      * @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 = "
@@ -687,7 +686,7 @@ class auth_plugin_mnet
                 $id_providers[]= array('id' => $hostservice->id, 'name' => $hostservice->hostname, 'wwwroot' => $hostservice->wwwroot);
             }
         }
+
         include "config.html";
     }
 
@@ -763,13 +762,13 @@ class auth_plugin_mnet
                 } 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;
             }
@@ -1043,9 +1042,9 @@ class auth_plugin_mnet
 
         $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) {
@@ -1060,7 +1059,7 @@ class auth_plugin_mnet
             $mnet_request->add_param($useragent);
             if ($mnet_request->send($mnet_peer) === false) {
                 debugging(join("\n", $mnet_request->error));
-                return false; 
+                return false;
             }
         }
 
@@ -1121,13 +1120,13 @@ class auth_plugin_mnet
             $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)) {
index 9848d9489d38ea675fa0f230c3325afe34d68902..070d07d3dd0f30cb69c4f913dd9b0cf3bf17d319 100644 (file)
@@ -65,7 +65,7 @@ foreach($id_providers as $host):
     <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">
@@ -78,10 +78,9 @@ foreach($service_providers as $host):
     <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);
 
 ?>
index 99a73fb0d173af17ce9145bd544834e7a45301b6..0dcc271c63e864551da4714f8fcb87c3c4e199c9 100644 (file)
 
 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');
index e03f4a96c9d9b54822e30595be6b244e95baba86..905119adf5e9f4a0052d03a16ad1dcd9c05b020e 100644 (file)
@@ -19,6 +19,9 @@ if (!$site = get_site()) {
     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);
@@ -29,7 +32,6 @@ $mnetauth = get_auth_plugin('mnet');
 $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();
 
index 39ef4756885aff738fa8640d0bd1de2ff8ccedf3..1cb5d376fc6d0fa062cf31c58a0a0c77b3f4a0a9 100644 (file)
@@ -12,8 +12,9 @@
  * 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.
@@ -38,16 +39,16 @@ class auth_plugin_nntp {
      *
      * @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) {
@@ -55,7 +56,7 @@ class auth_plugin_nntp {
 
             error_reporting(0);
             $connection = imap_open($host, $username, $password, OP_HALFOPEN);
-            error_reporting($CFG->debug);   
+            error_reporting($CFG->debug);
 
             if ($connection) {
                 imap_close($connection);
@@ -68,7 +69,7 @@ class auth_plugin_nntp {
     /**
      * Returns true if this authentication plugin is 'internal'.
      *
-     * @returns bool
+     * @return bool
      */
     function is_internal() {
         return false;
@@ -78,12 +79,12 @@ class auth_plugin_nntp {
      * 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.
      *
@@ -92,7 +93,7 @@ class auth_plugin_nntp {
      *
      * @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";
     }
 
index 67bc050ea072ee300c5fa24b4f745861eec82e32..2da7bbaeeb0aac0af777a984ff4a40004268d9cc 100644 (file)
@@ -19,16 +19,16 @@ if (!isset($config->changepasswordurl)) {
     <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");
 
@@ -45,7 +45,7 @@ if (!isset($config->changepasswordurl)) {
         if (isset($err["port"])) {
             formerr($err["port"]);
         }
-        
+
         ?>
     </td>
     <td><?php print_string("auth_nntpport", "auth") ?></td>
@@ -66,9 +66,8 @@ if (!isset($config->changepasswordurl)) {
     <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);
 
 ?>
diff --git a/auth/nologin/auth.php b/auth/nologin/auth.php
new file mode 100644 (file)
index 0000000..1ff8341
--- /dev/null
@@ -0,0 +1,96 @@
+<?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;
+    }
+
+}
+
+?>
index 00d7976a72115a0919290923086ac349de94527e..57c2b2a2f460423e24e43ecb393bb4475680036c 100644 (file)
@@ -12,8 +12,9 @@
  * 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.
@@ -41,7 +42,7 @@ class auth_plugin_none {
      *
      * @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;
@@ -69,7 +70,7 @@ class auth_plugin_none {
     /**
      * Returns true if this authentication plugin is 'internal'.
      *
-     * @returns bool
+     * @return bool
      */
     function is_internal() {
         return true;
@@ -79,22 +80,22 @@ class auth_plugin_none {
      * 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.
      *
@@ -103,7 +104,7 @@ class auth_plugin_none {
      *
      * @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";
     }
 
index f8e7d036203704ee1506ba1ddc21f12254c93f50..cdc7ff7962f125078f277aae9a0226916deb6e90 100644 (file)
@@ -2,9 +2,8 @@
 <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);
 
 ?>
index 22904271e4a4cd47af8134a1a3df4eef533efcb1..45ac727b1cde38ec4f95d172433f470b92758832 100644 (file)
@@ -7,16 +7,16 @@
  *
  * 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/
@@ -26,8 +26,9 @@
  * 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.
@@ -38,7 +39,7 @@ class auth_plugin_pam {
      * The configuration details for the plugin.
      */
     var $config;
-    
+
     /**
      * Store error messages from pam authentication attempts.
      */
@@ -58,12 +59,12 @@ class auth_plugin_pam {
      *
      * @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);
 
@@ -75,13 +76,13 @@ class auth_plugin_pam {
         else {
             $this->lasterror = $errormessage;
             return false;
-        }        
+        }
     }
 
     /**
      * Returns true if this authentication plugin is 'internal'.
      *
-     * @returns bool
+     * @return bool
      */
     function is_internal() {
         return false;
@@ -91,12 +92,12 @@ class auth_plugin_pam {
      * 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.
      *
@@ -105,7 +106,7 @@ class auth_plugin_pam {
      *
      * @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";
     }
 
index ba6c0eaf1053a638dbbb6e49d06ec3d40e6b495e..5252f18ca5c32356e6a1d225d8fb61b5f3902209 100644 (file)
@@ -2,9 +2,8 @@
 <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);
 
 ?>
index 41ebc120ddb07e90301479e0cbe6c7447e8948dd..7927b06c069cc178e4ca7fe7769f028a499b4976 100644 (file)
@@ -12,8 +12,9 @@
  * 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.
@@ -38,14 +39,14 @@ class auth_plugin_pop3 {
      *
      * @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
@@ -72,8 +73,8 @@ class auth_plugin_pop3 {
 
             error_reporting(0);
             $connection = imap_open($host, $username, $password);
-            error_reporting($CFG->debug);   
-     
+            error_reporting($CFG->debug);
+
             if ($connection) {
                 imap_close($connection);
                 return true;
@@ -85,7 +86,7 @@ class auth_plugin_pop3 {
     /**
      * Returns true if this authentication plugin is 'internal'.
      *
-     * @returns bool
+     * @return bool
      */
     function is_internal() {
         return false;
@@ -95,23 +96,23 @@ class auth_plugin_pop3 {
      * 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.
      *
@@ -120,7 +121,7 @@ class auth_plugin_pop3 {
      *
      * @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";
     }
 
@@ -146,8 +147,8 @@ class auth_plugin_pop3 {
         }
 
         // 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');
index 784e2841aec044e2bab6364bb1f6d7618650f616..6031d304d3c8e33123333064a21e6fa6870dda05 100644 (file)
@@ -34,10 +34,10 @@ if (!isset($config->changepasswordurl)) {
     </td>
     <td>
         <?php
-        
+
         print_string('auth_pop3host', 'auth');
         print_string('auth_multiplehosts', 'auth');
-        
+
         ?>
     </td>
 </tr>
@@ -103,9 +103,8 @@ if (!isset($config->changepasswordurl)) {
     <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);
 
 ?>
index c173eaeb24244cc8c301e80024e98e7c0ae0dded..1f30f0f1b4f80c34e6ce71dcfe11c516cd3f65ca 100644 (file)
@@ -13,8 +13,9 @@
  * 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.
@@ -39,26 +40,26 @@ class auth_plugin_radius {
      *
      * @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());
@@ -70,21 +71,21 @@ class auth_plugin_radius {
             // 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;
@@ -94,12 +95,12 @@ class auth_plugin_radius {
      * 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.
      *
@@ -108,7 +109,7 @@ class auth_plugin_radius {
      *
      * @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";
     }
 
index bf582b00d12b30daae97968abc564feb3a424c12..f0b6b8f08794e8f894ac764411a2e0de1922c21f 100644 (file)
@@ -5,7 +5,7 @@
 // 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)) {
@@ -44,11 +44,11 @@ if (!isset($config->changepasswordurl)) {
     <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>
@@ -59,7 +59,7 @@ if (!isset($config->changepasswordurl)) {
     <td>
         <input name="secret" type="text" size="6" value="<?php echo $config->secret ?>" />
         <?php
-        
+
         if (isset($err['secret'])) {
             formerr($err['secret']);
         }
index ec2633bf7bbf2eb29ed36071982fea38f6e0265c..9c65529469127b8f6a803ce38172e4d94e2c587e 100644 (file)
@@ -2,7 +2,7 @@ Shibboleth Authentication for Moodle
 -------------------------------------------------------------------------------
 
 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:
@@ -20,7 +20,7 @@ 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:
 
 --
@@ -31,25 +31,25 @@ Moodle Configuration with Dual login
 </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
@@ -60,10 +60,10 @@ Moodle Configuration with Dual login
    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.
@@ -73,44 +73,44 @@ Moodle Configuration with Shibboleth only login
 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.
 
@@ -119,21 +119,21 @@ How to customize the way the Shibboleth user data is used in Moodle
 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.
 
@@ -146,16 +146,16 @@ Example file:
     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;
@@ -165,5 +165,5 @@ Example file:
 --
 
 --------------------------------------------------------------------------------
-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>
index aca35835233aefc66552f7612233c9b765fbf1ab..7450f7a828bd8b67a1d169ff6f9e260b55de909f 100644 (file)
@@ -18,8 +18,9 @@
  * 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.
@@ -44,7 +45,7 @@ class auth_plugin_shibboleth {
      *
      * @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
@@ -75,7 +76,7 @@ class auth_plugin_shibboleth {
 
         $result = array();
         $search_attribs = array();
-      
+
         foreach ($attrmap as $key=>$value) {
             if (!empty($CFG->unicodedb)) {
                 $result[$key] = $this->get_first_string($_SERVER[$value]);
@@ -86,17 +87,17 @@ class auth_plugin_shibboleth {
 
          // 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;
     }
 
@@ -106,8 +107,8 @@ class auth_plugin_shibboleth {
     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();
@@ -124,7 +125,7 @@ class auth_plugin_shibboleth {
     /**
      * Returns true if this authentication plugin is 'internal'.
      *
-     * @returns bool
+     * @return bool
      */
     function is_internal() {
         return false;
@@ -134,12 +135,12 @@ class auth_plugin_shibboleth {
      * 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.
      *
@@ -148,7 +149,7 @@ class auth_plugin_shibboleth {
      *
      * @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";
     }
 
index fedfc08f5d74dbd7d2670aae9673f4a152cc85c2..e09e6b2a7e9c7c1963648b6343e05d456a1d64cd 100755 (executable)
@@ -30,7 +30,7 @@
 <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
@@ -45,8 +45,8 @@
 <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">';
@@ -74,9 +74,8 @@
     <td><?php print_string('changepasswordhelp', 'auth') ?></td>
 </tr>
 
-<?php 
+<?php
 
-global $user_fields;
 print_auth_lock_options('shibboleth', $user_fields, '<!-- empty help -->', true, false);
 
 ?>
index e71094b8c61416bcdde452d602a40aa34223eae1..398688c16379e3cefe5d5ad8904a938e0b7b3510 100644 (file)
@@ -13,7 +13,7 @@
             $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.
@@ -43,7 +43,7 @@
             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.'&amp;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.'\''));