--- LdapAuthentication.php	2009-06-29 11:46:50.000000000 +0100
+++ LdapAuthentication.php	2009-06-29 13:13:28.000000000 +0100
@@ -115,7 +115,7 @@
 			return true;
 		}
 
-		$this->ldapconn = $this->connect();
+		$this->connect();
 		if ( $this->ldapconn ) {
 			$this->printDebug( "Successfully connected", NONSENSITIVE );
 
@@ -162,6 +162,11 @@
 
 		$this->printDebug( "Entering Connect", NONSENSITIVE );
 
+		if ($this->ldapconn != null) {
+			$this->printDebug( "LDAP Connection previously established. Ignoring 'connect' call.", NONSENSITIVE );
+			return;
+		}
+
                 if ( !function_exists( 'ldap_connect' ) ) {
 			$this->printDebug( "It looks like you are issing LDAP support; please ensure you have either compiled LDAP support in, or have enabled the module. If the authentication is working for you, the plugin isn't properly detecting the LDAP module, and you can safely ignore this message.", NONSENSITIVE );
 			return false;
@@ -889,14 +894,37 @@
 	 */
 	function getCanonicalName( $username ) {
 		global $wgLDAPUseLocal;
+		global $wgHooks;
 		$this->printDebug( "Entering getCanonicalName", NONSENSITIVE );
 
 		if ( $username != '' ) {
 			$this->printDebug( "Username isn't empty.", NONSENSITIVE );
 
+			// This check allows Username rewriting BEFORE Mediawiki creates a User object in the login process.
+			// if MW calls this function before any LDAP calls have been made the LDAPUsername attribute will be null.
+			if (isset($wgHooks['SetUsernameAttributeFromLDAP']) && count($wgHooks['SetUsernameAttributeFromLDAP']) > 0 &&
+				($this->LDAPUsername == null || $this->LDAPUsername == '')){
+				
+				$this->printDebug( "Trying to get data from LDAP for username rewrite.", NONSENSITIVE );
+				
+				$this->connect();
+				if ( $this->ldapconn ) {
+					$this->printDebug( "Successfully connected", NONSENSITIVE );
+
+					// getSearchString will set LDAPUsername if it can.
+					$this->getSearchString( $username );
+
+					// getSearchString is going to bind, but will not unbind
+					// Let's clean up
+					@ldap_unbind();
+				} else {
+					$this->printDebug( "Failed to connect", NONSENSITIVE );
+				}
+			}
+			
 			//We want to use the username returned by LDAP
 			//if it exists
-			if ( $this->LDAPUsername != '' ) {
+			if ( $this->LDAPUsername != null && $this->LDAPUsername != '' ) {
 				$this->printDebug( "Using LDAPUsername.", NONSENSITIVE );
 				$username = $this->LDAPUsername;
 			}
