Index: /extensions/Ldap_Login/admin/configuration.php
===================================================================
--- /extensions/Ldap_Login/admin/configuration.php	(revision 28533)
+++ /extensions/Ldap_Login/admin/configuration.php	(revision 28534)
@@ -12,21 +12,35 @@
 $me = new Ldap();
 $me->load_config();
+$me->ldap_conn();
 //$me = get_plugin_data($plugin_id);
 
 $template->assign('HOST', 	$me->config['host']);
 $template->assign('BASEDN',	$me->config['basedn']); // racine !
+$template->assign('USERSBRANCH',$me->config['usersbranch']);
+$template->assign('GROUPBRANCH',$me->config['groupbranch']);
+$template->assign('LD_SEARCH_USERS',$me->config['ld_search_users']);
+$template->assign('LD_SEARCH_GROUPS',$me->config['ld_search_groups']);
 $template->assign('PORT', 	$me->config['port']);
 $template->assign('LD_ATTR',	$me->config['ld_attr']);
+$template->assign('LD_GROUP',	$me->config['ld_group']);
 $template->assign('LD_USE_SSL',	$me->config['ld_use_ssl']);
 $template->assign('LD_BINDPW',	$me->config['ld_bindpw']);
 $template->assign('LD_BINDDN',	$me->config['ld_binddn']);
+$template->assign('WEBMASTERS_GROUP',	$me->config['webmasters_group']);
+$template->assign('ADMINS_GROUP',	$me->config['admins_group']);
 
 if (isset($_POST['save'])){
 	$me->config['host'] 	 = $_POST['HOST'];
 	$me->config['basedn']    = $_POST['BASEDN'];
+	$me->config['usersbranch']    = $_POST['USERSBRANCH'];
+	$me->config['groupbranch']    = $_POST['GROUPBRANCH'];
 	$me->config['port']      = $_POST['PORT'];
 	$me->config['ld_attr']   = $_POST['LD_ATTR'];
+	$me->config['ld_group']   = $_POST['LD_GROUP'];
 	$me->config['ld_binddn'] = $_POST['LD_BINDDN'];
 	$me->config['ld_bindpw'] = $_POST['LD_BINDPW'];
+	
+	$me->config['webmasters_group'] = $_POST['WEBMASTERS_GROUP'];
+	$me->config['admins_group'] = $_POST['ADMINS_GROUP'];
 
 	if (isset($_POST['LD_USE_SSL'])){
@@ -34,4 +48,16 @@
 	} else {
 		$me->config['ld_use_ssl'] = False;
+	}
+	
+	if (isset($_POST['LD_SEARCH_GROUPS'])){
+		$me->config['ld_search_groups'] = True;
+	} else {
+		$me->config['ld_search_groups'] = False;
+	}
+	
+	if (isset($_POST['LD_SEARCH_USERS'])){
+		$me->config['ld_search_users'] = True;
+	} else {
+		$me->config['ld_search_users'] = False;
 	}
 }
@@ -44,12 +70,44 @@
 // Check LDAP configuration
 if (isset($_POST['check_ldap'])){
-$check = $me->ldap_name($_POST['USERNAME']);
-$error = $me->check_ldap();
+#$check = $me->ldap_name($_POST['USERNAME']);
+#$error = $me->check_ldap();
 
-	if ($me->ldap_bind_as($_POST['USERNAME'],$_POST['PASSWORD'])){
-	$template->assign('LD_CHECK_LDAP','<p style="color:green;">Configuration LDAP OK : '.$check.'</p>');
+	if ($me->config['users_group']) {
+		if ($me->user_membership($_POST['USERNAME'],$me->ldap_group($me->config['users_group']))) {
+			if ($me->ldap_bind_as($_POST['USERNAME'],$_POST['PASSWORD'])){
+				// search groups
+				$group_query = 'SELECT name, id FROM '.GROUPS_TABLE.';';
+				$groups = pwg_query($group_query);
+				$sentence = '';
+	
+				foreach($groups as $group) {
+					if($me->user_membership($_POST['USERNAME'], $me->ldap_group($group['name']))) {
+						$sentence = $sentence . ', '.$group['name'];
+					}
+				}
+				$template->assign('LD_CHECK_LDAP','<p style="color:green;">Configuration LDAP OK : '.$_POST['USERNAME'].' is in users'.$sentence.' group(s) and can auth. He is a '.$me->ldap_status($_POST['USERNAME']).' user according to the plugin.</p>');
+			}
+			else {
+				$template->assign('LD_CHECK_LDAP','<p style="color:red;">Error : test '.$me->config['uri'].' '.$me->ldap_name($_POST['USERNAME']).'</p>');
+			}
+		}
 	}
 	else {
-	$template->assign('LD_CHECK_LDAP','<p style="color:red;">Error :'.$error.' test '.$me->config['uri'].' '.$check.'</p>');
+		if ($me->ldap_bind_as($_POST['USERNAME'],$_POST['PASSWORD'])){
+			// search groups
+			$group_query = 'SELECT name, id FROM '.GROUPS_TABLE.';';
+			$groups = pwg_query($group_query);
+			$sentence = '';
+	
+			foreach($groups as $group) {
+				if($me->user_membership($_POST['USERNAME'], $me->ldap_group($group['name']))) {
+					$sentence = $sentence . ', '.$group['name'];
+				}
+			}
+			$template->assign('LD_CHECK_LDAP','<p style="color:green;">Configuration LDAP OK : '.$_POST['USERNAME'].' is in group(s) '.$sentence.' and can auth. He is a '.$me->ldap_status($_POST['USERNAME']).' user according to the plugin.</p>');
+		}
+		else {
+			$template->assign('LD_CHECK_LDAP','<p style="color:red;">Error : test '.$me->config['uri'].' '.$me->ldap_name($_POST['USERNAME']).'</p>');
+		}
 	}
 }
Index: /extensions/Ldap_Login/admin/configuration.tpl
===================================================================
--- /extensions/Ldap_Login/admin/configuration.tpl	(revision 28533)
+++ /extensions/Ldap_Login/admin/configuration.tpl	(revision 28534)
@@ -37,11 +37,7 @@
 			<input type="text" id="port" name="PORT" value="{$PORT}" />
 		</li>
-	</ul>
+		
 	<i>{'If empty, localhost and standard protocol ports will be used in configuration.'|@translate}</i>
-    </fieldset>
-    
-    <fieldset class="mainConf">
-	<legend>{'Ldap attributes'|@translate}</legend>
-	<ul>
+		
 		<li>
 			<label for="basedn">{'Base DN'|@translate}</label>
@@ -49,9 +45,80 @@
 			<input size="70" type="text" id="basedn" name="BASEDN" value="{$BASEDN}" />
 		</li>
+	</ul>
 	
+    </fieldset>
+    
+    <fieldset class="mainConf">
+	<legend>{'Ldap users'|@translate}</legend>
+	<ul>
+		<li>
+			<label for="usersbranch">{'Users Branch'|@translate}</label>
+			<br>
+			<input size="70" type="text" id="usersbranch" name="USERSBRANCH" value="{$USERSBRANCH}" />
+		</li>
+		
+		<li>
+			<label for="ld_search_users">
+			{if $LD_SEARCH_USERS }
+				<input type="checkbox" id="ld_search_users" name="LD_SEARCH_USERS" value="{$LD_SEARCH_USERS}" checked />
+			{else}
+				<input type="checkbox" id="ld_search_users" name="LD_SEARCH_USERS" value="{$LD_SEARCH_USERS}" />
+			{/if}
+			{'Search Ldap users ?'|@translate}</label>
+		</li>
+		
 		<li>
 			<label for="ld_attr">{'Attribute corresponding to the user name'|@translate}</label>
 			<br>
 			<input type="text" id="ld_attr" name="LD_ATTR" value="{$LD_ATTR}" />
+		</li>
+	</ul>
+    </fieldset>
+    
+    <fieldset class="mainConf">
+	<legend>{'Ldap groups'|@translate}</legend>
+	
+	<p><i>{'If you create a <a href="admin.php?page=group_list">piwigo group</a> with the same name as an ldap one, all members of the ldap group will automatically join the piwigo group at their next authentication. This allows you to create <a href="admin.php?page=help&section=groups">specific right access management</a> (restrict access to a particaular album...).'|@translate}</i></p>
+	<ul>
+		
+		<li>
+			<label for="groupbranch">{'Groups Branch'|@translate}</label>
+			<br>
+			<input size="70" type="text" id="groupbranch" name="GROUPBRANCH" value="{$GROUPBRANCH}" />
+		</li>
+		
+		<li>
+			<label for="ld_search_groups">
+			{if $LD_SEARCH_GROUPS }
+				<input type="checkbox" id="ld_search_groups" name="LD_SEARCH_GROUPS" value="{$LD_SEARCH_GROUPS}" checked />
+			{else}
+				<input type="checkbox" id="ld_search_groups" name="LD_SEARCH_GROUPS" value="{$LD_SEARCH_GROUPS}" />
+			{/if}
+			{'Search Ldap groups ?'|@translate}</label>
+		</li>
+	
+		<li>
+			<label for="ld_attr">{'Attribute corresponding to the group name'|@translate}</label>
+			<br>
+			<input type="text" id="ld_group" name="LD_GROUP" value="{$LD_GROUP}" />
+		</li>
+		<br>
+		
+		<li>
+			<label for="webmasters_group">{'Webmasters group'|@translate}</label>
+			<br>
+			{'Users members of this ldap group are granted piwigo webmasters.'|@translate}<br>
+			<input size="70" type="text" id="webmasters_group" name="WEBMASTERS_GROUP" value="{$WEBMASTERS_GROUP}" />
+		</li>
+		
+		<li>
+			<label for="admins_group">{'Admins group'|@translate}</label>
+			<br>
+			{'Users members of this ldap group are granted piwigo admins.'|@translate}<br>
+			<input size="70" type="text" id="admins_group" name="ADMINS_GROUP" value="{$ADMINS_GROUP}" />
+			
+			<br><br>
+			
+			{'To get them out of these roles, they must be sorted of the ldap group and then role updated in the <a href="admin.php?page=user_list">piwigo admin</a>. If a group is mandatory as described in the <a href="admin.php?page=plugin-Ldap_Login-newusers">new piwigo users tab</a>, then they must also belong to the users group.'|@translate}
 		</li>
 	</ul>
Index: /extensions/Ldap_Login/admin/newusers.php
===================================================================
--- /extensions/Ldap_Login/admin/newusers.php	(revision 28533)
+++ /extensions/Ldap_Login/admin/newusers.php	(revision 28534)
@@ -17,5 +17,9 @@
 $template->assign('SEND_CASUAL_MAIL',	$me->config['send_password_by_mail_ldap']);
 
+$template->assign('USERS_GROUP',	$me->config['users_group']);
+
 if (isset($_POST['save'])){
+
+	$me->config['users_group'] = $_POST['USERS_GROUP'];
 
 	if (isset($_POST['ALLOW_NEWUSERS'])){
Index: /extensions/Ldap_Login/admin/newusers.tpl
===================================================================
--- /extensions/Ldap_Login/admin/newusers.tpl	(revision 28533)
+++ /extensions/Ldap_Login/admin/newusers.tpl	(revision 28534)
@@ -28,5 +28,12 @@
 	{'Do you allow new piwigo users to be created when users authenticate succesfully on the ldap ?'|@translate}
     </p>
-
+    
+    <p>
+		<b><label for="users_group">{'Users group'|@translate}</label></b>
+		<br>
+		{'Users members of this ldap group (e.g.: piwigo,users ... , default is void ) can authenticate on piwigo and are created if the option above is selected. If left blank, everyone can authenticate.'|@translate}
+		<input size="70" type="text" id="users_group" name="USERS_GROUP" value="{$USERS_GROUP}" />
+	</p>
+    
     <p>
 	{if $ADVERTISE_ADMINS}
@@ -48,5 +55,5 @@
     
 </fieldset>
- 
+
 <p>
 <input type="submit" value="{'Save'|@translate}" name="save" />
Index: /extensions/Ldap_Login/class.ldap.php
===================================================================
--- /extensions/Ldap_Login/class.ldap.php	(revision 28533)
+++ /extensions/Ldap_Login/class.ldap.php	(revision 28534)
@@ -44,22 +44,35 @@
 	{
 		$this->config['host'] = 'localhost';
-		$this->config['basedn'] = 'ou=people,dc=example,dc=com'; // racine !
+		$this->config['basedn'] = 'dc=example,dc=com'; // racine !
+		$this->config['usersbranch'] = 'ou=people';
+		$this->config['groupbranch'] = 'ou=group';
+		$this->config['ld_search_users'] = False;
+		$this->config['ld_search_groups'] = False;
 		$this->config['port'] = ''; // if port is empty, I count on the software to care of it !
 		$this->config['ld_attr'] = 'uid';
+		$this->config['ld_group'] = 'cn';
+		//$this->config['ld_class'] = 'posixAccount';
 		$this->config['ld_use_ssl'] = False;
 		$this->config['ld_bindpw'] ='';
 		$this->config['ld_binddn'] ='';
-		
 		$this->config['allow_newusers'] = False;
 		$this->config['advertise_admin_new_ldapuser'] = False;
 		$this->config['send_password_by_mail_ldap'] = False;
+		
+		$this->config['users_group'] = False;
+		$this->config['webmasters_group'] = False;
+		$this->config['admins_group'] = False;
 	}
 	
 	function load_config() {
-		// first we load the base config
+		$this->load_default_config();
+		
+		// after the default, we can load the actual conf. That way, no holes !
 		$conf_file = @file_get_contents( LDAP_LOGIN_PATH.'data.dat' );
 		if ($conf_file!==false)
 		{
 			$this->config = unserialize($conf_file);
+			$this->config['full_usersbranch'] = $this->config['usersbranch'].','.$this->config['basedn'];
+			$this->config['full_groupbranch'] = $this->config['groupbranch'].','.$this->config['basedn'];
 		}
 	}
@@ -102,19 +115,24 @@
 		}
 
+		// first, we initializes connection to ldap
 		if ($this->cnx = @ldap_connect($this->config['uri'])){
-			@ldap_set_option($this->cnx, LDAP_OPT_PROTOCOL_VERSION, 3); // LDAPv3 if possible
-			return true;
-		}
-		return false;
-		
-		// connect with rootdn in case not anonymous.
-		if (!empty($obj->config['ld_binddn']) && !empty($obj->config['ld_bindpw'])){ // if empty ld_binddn, anonymous work
-		
-		// authentication with rootdn and rootpw for dn search
-		// carefull ! rootdn should be in full ldap style ! Nothing is supposed (to be one of the users the plugin auth…).
-		if (@ldap_bind($obj->config['ld_binddn'],$obj->config['ld_bindpw'])){
-		return false;
-		}
-	}
+				@ldap_set_option($this->cnx, LDAP_OPT_PROTOCOL_VERSION, 3); // LDAPv3 if possible
+		
+			// then we authenticate if anonymous search is forbidden
+			if (!empty($obj->config['ld_binddn']) && !empty($obj->config['ld_bindpw'])){
+				if (@ldap_bind($this->cnx,$this->config['ld_binddn'],$this->config['ld_bindpw'])){
+					return true;
+				}
+				else { return false; }
+			}
+			// if anonymous search is allowed, we still need a fake auth using ldap_bind
+			else {
+				if (@ldap_bind($this->cnx)){
+					return true;
+				}
+				else { return false; }
+			}
+		}
+		else { return false; }
 	}
 
@@ -126,5 +144,19 @@
 	// return the name ldap understand
 	public function ldap_name($name){
-	return $this->config['ld_attr'].'='.$name.','.$this->config['basedn'];
+		if ($this->config['ld_search_users']) {
+			return $this->ldap_search_dn($name);
+		}
+		else { return $this->config['ld_attr'].'='.$name.','.$this->config['full_usersbranch']; }
+	}
+	
+	public function ldap_group($groupname){
+		// this should return an array, even if it's only one !
+		if ($this->config['ld_search_groups']) {
+			return $this->ldap_search_group($groupname);
+		}
+		else {
+		$result[] = $this->config['ld_group'].'='.$groupname.','.$this->config['full_groupbranch'];
+		return $result;
+		}
 	}
 
@@ -138,7 +170,4 @@
 
 	public function ldap_mail($name){
-	
-		//echo $this->cnx;
-		//echo $this->ldap_name($name);
 		$sr=@ldap_read($this->cnx, $this->ldap_name($name), "(objectclass=*)", array('mail'));
 		$entry = @ldap_get_entries($this->cnx, $sr);
@@ -150,26 +179,70 @@
 	}
 	
-	// return userdn (and username) for authentication
-	/* public function ldap_search_dn($to_search){
-		$filter = str_replace('%s',$to_search,$this->config['ld_filter']);
-		//$this->write_log('$filter '.$filter);
-
-		if ($search = @ldap_search($this->cnx,$this->config['basedn'],$filter,array('dn',$this->config['ld_attr']),0,1)){
-			$entry = @ldap_get_entries($this->cnx, $search);
-			if (!empty($entry[0][strtolower($this->config['ld_attr'])][0])) {
-				return $entry;
-			}
-		}
-		return false;
-	} */
-	
-	
-	public function getAttr() {
+	public function ldap_search_group($to_search){
+		$ld_group = $this->config['ld_group'];
+		
+		$sr=@ldap_search($this->cnx, $this->config['full_groupbranch'], "($ld_group=$to_search)", array('dn'),0,0);
+		$groups = @ldap_get_entries($this->cnx, $sr);
+		$result = array();
+		foreach ($groups as $group) {
+			$result[] = $group['dn'];
+		}
+		return $result;
+	}
+	
+	public function ldap_search_dn($to_search){
+		$ld_attr = $this->config['ld_attr'];
+		
+		$sr=@ldap_search($this->cnx, $this->config['full_usersbranch'], "($ld_attr=$to_search)", array('dn','mail'),0,0);
+		$entry = @ldap_get_entries($this->cnx, $sr);
+		
+		if (!empty($entry[0]['dn'])) {
+			return $entry[0]['dn'];
+			}
+		else { return False; }
+	}
+	
+	public function user_membership($user, $groups){
+		// $groups is an array of groupdn ! (there is a possibility of several groups, we search the user in each of them).
+		foreach ($groups as $groupdn) {
+			$filter = '(objectClass=*)';
+			$result = @ldap_read($this->cnx,$groupdn,$filter,array('memberUid'));
+			$result2 = @ldap_get_entries($this->cnx, $result);
+			if(isset($result2[0]['memberuid'])){
+				foreach($result2[0]['memberuid'] as $item){
+					if ($item == $user){
+						return True;
+					}
+				}
+			}
+		}
+		return False;
+	}
+	
+	public function ldap_status($username){
+		if ($this->config['webmasters_group']) {
+			if ($this->user_membership($username,$this->ldap_group($this->config['webmasters_group']))) {
+				// set status to webmaster and quit (more powerfull, no need to get further)
+				return 'webmaster';
+			}
+		}
+		if ($this->config['admins_group']) {
+			if ($this->user_membership($username,$this->ldap_group($this->config['admins_group']))) {
+				// set status to admin
+				return 'admin';
+			}
+		}
+		else 
+		{
+		return 'normal';
+		}
+	}
+	
+	public function getAttr(){
 	$search = @ldap_read($this->cnx, "cn=subschema", "(objectClass=*)", array('*', 'subschemasubentry'));
 	$entries = @ldap_get_entries($this->cnx, $search);
-	echo count($entries);
-	}
-	
-	public function getRootDse() {
+	}
+	
+	public function getRootDse(){
 
         $search = @ldap_read($this->cnx, NULL, 'objectClass=*', array("*", "+"));
@@ -177,5 +250,4 @@
         return $entries[0];
 	}
-
 
 	public function ldap_check_basedn(){
Index: /extensions/Ldap_Login/language/en_UK/plugin.lang.php
===================================================================
--- /extensions/Ldap_Login/language/en_UK/plugin.lang.php	(revision 28533)
+++ /extensions/Ldap_Login/language/en_UK/plugin.lang.php	(revision 28534)
@@ -26,11 +26,16 @@
 $lang['Secure connexion'] = 'Secure connection (ldaps)';
 $lang['Ldap port'] = 'LDAP port';
+$lang['Base DN'] = 'Base DN of LDAP server (e.g.: dc=example,dc=com):';
 
-// ldap attributes
+// ldap users
+$lang['Ldap users'] = 'LDAP users';
+$lang['Users branch'] = 'Branch where LDAP users should be found (e.g.: ou=users):';
+$lang['Attribute corresponding to the user name'] = 'Attribute corresponding to the user name';
+$lang['Search Ldap users ?'] = 'Search Ldap users ? If you have your users widespreaded in several branchs or OU, you will need this. If you avoid it, you save one ldap request. You may not need it if your ldap tree is simple (e.g.: uid=user,ou=people,dc=example,dc=com).';
 
-$lang['Ldap attributes'] = 'LDAP attributes';
-$lang['Base DN'] = 'Base DN where LDAP users should be found (e.g.: ou=users,dc=example,dc=com):';
-$lang['Ldap filter :'] = 'LDAP filter';
-$lang['Attribute corresponding to the user name'] = 'Attribute corresponding to the user name';
+// ldap groups
+$lang['Ldap groups'] = 'LDAP groups';
+$lang['Groups branch'] = 'Branch where LDAP groups should be found (e.g.: ou=groups):';
+$lang['Search Ldap groups ?'] = 'Search Ldap users ? If you have your groups widespreaded in several branchs or OU, you will need this. If you avoid it, you save one ldap request. You may not need it if your ldap tree is simple (e.g.: cn=groupname,ou=groups,dc=example,dc=com).';
 
 // ldap connection credentials
Index: /extensions/Ldap_Login/language/fr_FR/plugin.lang.php
===================================================================
--- /extensions/Ldap_Login/language/fr_FR/plugin.lang.php	(revision 28533)
+++ /extensions/Ldap_Login/language/fr_FR/plugin.lang.php	(revision 28534)
@@ -25,4 +25,5 @@
 $lang['Secure connexion'] = 'Connexion sécurisée (ldaps)';
 $lang['Ldap port'] = 'Port a utiliser';
+$lang['Base DN'] = 'Racine du serveur LDAP (e.g.: dc=example,dc=com):';
 
 // ldap attributes
@@ -31,4 +32,16 @@
 $lang['Base DN'] = 'Arbre ldap à explorer où rechercher les utilisateurs (ex : ou=users,dc=exemple,dc=com)';
 $lang['Attribute corresponding to the user name'] = 'Attribut correspondant au nom d\'utilisateur';
+
+//ldap users
+$lang['Ldap users'] = 'utilisateurs Ldap';
+$lang['Users branch'] = 'Branche où les utilisateurs LDAP peuvent être trouvés (e.g.: ou=users):';
+$lang['Attribute corresponding to the user name'] = 'Attribut correspondant au nom d\'utilisateur (e.g.: uid):';
+$lang['Search Ldap users ?'] = 'Faire une recherche sur le nom des utilisateurs ? Vous n\'avez pas besoin de cela si votre annuaire est assez simple (e.g.: uid=user,ou=people,dc=example,dc=com). Si vous n\'utilisez pas cette option, vous épargnez une requete Ldap.';
+
+//ldap groups
+$lang['Ldap groups'] = 'groupes Ldap';
+$lang['Groups branch'] = 'Branche où les groupes LDAP peuvent être trouvés (e.g.: ou=groups):';
+$lang['Attribute corresponding to the group name'] = 'Attribut correspondant au nom du groupe (e.g.: cn):';
+$lang['Search Ldap groups ?'] = 'Faire une recherche sur le nom des groupes ? Vous n\'avez pas besoin de cela si votre annuaire est assez simple (e.g.: cn=groupname,ou=groups,dc=example,dc=com). Si vous n\'utilisez pas cette option, vous épargnez une requete Ldap.';
 
 // ldap connection credentials
Index: /extensions/Ldap_Login/main.inc.php
===================================================================
--- /extensions/Ldap_Login/main.inc.php	(revision 28533)
+++ /extensions/Ldap_Login/main.inc.php	(revision 28534)
@@ -2,5 +2,5 @@
 /*
 Plugin Name: Ldap_Login
-Version: 1.1
+Version: 1.2
 Description: Allow piwigo authentication along an ldap
 Plugin URI: http://www.22decembre.eu/2014/02/09/piwigo-ldap-login-v1-1/
@@ -14,7 +14,7 @@
 // +-----------------------------------------------------------------------+
 define('LDAP_LOGIN_ID',      basename(dirname(__FILE__)));
-define('LDAP_LOGIN_PATH' ,   PHPWG_PLUGINS_PATH . LDAP_LOGIN_ID . '/');
+define('LDAP_LOGIN_PATH' ,   __DIR__ . '/');
 define('LDAP_LOGIN_ADMIN',   get_root_url() . 'admin.php?page=plugin-' . LDAP_LOGIN_ID);
-define('LDAP_LOGIN_VERSION', '1.1');
+define('LDAP_LOGIN_VERSION', '1.2');
 
 include_once(LDAP_LOGIN_PATH.'/class.ldap.php');
@@ -51,64 +51,119 @@
 function ld_init(){
 	load_language('plugin.lang', LDAP_LOGIN_PATH);
+	global $conf;
 }
 
+function fail($username) {
+	trigger_action('login_failure', stripslashes($username));
+	return false;
+}
+
+function update_user($username,$id) {
+	$up = new Ldap();
+	$up->load_config();
+	$up->ldap_conn() or error_log("Unable to connect LDAP server : ".$up->getErrorString());
+
+	// update user piwigo rights / access according to ldap. Only if it's webmaster / admin, so no normal !
+	if($up->ldap_status($username) !='normal') {
+		single_update(USER_INFOS_TABLE,array('status' => $up->ldap_status($username)),array('user_id' => $id));
+	}
+
+	// search groups
+	$group_query = 'SELECT name, id FROM '.GROUPS_TABLE.';';
+	
+	$result = pwg_query($group_query);
+	$inserts = array();
+	while ($row = pwg_db_fetch_assoc($result))
+	{
+		if($up->user_membership($username, $up->ldap_group($row['name']))) {
+			$inserts[] = array('user_id' => $id,'group_id' => $row['id']);
+		}
+	}
+
+	if (count($inserts) > 0)
+	{
+		mass_inserts(USER_GROUP_TABLE, array('user_id', 'group_id'), $inserts,array('ignore'=>true));
+	}
+}
 
 function login($success, $username, $password, $remember_me){
 
 	global $conf;
+	$allow_auth = False;
 	
 	$obj = new Ldap();
 	$obj->load_config();
-	$obj->ldap_conn() or die("Unable to connect LDAP server : ".$ldap->getErrorString());
+	$obj->ldap_conn() or error_log("Unable to connect LDAP server : ".$obj->getErrorString());
+	
+	// if there's a users group...
+	if ($obj->config['users_group']) {
+		// and the user is in
+		if ($obj->user_membership($username,$obj->ldap_group($obj->config['users_group']))) {
+			// it can continue
+			$allow_auth = True;
+		}
+		else
+		{	// otherwise it means the user is not allowed to enter !
+			fail($username);
+		}
+	}
+	else {
+	// if there's no user group, we can continue.
+	$allow_auth = True;
+	}
+	
+	if ($allow_auth) {
+		if ($obj->ldap_bind_as($username,$password)){ // bind with userdn
+			// search user in piwigo database
+			$query = '
+				SELECT	'.$conf['user_fields']['id'].' AS id
+				FROM '.USERS_TABLE.'
+				WHERE	'.$conf['user_fields']['username'].' = \''.pwg_db_real_escape_string($username).'\';';
+			$row = pwg_db_fetch_assoc(pwg_query($query));
 
-	if (!$obj->ldap_bind_as($username,$password)){ // bind with userdn
-		trigger_action('login_failure', stripslashes($username));
-		return false; // wrong password
+			// if query is not empty, it means everything is ok and we can continue, auth is done !
+			if (!empty($row['id'])) {
+				update_user($username,$row['id']);
+				
+				log_user($row['id'], $remember_me);
+				trigger_action('login_success', stripslashes($username));
+				
+				return True;
+			}
+  	
+			// if query is empty but ldap auth is done we can create a piwigo user if it's said so !
+			else {
+				// this is where we check we are allowed to create new users upon that.
+				if ($obj->config['allow_newusers']) {
+			
+					// we got the email address
+					if ($obj->ldap_mail($username)) {
+						$mail = $obj->ldap_mail($username);
+					}
+					else {
+						$mail = NULL;
+					}
+			
+					// we actually register the new user
+					$new_id = register_user($username,random_password(8),$mail);
+					update_user($username,$new_id);
+                        
+					// now we fetch again his id in the piwigo db, and we get them, as we just created him !
+					log_user($new_id, False);
+					
+					trigger_action('login_success', stripslashes($username));
+					
+					redirect('profile.php');
+					return true;
+				}
+				// else : this is the normal behavior ! user is not created.
+				else { fail($username); }
+			}
+		}
+		// ldap_bind_as was not successful
+		else { fail($username); }
 	}
-
-	// search user in piwigo database
-$query = 'SELECT '.$conf['user_fields']['id'].' AS id FROM '.USERS_TABLE.' WHERE '.$conf['user_fields']['username'].' = \''.pwg_db_real_escape_string($username).'\' ;';
-
-  $row = pwg_db_fetch_assoc(pwg_query($query));
-
-  // if query is not empty, it means everything is ok and we can continue, auth is done !
-  	if (!empty($row['id'])) {
-  		log_user($row['id'], $remember_me);
-  		trigger_action('login_success', stripslashes($username));
-  		return true;
-  	}
-  	
-  	// if query is empty but ldap auth is done we can create a piwigo user if it's said so !
-  	else {
-		// this is where we check we are allowed to create new users upon that.
-		if ($obj->config['allow_newusers']) {
-			
-			// we got the email address
-			if ($obj->ldap_mail($username)) {
-				$mail = $obj->ldap_mail($username);
-			}
-			else {
-				$mail = NULL;
-			}
-			
-			// we actually register the new user
-			$new_id = register_user($username,random_password(8),$mail);
-                        
-			// now we fetch again his id in the piwigo db, and we get them, as we just created him !
-			//$query = 'SELECT '.$conf['user_fields']['id'].' AS id FROM '.USERS_TABLE.' WHERE '.$conf['user_fields']['username'].' = \''.pwg_db_real_escape_string($username).'\' ;';
-			//$row = pwg_db_fetch_assoc(pwg_query($query));
-
-			log_user($new_id, False);
-			trigger_action('login_success', stripslashes($username));
-			redirect('profile.php');
-			return true;
-		}
-		// else : this is the normal behavior ! user is not created.
-		else {
-		trigger_action('login_failure', stripslashes($username));
-		return false;
-		}
-  	}
+	// user is not allowed to auth or auth is wrong !
+	else { fail($username); }
 }
-
 ?>
