Index: /extensions/Ldap_Login/TODO
===================================================================
--- /extensions/Ldap_Login/TODO	(revision 27035)
+++ /extensions/Ldap_Login/TODO	(revision 27036)
@@ -1,16 +1,30 @@
 TODO :
+auto config (may use ajax): fill in the settings, then the page guess the next settings.
+Ex : after filled the host address, the page guess the base dn. The last to guess is the users OU.
+	Users OU can come with a select field, as the ld_attr.
 
-Translate the whole plugin to english and furnish lang files or another way to make the plugin, at least bilingual.
-Create a "check" function to test the ldap auth before using it !
-Enable use of common auth along with ldap one, as, currently, they are not compatible.
-Enable use of other elements to auth (typically : mail) rather than just username.
-Create INSTALL file and procedure.
+correct init plugin
+if mail isn't furnished ?
+create common piwigo users upon successfull ldap connection when piwigo user doesn't exist => done !
+	Groups : users may belong to ldap group to allow connection
+	Groups : users belonging to «sudo» or «admin» ldap group become piwigo admin when created this way
+	fetching attributes from ldap (mail…).
+	
+config of the previous one (need tabs)
+config page to render better
 
-Choses à faire :
+########
 
-Alleger et verifier la pertinence du code.
-Traduire le plugin (code, commentaires du code, zone d'administration piwigo) et trouver un moyen pour que le plugin soit à minima bilingue.
-Créer une fonction de verification, pour tester que les paramètres ldap sont bons.
-Résoudre le conflit dans le code coeur de piwigo et du plugin pour l'utilisation de l'authentification de base et ldap.
-Permettre l'authentification avec autre chose qu'un nom d'utilisateur (typiquement : mail).
-Créer un fichier d'installation.
+à faire :
+initialisation du plugin correcte
+qu'est-ce qu'on fait si le mail est pas fourni ?
+configuration automatique (javascript/ajax probable): entrée des paramètres et la page recherche le paramètre suivant si possible.
+Ex : adresse du serveur -> la page trouve toute seule la racine ldap, reste plus que la OU des utilisateurs (qu'on peut selectionner via une liste déroulante).
+	l'attribut d'identification peut être selectionné par une liste déroulante.
+
+creation d'un utilisateur piwigo suite à une authentification ldap quand l'utilisateur n'existe pas. => fait !
+	question de groups : les utilisateurs membres du groupe ldap «sudo» ou autre pourraient automatiquement être admins piwigo
+	question de groupe : les utilisateurs devraient appartenir à un groupe ldap pour se connecter…
+	récuperer les attributs dans le ldap (mail…).
+	
+page de config à peaufiner, option précédente à intégrer dans un onglet.
Index: /extensions/Ldap_Login/admin.php
===================================================================
--- /extensions/Ldap_Login/admin.php	(revision 27036)
+++ /extensions/Ldap_Login/admin.php	(revision 27036)
@@ -0,0 +1,25 @@
+<?php
+defined('LDAP_LOGIN_PATH') or die('Hacking attempt!');
+ 
+global $template, $page, $conf;
+
+// get current tab
+$page['tab'] = (isset($_GET['tab'])) ? $_GET['tab'] : $page['tab'] = 'configuration';
+
+// tabsheet
+include_once(PHPWG_ROOT_PATH.'admin/include/tabsheet.class.php');
+$tabsheet = new tabsheet();
+$tabsheet->set_id('ldap_login');
+
+$tabsheet->add('configuration', l10n('Configuration'), LDAP_LOGIN_ADMIN . '-configuration');
+$tabsheet->add('newusers', l10n('New users when ldap auth is successfull'), LDAP_LOGIN_ADMIN . '-newusers');
+$tabsheet->select($page['tab']);
+$tabsheet->assign();
+  
+// include page
+include(LDAP_LOGIN_PATH . 'admin/' . $page['tab'] . '.php');
+
+// template vars
+$template->assign('LDAP_LOGIN_PATH', get_root_url() . LDAP_LOGIN_PATH );
+  
+?>
Index: /extensions/Ldap_Login/admin/configuration.php
===================================================================
--- /extensions/Ldap_Login/admin/configuration.php	(revision 27036)
+++ /extensions/Ldap_Login/admin/configuration.php	(revision 27036)
@@ -0,0 +1,58 @@
+<?php
+if (!defined('PHPWG_ROOT_PATH')) die('Hacking attempt!');
+
+global $template;
+$template->set_filenames( array('plugin_admin_content' => dirname(__FILE__).'/configuration.tpl') );
+$template->assign(
+  array(
+    'PLUGIN_ACTION' => get_root_url().'admin.php?page=plugin-ldap_login-configuration',
+    'PLUGIN_CHECK' => get_root_url().'admin.php?page=plugin-ldap_login-configuration',
+    ));
+
+$me = new Ldap();
+$me->load_config();
+//$me = get_plugin_data($plugin_id);
+
+$template->assign('HOST', 	$me->config['host']);
+$template->assign('BASEDN',	$me->config['basedn']); // racine !
+$template->assign('PORT', 	$me->config['port']);
+$template->assign('LD_ATTR',	$me->config['ld_attr']);
+$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']);
+
+if (isset($_POST['save'])){
+	$me->config['host'] 	 = $_POST['HOST'];
+	$me->config['basedn']    = $_POST['BASEDN'];
+	$me->config['port']      = $_POST['PORT'];
+	$me->config['ld_attr']   = $_POST['LD_ATTR'];
+	$me->config['ld_binddn'] = $_POST['LD_BINDDN'];
+	$me->config['ld_bindpw'] = $_POST['LD_BINDPW'];
+
+	if (isset($_POST['LD_USE_SSL'])){
+		$me->config['ld_use_ssl'] = True;
+	} else {
+		$me->config['ld_use_ssl'] = False;
+	}
+}
+
+// Save LDAP configuration
+if (isset($_POST['save'])){
+	$me->save_config();
+}
+
+// Check LDAP configuration
+if (isset($_POST['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>');
+	}
+	else {
+	$template->assign('LD_CHECK_LDAP','<p style="color:red;">Error :'.$error.' test '.$me->config['uri'].' '.$check.'</p>');
+	}
+}
+
+$template->assign_var_from_handle( 'ADMIN_CONTENT', 'plugin_admin_content');
+?>
Index: /extensions/Ldap_Login/admin/configuration.tpl
===================================================================
--- /extensions/Ldap_Login/admin/configuration.tpl	(revision 27036)
+++ /extensions/Ldap_Login/admin/configuration.tpl	(revision 27036)
@@ -0,0 +1,109 @@
+<h2>{'Ldap_Login Plugin'|@translate}</h2>
+
+<div id="configContent">
+
+<p>{'All LDAP users can use their ldap password everywhere on piwigo if needed.'|@translate}</p>
+
+<form method="post" action="{$PLUGIN_ACTION}" class="general">
+
+	{if (!extension_loaded('ldap'))}
+		<p style="color:red;">{'Warning: LDAP Extension missing.'|@translate}</p>
+		<br />
+	{/if}
+	
+	<fieldset class="mainConf">
+	<legend>{'Ldap server host connection'|@translate}</legend>
+	
+	<ul>
+		<li>
+			<label for="host">{'Ldap server host'|@translate}</label>
+			<br>
+			<input size="70" type="text" id="host" name="HOST" value="{$HOST}" />
+		</li>
+	
+		<li>
+			<label for="ld_use_ssl">
+			{if $LD_USE_SSL }
+				<input type="checkbox" id="ld_use_ssl" name="LD_USE_SSL" value="{$LD_USE_SSL}" checked />
+			{else}
+				<input type="checkbox" id="ld_use_ssl" name="LD_USE_SSL" value="{$LD_USE_SSL}" />
+			{/if}
+			{'Secure connexion'|@translate}</label>
+		</li>
+	
+		<li>
+			<label for="port">{'Ldap port'|@translate}</label>
+			<br>
+			<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>
+			<br>
+			<input size="70" type="text" id="basedn" name="BASEDN" value="{$BASEDN}" />
+		</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 connection credentials'|@translate}</legend>
+	<ul>
+		<li>
+			<label for="ld_binddn">{'Bind DN, field in full ldap style'|@translate}</label>
+			<br>
+			<input size="70" type="text" id="ld_binddn" name="LD_BINDDN" value="{$LD_BINDDN}" />
+		</li>
+		
+		<li>
+			<label for="ld_bindpw">{'Bind password'|@translate}</label>
+			<br>
+			<input type="password" id="ld_bindpw" name="LD_BINDPW" />
+		</li>
+	</ul>
+	<i>{'Let the fields blank if the ldap accept anonymous connections.'|@translate}</i>
+</fieldset>
+ 
+<p>
+<input type="submit" value="{'Save'|@translate}" name="save" />
+</p>
+</form>
+
+<form method="post" action="{$PLUGIN_CHECK}" class="general">
+<fieldset class="mainConf">
+<legend>{'Ldap_Login Test'|@translate}</legend>
+<i>{'You must save the settings with the Save button just up there before testing here.'|@translate}</i>
+	<ul>
+		<li>
+			<label for="username">{'Username'|@translate}</label>
+			<br>
+			<input type="text" id="username" name="USERNAME" value="{$USERNAME}" />
+		</li>
+		
+		<li>
+			<label for="ld_attr">{'Your password'|@translate}</label>
+			<br>
+			<input type="password" id="password" name="PASSWORD" value="{$PASSWORD}" />
+		</li>
+	</ul>
+	
+	{if (!empty($LD_CHECK_LDAP))}
+ 		{$LD_CHECK_LDAP}
+	{/if}
+
+</fieldset>
+<p><input type="submit" value="{'Test Settings'|@translate}" name="check_ldap" /></p>
+
+</form>
+</div>
Index: /extensions/Ldap_Login/admin/index.php
===================================================================
--- /extensions/Ldap_Login/admin/index.php	(revision 27036)
+++ /extensions/Ldap_Login/admin/index.php	(revision 27036)
@@ -0,0 +1,30 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | Piwigo - a PHP based photo gallery                                    |
+// +-----------------------------------------------------------------------+
+// | Copyright(C) 2008-2013 Piwigo Team                  http://piwigo.org |
+// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
+// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+// Recursive call
+$url = '../';
+header( 'Request-URI: '.$url );
+header( 'Content-Location: '.$url );
+header( 'Location: '.$url );
+exit();
+?>
Index: /extensions/Ldap_Login/admin/newusers.php
===================================================================
--- /extensions/Ldap_Login/admin/newusers.php	(revision 27036)
+++ /extensions/Ldap_Login/admin/newusers.php	(revision 27036)
@@ -0,0 +1,52 @@
+<?php
+if (!defined('PHPWG_ROOT_PATH')) die('Hacking attempt!');
+
+global $template;
+$template->set_filenames( array('plugin_admin_content' => dirname(__FILE__).'/newusers.tpl') );
+$template->assign(
+  array(
+    'PLUGIN_NEWUSERS' => get_root_url().'admin.php?page=plugin-ldap_login-newusers',
+    ));
+
+$me = new Ldap();
+$me->load_config();
+//$me = get_plugin_data($plugin_id);
+
+$template->assign('ALLOW_NEWUSERS',	$me->config['allow_newusers']);
+$template->assign('ADVERTISE_ADMINS',	$me->config['advertise_admin_new_ldapuser']);
+$template->assign('SEND_CASUAL_MAIL',	$me->config['send_password_by_mail_ldap']);
+
+if (isset($_POST['save'])){
+
+	if (isset($_POST['ALLOW_NEWUSERS'])){
+		$me->config['allow_newusers'] = True;
+	} else {
+		$me->config['allow_newusers'] = False;
+	}
+	
+	if (isset($_POST['ADVERTISE_ADMINS'])){
+		$me->config['advertise_admin_new_ldapuser'] = True;
+	} else {
+		$me->config['advertise_admin_new_ldapuser'] = False;
+	}
+	
+	if (isset($_POST['SEND_CASUAL_MAIL'])){
+		$me->config['send_password_by_mail_ldap'] = True;
+	} else {
+		$me->config['send_password_by_mail_ldap'] = False;
+	}
+}
+
+// Save LDAP configuration
+if (isset($_POST['save'])){
+	$me->save_config();
+}
+
+// do we allow to create new piwigo users in case of auth along the ldap ?
+// does he have to belong an ldap group ?
+// does ldap groups give some power ?
+// what do we do when there's no mail in the ldap ?
+// do we send mail to admins ?
+
+$template->assign_var_from_handle( 'ADMIN_CONTENT', 'plugin_admin_content');
+?>
Index: /extensions/Ldap_Login/admin/newusers.tpl
===================================================================
--- /extensions/Ldap_Login/admin/newusers.tpl	(revision 27036)
+++ /extensions/Ldap_Login/admin/newusers.tpl	(revision 27036)
@@ -0,0 +1,54 @@
+{literal}
+<style>
+label
+{
+    display: block;
+    width: 250px;
+    float: left;
+}
+</style>
+{/literal}
+
+<div class="titrePage">
+	<h2>{'Ldap_Login Plugin'|@translate}</h2>
+</div>
+
+<i>{"If the LDAP doesn't furnish the mail address, users can set it up in the profile page."|@translate}</i>
+<form method="post" action="{$PLUGIN_NEWUSERS}" class="general">
+
+<fieldset>
+	<legend>{'Ldap_Login configuration'|@translate}</legend>
+	
+    <p>
+	{if $ALLOW_NEWUSERS}
+		<input type="checkbox" id="allow_newusers" name="ALLOW_NEWUSERS" value="{$ALLOW_NEWUSERS}" checked />
+	{else}
+		<input type="checkbox" id="allow_newusers" name="ALLOW_NEWUSERS" value="{$ALLOW_NEWUSERS}" />
+	{/if}
+	{'Do you allow new piwigo users to be created when users authenticate succesfully on the ldap ?'|@translate}
+    </p>
+
+    <p>
+	{if $ADVERTISE_ADMINS}
+		<input type="checkbox" id="advertise_admin_new_ldapuser" name="ADVERTISE_ADMINS" value="{$ADVERTISE_ADMINS}" checked />
+	{else}
+		<input type="checkbox" id="advertise_admin_new_ldapuser" name="ADVERTISE_ADMINS" value="{$ADVERTISE_ADMINS}" />
+	{/if}
+	{'Do you want admins to be advertised by mail in case of new users creation upon ldap login ?'|@translate}
+    </p>
+    
+    <p>
+	{if $SEND_CASUAL_MAIL}
+		<input type="checkbox" id="send_password_by_mail_ldap" name="SEND_CASUAL_MAIL" value="{$SEND_CASUAL_MAIL}" checked />
+	{else}
+		<input type="checkbox" id="send_password_by_mail_ldap" name="SEND_CASUAL_MAIL" value="{$SEND_CASUAL_MAIL}" />
+	{/if}
+	{'Do you want to send mail to the new users, like casual piwigo users receive ?'|@translate}
+    </p>
+    
+</fieldset>
+ 
+<p>
+<input type="submit" value="{'Save'|@translate}" name="save" />
+</p>
+</form>
Index: /extensions/Ldap_Login/class.ldap.php
===================================================================
--- /extensions/Ldap_Login/class.ldap.php	(revision 27036)
+++ /extensions/Ldap_Login/class.ldap.php	(revision 27036)
@@ -0,0 +1,195 @@
+<?php
+class Ldap {
+
+	var $cnx;
+	var $config;
+
+	// for debug
+	public function write_log($message){
+		@file_put_contents('/var/log/ldap_login.log',$message."\n",FILE_APPEND);
+	}
+
+	/**
+	 * check ldap configuration
+	 *
+	 * Dans le cas ou l'acces au ldap est anonyme il faut impérativement faire une recherche
+	 * pour tester la connection.
+	 *
+	 * When OpenLDAP 2.x.x is used, ldap_connect() will always return a resource as it does not actually connect
+	 * but just initializes the connecting parameters. The actual connect happens with the next calls
+	 * to ldap_* funcs, usually with ldap_bind().
+	 */
+	public function check_ldap(){
+
+		if (!$this->ldap_conn()) {
+			return $this->getErrorString();
+		}
+
+		// test du compte root si renseigné
+		if (!empty($this->config['ld_binddn']) && !empty($this->config['ld_bindpw'])){ // if empty ld_binddn, anonymous search
+			// authentication with rootdn and rootpw for search
+			if (!$this->ldap_bind_as($this->config['ld_binddn'],$this->config['ld_bindpw'])){
+				return $this->getErrorString();
+			}
+		} else {
+			// sinon recherche du basedn (cf comportement ldap_connect avec OpenLDAP)
+			if (!$this->ldap_check_basedn()){ // search userdn
+				return $this->getErrorString();
+			}
+		}
+		return true;
+	}
+	
+	function load_config()
+	{
+		// init to defaults
+		$this->config['host'] = 'localhost';
+		$this->config['basedn'] = 'ou=people,dc=example,dc=com'; // racine !
+		$this->config['port'] = ''; // if port is empty, I count on the software to care of it !
+		$this->config['ld_attr'] = 'uid';
+		$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;
+		
+		echo $this->config['send_password_by_mail_ldap'];
+		// fetch the actual config
+		$x = @file_get_contents( LDAP_LOGIN_PATH.'data.dat' );
+		if ($x!==false)
+		{
+			$c = unserialize($x);
+			// do some more tests here
+			$this->config = $c;
+		}
+	}
+
+	function save_config()
+	{
+		$file = fopen( LDAP_LOGIN_PATH.'/data.dat', 'w' );
+		fwrite($file, serialize($this->config) );
+		fclose( $file );
+	}
+
+	function ldap_admin_menu($menu)
+	{
+		array_push($menu,
+		array(
+		'NAME' => 'Ldap Login',
+		'URL' => get_admin_plugin_menu_link(LDAP_LOGIN_PATH.'/admin.php') )
+		);
+		return $menu;
+	}
+
+	public function ldap_conn(){
+
+		if ($this->config['use_ssl'] == 1){
+			if (empty($this->config['port'])){
+				$this->config['uri'] = 'ldaps://'.$this->config['host'];
+			}
+			else {
+			$this->config['uri'] = 'ldaps://'.$this->config['host'].':'.$this->config['port'];
+			}
+		}
+		
+		// now, it's without ssl
+		else {
+			if (empty($this->config['port'])){
+				$this->config['uri'] = 'ldap://'.$this->config['host'];
+			}
+			else {
+				$this->config['uri'] = 'ldap://'.$this->config['host'].':'.$this->config['port'];
+			}
+		}
+
+		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;
+		}
+	}
+	}
+
+	// return ldap error
+	public function getErrorString(){
+		return ldap_err2str(ldap_errno($this->cnx));
+	}
+	
+	// return the name ldap understand
+	public function ldap_name($name){
+	return $this->config['ld_attr'].'='.$name.','.$this->config['basedn'];
+	}
+
+	// authentication
+	public function ldap_bind_as($user,$user_passwd){
+		if (@ldap_bind($this->cnx,$this->ldap_name($user),$user_passwd)){
+			return true;
+		}
+		return false;
+	}
+
+	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);
+		
+		if (!empty($entry[0]['mail'])) {
+			return $entry[0]['mail'][0];
+			}
+		return False;
+	}
+	
+	// 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() {
+	$search = @ldap_read($this->cnx, "cn=subschema", "(objectClass=*)", array('*', 'subschemasubentry'));
+	$entries = @ldap_get_entries($this->cnx, $search);
+	echo count($entries);
+	}
+	
+	public function getRootDse() {
+
+        $search = @ldap_read($this->cnx, NULL, 'objectClass=*', array("*", "+"));
+        $entries = @ldap_get_entries($this->cnx, $search);
+        return $entries[0];
+	}
+
+
+	public function ldap_check_basedn(){
+		if ($read = @ldap_read($this->cnx,$this->config['basedn'],'(objectClass=*)',array('dn'))){
+			$entry = @ldap_get_entries($this->cnx, $read);
+			if (!empty($entry[0]['dn'])) {
+				return true;
+			}
+		}
+		return false;
+	}
+
+}
+?>
Index: tensions/Ldap_Login/data.dat
===================================================================
--- /extensions/Ldap_Login/data.dat	(revision 27035)
+++ 	(revision )
@@ -1,1 +1,0 @@
-a:3:{s:4:"host";s:9:"localhost";s:6:"basedn";s:36:",ou=utilisateurs,dc=22decembre,dc=eu";s:4:"pref";s:4:"uid=";}
Index: tensions/Ldap_Login/functions_user.inc.php
===================================================================
--- /extensions/Ldap_Login/functions_user.inc.php	(revision 27035)
+++ 	(revision )
@@ -1,1497 +1,0 @@
-<?php
-// +-----------------------------------------------------------------------+
-// | Piwigo - a PHP based photo gallery                                    |
-// +-----------------------------------------------------------------------+
-// | Copyright(C) 2008-2012 Piwigo Team                  http://piwigo.org |
-// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
-// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
-// +-----------------------------------------------------------------------+
-// | This program is free software; you can redistribute it and/or modify  |
-// | it under the terms of the GNU General Public License as published by  |
-// | the Free Software Foundation                                          |
-// |                                                                       |
-// | This program is distributed in the hope that it will be useful, but   |
-// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
-// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
-// | General Public License for more details.                              |
-// |                                                                       |
-// | You should have received a copy of the GNU General Public License     |
-// | along with this program; if not, write to the Free Software           |
-// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
-// | USA.                                                                  |
-// +-----------------------------------------------------------------------+
-
-// validate_mail_address:
-//   o verifies whether the given mail address has the
-//     right format. ie someone@domain.com "someone" can contain ".", "-" or
-//     even "_". Exactly as "domain". The extension doesn't have to be
-//     "com". The mail address can also be empty.
-//   o check if address could be empty
-//   o check if address is not used by a other user
-// If the mail address doesn't correspond, an error message is returned.
-//
-function validate_mail_address($user_id, $mail_address)
-{
-  global $conf;
-
-  if (empty($mail_address) and
-      !($conf['obligatory_user_mail_address'] and
-      in_array(script_basename(), array('register', 'profile'))))
-  {
-    return '';
-  }
-
-  $atom   = '[-a-z0-9!#$%&\'*+\\/=?^_`{|}~]';   // before  arobase
-  $domain = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)'; // domain name
-  $regex = '/^' . $atom . '+' . '(\.' . $atom . '+)*' . '@' . '(' . $domain . '{1,63}\.)+' . $domain . '{2,63}$/i';
-
-  if ( !preg_match( $regex, $mail_address ) )
-  {
-    return l10n('mail address must be like xxx@yyy.eee (example : jack@altern.org)');
-  }
-
-  if (defined("PHPWG_INSTALLED") and !empty($mail_address))
-  {
-    $query = '
-select count(*)
-from '.USERS_TABLE.'
-where upper('.$conf['user_fields']['email'].') = upper(\''.$mail_address.'\')
-'.(is_numeric($user_id) ? 'and '.$conf['user_fields']['id'].' != \''.$user_id.'\'' : '').'
-;';
-    list($count) = pwg_db_fetch_row(pwg_query($query));
-    if ($count != 0)
-    {
-      return l10n('this email address is already in use');
-    }
-  }
-}
-
-// validate_login_case:
-//   o check if login is not used by a other user
-// If the login doesn't correspond, an error message is returned.
-//
-function validate_login_case($login)
-{
-  global $conf;
-
-  if (defined("PHPWG_INSTALLED"))
-  {
-    $query = "
-SELECT ".$conf['user_fields']['username']."
-FROM ".USERS_TABLE."
-WHERE LOWER(".stripslashes($conf['user_fields']['username']).") = '".strtolower($login)."'
-;";
-
-    $count = pwg_db_num_rows(pwg_query($query));
-
-    if ($count > 0)
-    {
-      return l10n('this login is already used');
-    }
-  }
-}
-/**
- * For test on username case sensitivity
- *
- * @param : $username typed in by user for identification
- *
- * @return : $username found in database
- *
- */
-function search_case_username($username)
-{
-  global $conf;
-
-  $username_lo = strtolower($username);
-
-  $SCU_users = array();
-
-  $q = pwg_query("
-    SELECT ".$conf['user_fields']['username']." AS username
-    FROM `".USERS_TABLE."`;
-  ");
-  while ($r = pwg_db_fetch_assoc($q))
-   $SCU_users[$r['username']] = strtolower($r['username']);
-   // $SCU_users is now an associative table where the key is the account as
-   // registered in the DB, and the value is this same account, in lower case
-
-  $users_found = array_keys($SCU_users, $username_lo);
-  // $users_found is now a table of which the values are all the accounts
-  // which can be written in lowercase the same way as $username
-  if (count($users_found) != 1) // If ambiguous, don't allow lowercase writing
-   return $username; // but normal writing will work
-  else
-   return $users_found[0];
-}
-function register_user($login, $password, $mail_address,
-  $with_notification = true, $errors = array())
-{
-  global $conf;
-
-  if ($login == '')
-  {
-    $errors[] = l10n('Please, enter a login');
-  }
-  if (preg_match('/^.* $/', $login))
-  {
-    $errors[] = l10n('login mustn\'t end with a space character');
-  }
-  if (preg_match('/^ .*$/', $login))
-  {
-    $errors[] = l10n('login mustn\'t start with a space character');
-  }
-  if (get_userid($login))
-  {
-    $errors[] = l10n('this login is already used');
-  }
-  if ($login != strip_tags($login))
-  {
-    $errors[] = l10n('html tags are not allowed in login');
-  }
-  $mail_error = validate_mail_address(null, $mail_address);
-  if ('' != $mail_error)
-  {
-    $errors[] = $mail_error;
-  }
-
-  if ($conf['insensitive_case_logon'] == true)
-  {
-    $login_error = validate_login_case($login);
-    if ($login_error != '')
-    {
-      $errors[] = $login_error;
-    }
-  }
-
-  $errors = trigger_event('register_user_check',
-              $errors,
-              array(
-                'username'=>$login,
-                'password'=>$password,
-                'email'=>$mail_address,
-              )
-            );
-
-  // if no error until here, registration of the user
-  if (count($errors) == 0)
-  {
-    // what will be the inserted id ?
-    $query = '
-SELECT MAX('.$conf['user_fields']['id'].') + 1
-  FROM '.USERS_TABLE.'
-;';
-    list($next_id) = pwg_db_fetch_row(pwg_query($query));
-
-    $insert =
-      array(
-        $conf['user_fields']['id'] => $next_id,
-        $conf['user_fields']['username'] => pwg_db_real_escape_string($login),
-        $conf['user_fields']['password'] => $conf['pass_convert']($password),
-        $conf['user_fields']['email'] => $mail_address
-        );
-
-    mass_inserts(USERS_TABLE, array_keys($insert), array($insert));
-
-    // Assign by default groups
-    {
-      $query = '
-SELECT id
-  FROM '.GROUPS_TABLE.'
-  WHERE is_default = \''.boolean_to_string(true).'\'
-  ORDER BY id ASC
-;';
-      $result = pwg_query($query);
-
-      $inserts = array();
-      while ($row = pwg_db_fetch_assoc($result))
-      {
-          $inserts[] = array(
-            'user_id' => $next_id,
-            'group_id' => $row['id']
-          );
-      }
-    }
-
-    if (count($inserts) != 0)
-    {
-      mass_inserts(USER_GROUP_TABLE, array('user_id', 'group_id'), $inserts);
-    }
-
-    $override = null;
-    if ($with_notification and $conf['browser_language'])
-    {
-      if ( !get_browser_language($override['language']) )
-        $override=null;
-    }
-    create_user_infos($next_id, $override);
-
-    if ($with_notification and $conf['email_admin_on_new_user'])
-    {
-      include_once(PHPWG_ROOT_PATH.'include/functions_mail.inc.php');
-      $admin_url = get_absolute_root_url()
-                   .'admin.php?page=user_list&username='.$login;
-
-      $keyargs_content = array
-      (
-        get_l10n_args('User: %s', stripslashes($login)),
-        get_l10n_args('Email: %s', $_POST['mail_address']),
-        get_l10n_args('', ''),
-        get_l10n_args('Admin: %s', $admin_url)
-      );
-
-      pwg_mail_notification_admins
-      (
-        get_l10n_args('Registration of %s', stripslashes($login)),
-        $keyargs_content
-      );
-    }
-
-    trigger_action('register_user',
-      array(
-        'id'=>$next_id,
-        'username'=>$login,
-        'email'=>$mail_address,
-       )
-      );
-  }
-
-  return $errors;
-}
-
-function build_user( $user_id, $use_cache )
-{
-  global $conf;
-
-  $user['id'] = $user_id;
-  $user = array_merge( $user, getuserdata($user_id, $use_cache) );
-
-  if ($user['id'] == $conf['guest_id'] and $user['status'] <> 'guest')
-  {
-    $user['status'] = 'guest';
-    $user['internal_status']['guest_must_be_guest'] = true;
-  }
-
-  // Check user theme
-  if (!isset($user['theme_name']))
-  {
-    $user['theme'] = get_default_theme();
-  }
-
-  return $user;
-}
-
-/**
- * find informations related to the user identifier
- *
- * @param int user identifier
- * @param boolean use_cache
- * @param array
- */
-function getuserdata($user_id, $use_cache)
-{
-  global $conf;
-
-  $userdata = array();
-
-  // retrieve basic user data
-  $query = '
-SELECT ';
-  $is_first = true;
-  foreach ($conf['user_fields'] as $pwgfield => $dbfield)
-  {
-    if ($is_first)
-    {
-      $is_first = false;
-    }
-    else
-    {
-      $query.= '
-     , ';
-    }
-    $query.= $dbfield.' AS '.$pwgfield;
-  }
-  $query.= '
-  FROM '.USERS_TABLE.'
-  WHERE '.$conf['user_fields']['id'].' = \''.$user_id.'\'';
-
-  $row = pwg_db_fetch_assoc(pwg_query($query));
-
-  // retrieve additional user data ?
-  if ($conf['external_authentification'])
-  {
-    $query = '
-SELECT
-    COUNT(1) AS counter
-  FROM '.USER_INFOS_TABLE.' AS ui
-    LEFT JOIN '.USER_CACHE_TABLE.' AS uc ON ui.user_id = uc.user_id
-    LEFT JOIN '.THEMES_TABLE.' AS t ON t.id = ui.theme
-  WHERE ui.user_id = '.$user_id.'
-  GROUP BY ui.user_id
-;';
-    list($counter) = pwg_db_fetch_row(pwg_query($query));
-    if ($counter != 1)
-    {
-      create_user_infos($user_id);
-    }
-  }
-
-  // retrieve user info
-  $query = '
-SELECT
-    ui.*,
-    uc.*,
-    t.name AS theme_name
-  FROM '.USER_INFOS_TABLE.' AS ui
-    LEFT JOIN '.USER_CACHE_TABLE.' AS uc ON ui.user_id = uc.user_id
-    LEFT JOIN '.THEMES_TABLE.' AS t ON t.id = ui.theme
-  WHERE ui.user_id = '.$user_id.'
-;';
-
-  $result = pwg_query($query);
-  $user_infos_row = pwg_db_fetch_assoc($result);
-
-  // then merge basic + additional user data
-  $row = array_merge($row, $user_infos_row);
-
-  foreach ($row as $key => $value)
-  {
-    if (!is_numeric($key))
-    {
-      // If the field is true or false, the variable is transformed into a
-      // boolean value.
-      if ($value == 'true' or $value == 'false')
-      {
-        $userdata[$key] = get_boolean($value);
-      }
-      else
-      {
-        $userdata[$key] = $value;
-      }
-    }
-  }
-
-  if ($use_cache)
-  {
-    if (!isset($userdata['need_update'])
-        or !is_bool($userdata['need_update'])
-        or $userdata['need_update'] == true)
-    {
-      $userdata['cache_update_time'] = time();
-
-      // Set need update are done
-      $userdata['need_update'] = false;
-
-      $userdata['forbidden_categories'] =
-        calculate_permissions($userdata['id'], $userdata['status']);
-
-      /* now we build the list of forbidden images (this list does not contain
-      images that are not in at least an authorized category)*/
-      $query = '
-SELECT DISTINCT(id)
-  FROM '.IMAGES_TABLE.' INNER JOIN '.IMAGE_CATEGORY_TABLE.' ON id=image_id
-  WHERE category_id NOT IN ('.$userdata['forbidden_categories'].')
-    AND level>'.$userdata['level'];
-      $forbidden_ids = array_from_query($query, 'id');
-
-      if ( empty($forbidden_ids) )
-      {
-        $forbidden_ids[] = 0;
-      }
-      $userdata['image_access_type'] = 'NOT IN'; //TODO maybe later
-      $userdata['image_access_list'] = implode(',',$forbidden_ids);
-
-
-      $query = '
-SELECT COUNT(DISTINCT(image_id)) as total
-  FROM '.IMAGE_CATEGORY_TABLE.'
-  WHERE category_id NOT IN ('.$userdata['forbidden_categories'].')
-    AND image_id '.$userdata['image_access_type'].' ('.$userdata['image_access_list'].')';
-      list($userdata['nb_total_images']) = pwg_db_fetch_row(pwg_query($query));
-
-
-      // now we update user cache categories
-      $user_cache_cats = get_computed_categories($userdata, null);
-      if ( !is_admin($userdata['status']) )
-      { // for non admins we forbid categories with no image (feature 1053)
-        $forbidden_ids = array();
-        foreach ($user_cache_cats as $cat)
-        {
-          if ($cat['count_images']==0)
-          {
-            $forbidden_ids[] = $cat['cat_id'];
-            unset( $user_cache_cats[$cat['cat_id']] );
-          }
-        }
-        if ( !empty($forbidden_ids) )
-        {
-          if ( empty($userdata['forbidden_categories']) )
-          {
-            $userdata['forbidden_categories'] = implode(',', $forbidden_ids);
-          }
-          else
-          {
-            $userdata['forbidden_categories'] .= ','.implode(',', $forbidden_ids);
-          }
-        }
-      }
-
-      // delete user cache
-      $query = '
-DELETE FROM '.USER_CACHE_CATEGORIES_TABLE.'
-  WHERE user_id = '.$userdata['id'];
-      pwg_query($query);
-
-      // Due to concurrency issues, we ask MySQL to ignore errors on
-      // insert. This may happen when cache needs refresh and that Piwigo is
-      // called "very simultaneously".
-      mass_inserts
-      (
-        USER_CACHE_CATEGORIES_TABLE,
-        array
-        (
-          'user_id', 'cat_id',
-          'date_last', 'max_date_last', 'nb_images', 'count_images', 'count_categories'
-        ),
-        $user_cache_cats,
-        array('ignore' => true)
-      );
-
-
-      // update user cache
-      $query = '
-DELETE FROM '.USER_CACHE_TABLE.'
-  WHERE user_id = '.$userdata['id'];
-      pwg_query($query);
-
-      // for the same reason as user_cache_categories, we ignore error on
-      // this insert
-      $query = '
-INSERT IGNORE INTO '.USER_CACHE_TABLE.'
-  (user_id, need_update, cache_update_time, forbidden_categories, nb_total_images,
-    image_access_type, image_access_list)
-  VALUES
-  ('.$userdata['id'].',\''.boolean_to_string($userdata['need_update']).'\','
-  .$userdata['cache_update_time'].',\''
-  .$userdata['forbidden_categories'].'\','.$userdata['nb_total_images'].',\''
-  .$userdata['image_access_type'].'\',\''.$userdata['image_access_list'].'\')';
-      pwg_query($query);
-    }
-  }
-
-  return $userdata;
-}
-
-/*
- * deletes favorites of the current user if he's not allowed to see them
- *
- * @return void
- */
-function check_user_favorites()
-{
-  global $user;
-
-  if ($user['forbidden_categories'] == '')
-  {
-    return;
-  }
-
-  // $filter['visible_categories'] and $filter['visible_images']
-  // must be not used because filter <> restriction
-  // retrieving images allowed : belonging to at least one authorized
-  // category
-  $query = '
-SELECT DISTINCT f.image_id
-  FROM '.FAVORITES_TABLE.' AS f INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic
-    ON f.image_id = ic.image_id
-  WHERE f.user_id = '.$user['id'].'
-'.get_sql_condition_FandF
-  (
-    array
-      (
-        'forbidden_categories' => 'ic.category_id',
-      ),
-    'AND'
-  ).'
-;';
-  $authorizeds = array_from_query($query, 'image_id');
-
-  $query = '
-SELECT image_id
-  FROM '.FAVORITES_TABLE.'
-  WHERE user_id = '.$user['id'].'
-;';
-  $favorites = array_from_query($query, 'image_id');
-
-  $to_deletes = array_diff($favorites, $authorizeds);
-  if (count($to_deletes) > 0)
-  {
-    $query = '
-DELETE FROM '.FAVORITES_TABLE.'
-  WHERE image_id IN ('.implode(',', $to_deletes).')
-    AND user_id = '.$user['id'].'
-;';
-    pwg_query($query);
-  }
-}
-
-/**
- * calculates the list of forbidden categories for a given user
- *
- * Calculation is based on private categories minus categories authorized to
- * the groups the user belongs to minus the categories directly authorized
- * to the user. The list contains at least -1 to be compliant with queries
- * such as "WHERE category_id NOT IN ($forbidden_categories)"
- *
- * @param int user_id
- * @param string user_status
- * @return string forbidden_categories
- */
-function calculate_permissions($user_id, $user_status)
-{
-  $query = '
-SELECT id
-  FROM '.CATEGORIES_TABLE.'
-  WHERE status = \'private\'
-;';
-  $private_array = array_from_query($query, 'id');
-
-  // retrieve category ids directly authorized to the user
-  $query = '
-SELECT cat_id
-  FROM '.USER_ACCESS_TABLE.'
-  WHERE user_id = '.$user_id.'
-;';
-  $authorized_array = array_from_query($query, 'cat_id');
-
-  // retrieve category ids authorized to the groups the user belongs to
-  $query = '
-SELECT cat_id
-  FROM '.USER_GROUP_TABLE.' AS ug INNER JOIN '.GROUP_ACCESS_TABLE.' AS ga
-    ON ug.group_id = ga.group_id
-  WHERE ug.user_id = '.$user_id.'
-;';
-  $authorized_array =
-    array_merge(
-      $authorized_array,
-      array_from_query($query, 'cat_id')
-      );
-
-  // uniquify ids : some private categories might be authorized for the
-  // groups and for the user
-  $authorized_array = array_unique($authorized_array);
-
-  // only unauthorized private categories are forbidden
-  $forbidden_array = array_diff($private_array, $authorized_array);
-
-  // if user is not an admin, locked categories are forbidden
-  if (!is_admin($user_status))
-  {
-    $query = '
-SELECT id
-  FROM '.CATEGORIES_TABLE.'
-  WHERE visible = \'false\'
-;';
-    $result = pwg_query($query);
-    while ($row = pwg_db_fetch_assoc($result))
-    {
-      $forbidden_array[] = $row['id'];
-    }
-    $forbidden_array = array_unique($forbidden_array);
-  }
-
-  if ( empty($forbidden_array) )
-  {// at least, the list contains 0 value. This category does not exists so
-   // where clauses such as "WHERE category_id NOT IN(0)" will always be
-   // true.
-    $forbidden_array[] = 0;
-  }
-
-  return implode(',', $forbidden_array);
-}
-
-/**
- * compute data of categories branches (one branch only)
- */
-function compute_branch_cat_data(&$cats, &$list_cat_id, &$level, &$ref_level)
-{
-  $date = '';
-  $count_images = 0;
-  $count_categories = 0;
-  do
-  {
-    $cat_id = array_pop($list_cat_id);
-    if (!is_null($cat_id))
-    {
-      // Count images and categories
-      $cats[$cat_id]['count_images'] += $count_images;
-      $cats[$cat_id]['count_categories'] += $count_categories;
-      $count_images = $cats[$cat_id]['count_images'];
-      $count_categories = $cats[$cat_id]['count_categories'] + 1;
-
-      if ((empty($cats[$cat_id]['max_date_last'])) or ($cats[$cat_id]['max_date_last'] < $date))
-      {
-        $cats[$cat_id]['max_date_last'] = $date;
-      }
-      else
-      {
-        $date = $cats[$cat_id]['max_date_last'];
-      }
-      $ref_level = substr_count($cats[$cat_id]['global_rank'], '.') + 1;
-    }
-    else
-    {
-      $ref_level = 0;
-    }
-  } while ($level <= $ref_level);
-
-  // Last cat updating must be added to list for next branch
-  if ($ref_level <> 0)
-  {
-    array_push($list_cat_id, $cat_id);
-  }
-}
-
-/**
- * compute data of categories branches
- */
-function compute_categories_data(&$cats)
-{
-  $ref_level = 0;
-  $level = 0;
-  $list_cat_id = array();
-
-  foreach ($cats as $id => $category)
-  {
-    // Compute
-    $level = substr_count($category['global_rank'], '.') + 1;
-    if ($level > $ref_level)
-    {
-      array_push($list_cat_id, $id);
-    }
-    else
-    {
-      compute_branch_cat_data($cats, $list_cat_id, $level, $ref_level);
-      array_push($list_cat_id, $id);
-    }
-    $ref_level = $level;
-  }
-
-  $level = 1;
-  compute_branch_cat_data($cats, $list_cat_id, $level, $ref_level);
-}
-
-/**
- * get computed array of categories
- *
- * @param array userdata
- * @param int filter_days number of recent days to filter on or null
- * @return array
- */
-function get_computed_categories($userdata, $filter_days=null)
-{
-  $query = 'SELECT c.id AS cat_id, global_rank';
-  // Count by date_available to avoid count null
-  $query .= ',
-  MAX(date_available) AS date_last, COUNT(date_available) AS nb_images
-FROM '.CATEGORIES_TABLE.' as c
-  LEFT JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON ic.category_id = c.id
-  LEFT JOIN '.IMAGES_TABLE.' AS i
-    ON ic.image_id = i.id
-      AND i.level<='.$userdata['level'];
-
-  if ( isset($filter_days) )
-  {
-    $query .= ' AND i.date_available > '.pwg_db_get_recent_period_expression($filter_days);
-  }
-
-  if ( !empty($userdata['forbidden_categories']) )
-  {
-    $query.= '
-  WHERE c.id NOT IN ('.$userdata['forbidden_categories'].')';
-  }
-
-  $query.= '
-  GROUP BY c.id, c.global_rank';
-
-  $result = pwg_query($query);
-
-  $cats = array();
-  while ($row = pwg_db_fetch_assoc($result))
-  {
-    $row['user_id'] = $userdata['id'];
-    $row['count_categories'] = 0;
-    $row['count_images'] = (int)$row['nb_images'];
-    $row['max_date_last'] = $row['date_last'];
-
-    $cats += array($row['cat_id'] => $row);
-  }
-  uasort($cats, 'global_rank_compare');
-
-  compute_categories_data($cats);
-
-  if ( isset($filter_days) )
-  {
-    $cat_tmp = $cats;
-    $cats = array();
-
-    foreach ($cat_tmp as $category)
-    {
-      if (!empty($category['max_date_last']))
-      {
-        // Re-init counters
-        $category['count_categories'] = 0;
-        $category['count_images'] = (int)$category['nb_images'];
-        // Keep category
-        $cats[$category['cat_id']] = $category;
-      }
-    }
-    // Compute a second time
-    compute_categories_data($cats);
-  }
-  return $cats;
-}
-
-/**
- * returns user identifier thanks to his name, false if not found
- *
- * @param string username
- * @param int user identifier
- */
-function get_userid($username)
-{
-  global $conf;
-
-  $username = pwg_db_real_escape_string($username);
-
-  $query = '
-SELECT '.$conf['user_fields']['id'].'
-  FROM '.USERS_TABLE.'
-  WHERE '.$conf['user_fields']['username'].' = \''.$username.'\'
-;';
-  $result = pwg_query($query);
-
-  if (pwg_db_num_rows($result) == 0)
-  {
-    return false;
-  }
-  else
-  {
-    list($user_id) = pwg_db_fetch_row($result);
-    return $user_id;
-  }
-}
-
-function get_userid_by_email($email)
-{
-  global $conf;
-
-  $email = pwg_db_real_escape_string($email);
-
-  $query = '
-SELECT
-    '.$conf['user_fields']['id'].'
-  FROM '.USERS_TABLE.'
-  WHERE UPPER('.$conf['user_fields']['email'].') = UPPER(\''.$email.'\')
-;';
-  $result = pwg_query($query);
-
-  if (pwg_db_num_rows($result) == 0)
-  {
-    return false;
-  }
-  else
-  {
-    list($user_id) = pwg_db_fetch_row($result);
-    return $user_id;
-  }
-}
-
-/*
- * Returns a array with default user value
- *
- * @param convert_str allows to convert string value if necessary
- */
-function get_default_user_info($convert_str = true)
-{
-  global $cache, $conf;
-
-  if (!isset($cache['default_user']))
-  {
-    $query = 'SELECT * FROM '.USER_INFOS_TABLE.
-            ' WHERE user_id = '.$conf['default_user_id'].';';
-
-    $result = pwg_query($query);
-    $cache['default_user'] = pwg_db_fetch_assoc($result);
-
-    if ($cache['default_user'] !== false)
-    {
-      unset($cache['default_user']['user_id']);
-      unset($cache['default_user']['status']);
-      unset($cache['default_user']['registration_date']);
-    }
-  }
-
-  if (is_array($cache['default_user']) and $convert_str)
-  {
-    $default_user = array();
-    foreach ($cache['default_user'] as $name => $value)
-    {
-      // If the field is true or false, the variable is transformed into a
-      // boolean value.
-      if ($value == 'true' or $value == 'false')
-      {
-        $default_user[$name] = get_boolean($value);
-      }
-      else
-      {
-        $default_user[$name] = $value;
-      }
-    }
-    return $default_user;
-  }
-  else
-  {
-    return $cache['default_user'];
-  }
-}
-
-/*
- * Returns a default user value
- *
- * @param value_name: name of value
- * @param sos_value: value used if don't exist value
- */
-function get_default_user_value($value_name, $sos_value)
-{
-  $default_user = get_default_user_info(true);
-  if ($default_user === false or empty($default_user[$value_name]))
-  {
-    return $sos_value;
-  }
-  else
-  {
-   return $default_user[$value_name];
-  }
-}
-
-/*
- * Returns the default template value
- *
- */
-function get_default_theme()
-{
-  $theme = get_default_user_value('theme', PHPWG_DEFAULT_TEMPLATE);
-  if (check_theme_installed($theme))
-  {
-    return $theme;
-  }
-
-  // let's find the first available theme
-  $active_themes = get_pwg_themes();
-  foreach (array_keys(get_pwg_themes()) as $theme_id)
-  {
-    return $theme_id;
-  }
-}
-
-/*
- * Returns the default language value
- *
- */
-function get_default_language()
-{
-  return get_default_user_value('language', PHPWG_DEFAULT_LANGUAGE);
-}
-
-/**
-  * Returns true if the browser language value is set into param $lang
-  *
-  */
-function get_browser_language(&$lang)
-{
-  $browser_language = substr(@$_SERVER["HTTP_ACCEPT_LANGUAGE"], 0, 2);
-  foreach (get_languages() as $language_code => $language_name)
-  {
-    if (substr($language_code, 0, 2) == $browser_language)
-    {
-      $lang = $language_code;
-      return true;
-    }
-  }
-  return false;
-}
-
-/**
- * add user informations based on default values
- *
- * @param int user_id / array of user_if
- * @param array of values used to override default user values
- */
-function create_user_infos($arg_id, $override_values = null)
-{
-  global $conf;
-
-  if (is_array($arg_id))
-  {
-    $user_ids = $arg_id;
-  }
-  else
-  {
-    $user_ids = array();
-    if (is_numeric($arg_id))
-    {
-      $user_ids[] = $arg_id;
-    }
-  }
-
-  if (!empty($user_ids))
-  {
-    $inserts = array();
-    list($dbnow) = pwg_db_fetch_row(pwg_query('SELECT NOW();'));
-
-    $default_user = get_default_user_info(false);
-    if ($default_user === false)
-    {
-      // Default on structure are used
-      $default_user = array();
-    }
-
-    if (!is_null($override_values))
-    {
-      $default_user = array_merge($default_user, $override_values);
-    }
-
-    foreach ($user_ids as $user_id)
-    {
-      $level= isset($default_user['level']) ? $default_user['level'] : 0;
-      if ($user_id == $conf['webmaster_id'])
-      {
-        $status = 'webmaster';
-        $level = max( $conf['available_permission_levels'] );
-      }
-      else if (($user_id == $conf['guest_id']) or
-               ($user_id == $conf['default_user_id']))
-      {
-        $status = 'guest';
-      }
-      else
-      {
-        $status = 'normal';
-      }
-
-      $insert = array_merge(
-        $default_user,
-        array(
-          'user_id' => $user_id,
-          'status' => $status,
-          'registration_date' => $dbnow,
-          'level' => $level
-          ));
-
-      array_push($inserts, $insert);
-    }
-
-    mass_inserts(USER_INFOS_TABLE, array_keys($inserts[0]), $inserts);
-  }
-}
-
-/**
- * returns the auto login key or false on error
- * @param int user_id
- * @param time_t time
- * @param string [out] username
-*/
-function calculate_auto_login_key($user_id, $time, &$username)
-{
-  global $conf;
-  $query = '
-SELECT '.$conf['user_fields']['username'].' AS username
-  , '.$conf['user_fields']['password'].' AS password
-FROM '.USERS_TABLE.'
-WHERE '.$conf['user_fields']['id'].' = '.$user_id;
-  $result = pwg_query($query);
-  if (pwg_db_num_rows($result) > 0)
-  {
-    $row = pwg_db_fetch_assoc($result);
-    $username = stripslashes($row['username']);
-    $data = $time.$user_id.$username;
-    $key = base64_encode( hash_hmac('sha1', $data, $conf['secret_key'].$row['password'],true) );
-    return $key;
-  }
-  return false;
-}
-
-/*
- * Performs all required actions for user login
- * @param int user_id
- * @param bool remember_me
- * @return void
-*/
-function log_user($user_id, $remember_me)
-{
-  global $conf, $user;
-
-  if ($remember_me and $conf['authorize_remembering'])
-  {
-    $now = time();
-    $key = calculate_auto_login_key($user_id, $now, $username);
-    if ($key!==false)
-    {
-      $cookie = $user_id.'-'.$now.'-'.$key;
-      if (version_compare(PHP_VERSION, '5.2', '>=') )
-      {
-        setcookie($conf['remember_me_name'],
-            $cookie,
-            time()+$conf['remember_me_length'],
-            cookie_path(),ini_get('session.cookie_domain'),ini_get('session.cookie_secure'),
-            ini_get('session.cookie_httponly')
-          );
-      }
-      else
-      {
-        setcookie($conf['remember_me_name'],
-            $cookie,
-            time()+$conf['remember_me_length'],
-            cookie_path(),ini_get('session.cookie_domain'),ini_get('session.cookie_secure')
-          );
-      }
-    }
-  }
-  else
-  { // make sure we clean any remember me ...
-    setcookie($conf['remember_me_name'], '', 0, cookie_path(),ini_get('session.cookie_domain'));
-  }
-  if ( session_id()!="" )
-  { // we regenerate the session for security reasons
-    // see http://www.acros.si/papers/session_fixation.pdf
-    session_regenerate_id(true);
-  }
-  else
-  {
-    session_start();
-  }
-  $_SESSION['pwg_uid'] = (int)$user_id;
-
-  $user['id'] = $_SESSION['pwg_uid'];
-}
-
-/*
- * Performs auto-connexion when cookie remember_me exists
- * @return true/false
-*/
-function auto_login() {
-  global $conf;
-
-  if ( isset( $_COOKIE[$conf['remember_me_name']] ) )
-  {
-    $cookie = explode('-', stripslashes($_COOKIE[$conf['remember_me_name']]));
-    if ( count($cookie)===3
-        and is_numeric(@$cookie[0]) /*user id*/
-        and is_numeric(@$cookie[1]) /*time*/
-        and time()-$conf['remember_me_length']<=@$cookie[1]
-        and time()>=@$cookie[1] /*cookie generated in the past*/ )
-    {
-      $key = calculate_auto_login_key( $cookie[0], $cookie[1], $username );
-      if ($key!==false and $key===$cookie[2])
-      {
-        log_user($cookie[0], true);
-        trigger_action('login_success', stripslashes($username));
-        return true;
-      }
-    }
-    setcookie($conf['remember_me_name'], '', 0, cookie_path(),ini_get('session.cookie_domain'));
-  }
-  return false;
-}
-
-/**
- * Tries to login a user given username and password (must be MySql escaped)
- * return true on success
- */
-function try_log_user($username, $password, $remember_me)
-{
- return trigger_event('try_login', $username, $password, $remember_me, false);
-}
-
-include_once(PHPWG_ROOT_PATH.'include/functions_plugins.inc.php');
-
-#add_event_handler('try_login', 'common_login', 0, 4);
-#add_event_handler('try_login', 'common_login', EVENT_HANDLER_PRIORITY_NEUTRAL, 4);
-
-function common_login($username, $password, $remember_me, $success)
-{
-  if ($success)
-  {
-    return true;
-  }
-  
-  // we force the session table to be clean
-  pwg_session_gc();
-
-  global $conf;
-  // retrieving the encrypted password of the login submitted
-  $query = '
-SELECT '.$conf['user_fields']['id'].' AS id,
-       '.$conf['user_fields']['password'].' AS password
-  FROM '.USERS_TABLE.'
-  WHERE '.$conf['user_fields']['username'].' = \''.pwg_db_real_escape_string($username).'\'
-;';
-  $row = pwg_db_fetch_assoc(pwg_query($query));
-  if ($row['password'] == $conf['pass_convert']($password))
-  {
-    log_user($row['id'], $remember_me);
-    trigger_action('login_success', stripslashes($username));
-    return true;
-  }
-  trigger_action('login_failure', stripslashes($username));
-  return false;
-}
-
-/** Performs all the cleanup on user logout */
-function logout_user()
-{
-  global $conf;
-  $_SESSION = array();
-  session_unset();
-  session_destroy();
-  setcookie(session_name(),'',0,
-      ini_get('session.cookie_path'),
-      ini_get('session.cookie_domain')
-    );
-  setcookie($conf['remember_me_name'], '', 0, cookie_path(),ini_get('session.cookie_domain'));
-}
-
-/*
- * Return user status used in this library
- * @return string
-*/
-function get_user_status($user_status)
-{
-  global $user;
-
-  if (empty($user_status))
-  {
-    if (isset($user['status']))
-    {
-      $user_status = $user['status'];
-    }
-    else
-    {
-      // swicth to default value
-      $user_status = '';
-    }
-  }
-  return $user_status;
-}
-
-/*
- * Return access_type definition of user
- * Test does with user status
- * @return bool
-*/
-function get_access_type_status($user_status='')
-{
-  global $conf;
-
-  switch (get_user_status($user_status))
-  {
-    case 'guest':
-    {
-      $access_type_status =
-        ($conf['guest_access'] ? ACCESS_GUEST : ACCESS_FREE);
-      break;
-    }
-    case 'generic':
-    {
-      $access_type_status = ACCESS_GUEST;
-      break;
-    }
-    case 'normal':
-    {
-      $access_type_status = ACCESS_CLASSIC;
-      break;
-    }
-    case 'admin':
-    {
-      $access_type_status = ACCESS_ADMINISTRATOR;
-      break;
-    }
-    case 'webmaster':
-    {
-      $access_type_status = ACCESS_WEBMASTER;
-      break;
-    }
-    default:
-    {
-      $access_type_status = ACCESS_FREE;
-      break;
-    }
-  }
-
-  return $access_type_status;
-}
-
-/*
- * Return if user have access to access_type definition
- * Test does with user status
- * @return bool
-*/
-function is_autorize_status($access_type, $user_status = '')
-{
-  return (get_access_type_status($user_status) >= $access_type);
-}
-
-/*
- * Check if user have access to access_type definition
- * Stop action if there are not access
- * Test does with user status
- * @return none
-*/
-function check_status($access_type, $user_status = '')
-{
-  if (!is_autorize_status($access_type, $user_status))
-  {
-    access_denied();
-  }
-}
-
-/*
- * Return if user is generic
- * @return bool
-*/
- function is_generic($user_status = '')
-{
-  return get_user_status($user_status) == 'generic';
-}
-
-/*
- * Return if user is only a guest
- * @return bool
-*/
- function is_a_guest($user_status = '')
-{
-  return get_user_status($user_status) == 'guest';
-}
-
-/*
- * Return if user is, at least, a classic user
- * @return bool
-*/
- function is_classic_user($user_status = '')
-{
-  return is_autorize_status(ACCESS_CLASSIC, $user_status);
-}
-
-/*
- * Return if user is, at least, an administrator
- * @return bool
-*/
- function is_admin($user_status = '')
-{
-  return is_autorize_status(ACCESS_ADMINISTRATOR, $user_status);
-}
-
-/*
- * Return if user is, at least, a webmaster
- * @return bool
-*/
- function is_webmaster($user_status = '')
-{
-  return is_autorize_status(ACCESS_WEBMASTER, $user_status);
-}
-
-/*
- * Adviser status is depreciated from piwigo 2.2
- * @return false
-*/
-function is_adviser()
-{
-  // TODO for Piwigo 2.4 : trigger a warning. We don't do it on Piwigo 2.3
-  // to avoid changes for plugin contributors
-  // trigger_error('call to obsolete function is_adviser', E_USER_WARNING);
-  return false;
-}
-
-/*
- * Return if current user can edit/delete/validate a comment
- * @param action edit/delete/validate
- * @return bool
- */
-function can_manage_comment($action, $comment_author_id)
-{
-  global $user, $conf;
-
-  if (is_a_guest())
-  {
-    return false;
-  }
-
-  if (!in_array($action, array('delete','edit', 'validate')))
-  {
-    return false;
-  }
-
-  if (is_admin())
-  {
-    return true;
-  }
-
-  if ('edit' == $action and $conf['user_can_edit_comment'])
-  {
-    if ($comment_author_id == $user['id']) {
-      return true;
-    }
-  }
-
-  if ('delete' == $action and $conf['user_can_delete_comment'])
-  {
-    if ($comment_author_id == $user['id']) {
-      return true;
-    }
-  }
-
-  return false;
-}
-
-/*
- * Return mail address as display text
- * @return string
-*/
-function get_email_address_as_display_text($email_address)
-{
-  global $conf;
-
-  if (!isset($email_address) or (trim($email_address) == ''))
-  {
-    return '';
-  }
-  else
-  {
-    return $email_address;
-  }
-}
-
-/*
- * Compute sql where condition with restrict and filter data. "FandF" means
- * Forbidden and Filters.
- *
- * @param array condition_fields: read function body
- * @param string prefix_condition: prefixes sql if condition is not empty
- * @param boolean force_one_condition: use at least "1 = 1"
- *
- * @return string sql where/conditions
- */
-function get_sql_condition_FandF(
-  $condition_fields,
-  $prefix_condition = null,
-  $force_one_condition = false
-  )
-{
-  global $user, $filter;
-
-  $sql_list = array();
-
-  foreach ($condition_fields as $condition => $field_name)
-  {
-    switch($condition)
-    {
-      case 'forbidden_categories':
-      {
-        if (!empty($user['forbidden_categories']))
-        {
-          $sql_list[] =
-            $field_name.' NOT IN ('.$user['forbidden_categories'].')';
-        }
-        break;
-      }
-      case 'visible_categories':
-      {
-        if (!empty($filter['visible_categories']))
-        {
-          $sql_list[] =
-            $field_name.' IN ('.$filter['visible_categories'].')';
-        }
-        break;
-      }
-      case 'visible_images':
-        if (!empty($filter['visible_images']))
-        {
-          $sql_list[] =
-            $field_name.' IN ('.$filter['visible_images'].')';
-        }
-        // note there is no break - visible include forbidden
-      case 'forbidden_images':
-        if (
-            !empty($user['image_access_list'])
-            or $user['image_access_type']!='NOT IN'
-            )
-        {
-          $table_prefix=null;
-          if ($field_name=='id')
-          {
-            $table_prefix = '';
-          }
-          elseif ($field_name=='i.id')
-          {
-            $table_prefix = 'i.';
-          }
-          if ( isset($table_prefix) )
-          {
-            $sql_list[]=$table_prefix.'level<='.$user['level'];
-          }
-          else
-          {
-            $sql_list[]=$field_name.' '.$user['image_access_type']
-                .' ('.$user['image_access_list'].')';
-          }
-        }
-        break;
-      default:
-      {
-        die('Unknow condition');
-        break;
-      }
-    }
-  }
-
-  if (count($sql_list) > 0)
-  {
-    $sql = '('.implode(' AND ', $sql_list).')';
-  }
-  else
-  {
-    $sql = $force_one_condition ? '1 = 1' : '';
-  }
-
-  if (isset($prefix_condition) and !empty($sql))
-  {
-    $sql = $prefix_condition.' '.$sql;
-  }
-
-  return $sql;
-}
-
-/**
- * search an available activation_key
- *
- * @return string
- */
-function get_user_activation_key()
-{
-  while (true)
-  {
-    $key = generate_key(20);
-    $query = '
-SELECT COUNT(*)
-  FROM '.USER_INFOS_TABLE.'
-  WHERE activation_key = \''.$key.'\'
-;';
-    list($count) = pwg_db_fetch_row(pwg_query($query));
-    if (0 == $count)
-    {
-      return $key;
-    }
-  }
-}
-
-?>
Index: /extensions/Ldap_Login/index.php
===================================================================
--- /extensions/Ldap_Login/index.php	(revision 27036)
+++ /extensions/Ldap_Login/index.php	(revision 27036)
@@ -0,0 +1,30 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | Piwigo - a PHP based photo gallery                                    |
+// +-----------------------------------------------------------------------+
+// | Copyright(C) 2008-2013 Piwigo Team                  http://piwigo.org |
+// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
+// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+// Recursive call
+$url = '../';
+header( 'Request-URI: '.$url );
+header( 'Content-Location: '.$url );
+header( 'Location: '.$url );
+exit();
+?>
Index: /extensions/Ldap_Login/language/da_DK/plugin.lang.php
===================================================================
--- /extensions/Ldap_Login/language/da_DK/plugin.lang.php	(revision 27036)
+++ /extensions/Ldap_Login/language/da_DK/plugin.lang.php	(revision 27036)
@@ -0,0 +1,57 @@
+<?php
+/*
+Plugin Name: Ldap_Login
+Version: 1.0.1
+Description: Permet de se logger via une authentification ldap
+Plugin URI: http://www.22decembre.eu
+Author: 22decembre
+Author URI:http://www.22decembre.eu
+___________________________________
+
+Language Name: Dansk [DK]
+*/
+$lang['All LDAP users can use their ldap password everywhere on piwigo if needed.'] = 'Ldab bruger kan bruge ldap adgangskode overalt, de har brug.';
+$lang['New users when ldap auth is successfull'] = 'Nye bruger i tilfælde af en vellykket ldap';
+$lang['Ldap_Login Plugin'] = 'Ldap_Login Plugin';
+$lang['Ldap_Login configuration'] = 'Ldap_Login konfiguration';
+$lang['Warning: LDAP Extension missing.'] = 'Php-ldap udvidelse mangler.';
+
+// ldap server connection
+
+$lang['Ldap server host connection'] = 'Ldap server forbindelse';
+$lang['If empty, standard protocol ports will be used by the software.'] = 'Hvis dette felt er tomt, standart protokol ip-port vil blev brugt.';
+$lang['If empty, localhost and standard protocol ports will be used in configuration.'] = 'Hvis dette felterne er tomt, localhost og standart ip-port vil blev brugt.';
+$lang['Ldap server host'] = 'LDAP server adresse';
+$lang['Secure connexion'] = 'ssl forbindelse (ldaps)';
+$lang['Ldap port'] = 'Ip-port hvor LDAP lytter';
+
+// ldap attributes
+
+$lang['Ldap attributes'] = 'Attributer ldap';
+$lang['Base DN'] = 'Base DN hvor er brugerne (f.eks : ou=people,dc=example,dc=com)';
+$lang['Ldap filter'] = '';
+$lang['Attribute corresponding to the user name'] = 'Attribut der svarer til brugernavnet.';
+
+// ldap connection credentials
+$lang['Ldap connection credentials'] = 'Ldap forbindelse DN og adgangskode';
+$lang['Let the fields blank if the ldap accept anonymous connections.'] = 'Lade felterne tomt hvid LDAP acceptere anonym forbindelser.';
+$lang['Bind DN, field in full ldap style'] = 'Bind DN med den ldap stil (f.eks : cn=admin,dc=example,dc=com).';
+$lang['Bind password'] = 'Adgangskode';
+
+// test and save
+
+$lang['Username'] = 'Din LDAP brugernavn.';
+$lang['Your password'] = 'Din LDAP adgangskode.';
+$lang['Ldap_Login Test'] = 'Ldap_Login Test';
+$lang['You must save the settings with the Save button just up there before testing here.'] = 'Du skal gemme indstillingerne med knappen Gem lige deroppe før testning her';
+$lang['Save'] = 'Gem';
+$lang['Test Settings'] = 'Test instillingerne.';
+
+// new piwigo users
+
+$lang['If the LDAP doesn\'t furnish the mail address, users can set it up in the profile page.'] = 'Hvis LDAP ikke give mail addresse, brugerne kan give i profile side.';
+$lang['Do you want to send mail to the new users, like casual piwigo users receive ?'] = 'Vil du send beskeder til nye bruger, ligesom tilfældige brugere modtager?';
+$lang['Do you allow new piwigo users to be created when users authenticate succesfully on the ldap ?'] = 'Ønsker du at oprette nye brugere, når Ldap forbindelse er en succes?';
+$lang['Do you want admins to be advertised by mail in case of new users creation upon ldap login ?'] = 'Vil du send beskeder til administratorer da vi oprette nye bruger ?';
+
+?>
Index: /extensions/Ldap_Login/language/en_UK/plugin.lang.php
===================================================================
--- /extensions/Ldap_Login/language/en_UK/plugin.lang.php	(revision 27036)
+++ /extensions/Ldap_Login/language/en_UK/plugin.lang.php	(revision 27036)
@@ -0,0 +1,59 @@
+<?php
+/*
+Plugin Name: Ldap_Login
+Version: 1.0.1
+Description: Permet de se logger via une authentification ldap
+Plugin URI: http://www.22decembre.eu
+Author: 22decembre
+Author URI:http://www.22decembre.eu
+___________________________________
+
+Language Name: English [UK]
+*/
+
+$lang['All LDAP users can use their ldap password everywhere on piwigo if needed.'] = 'All LDAP users can use their ldap password everywhere on piwigo if needed.';
+$lang['New users when ldap auth is successfull'] = 'New users when ldap auth is successfull';
+$lang['Ldap_Login Plugin'] = 'Ldap_Login Plugin';
+$lang['Ldap_Login configuration'] = 'Ldap_Login configuration';
+$lang['Warning: LDAP Extension missing.'] = 'Warning: LDAP Extension missing.';
+
+// ldap server connection
+
+$lang['Ldap server host connection'] = 'Ldap server connection';
+$lang['If empty, standard protocol ports will be used by the software.'] = 'If empty, standard protocol ports will be used by the software.';
+$lang['If empty, localhost and standard protocol ports will be used in configuration.'] = 'If empty, localhost and standard protocol ports will be used in configuration.';
+$lang['Ldap server host'] = 'Ldap server host';
+$lang['Secure connexion'] = 'Secure connexion (ldaps)';
+$lang['Ldap port'] = 'Ldap port';
+
+// ldap attributes
+
+$lang['Ldap attributes'] = 'Ldap attributes';
+$lang['Base DN'] = 'Base DN where ldap users should be found (ex : 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 connection credentials
+
+$lang['Ldap connection credentials'] = 'Ldap connection credentials';
+$lang['Let the fields blank if the ldap accept anonymous connections.'] = 'Let the fields blank if the ldap accept anonymous connections.';
+$lang['Bind DN, field in full ldap style'] = 'Bind DN in ldap style (for ex : cn=admin,dc=example,dc=com).';
+$lang['Bind password'] = 'Bind password';
+
+// test and save
+
+$lang['Username'] = 'Votre ldap username';
+$lang['Your password'] = 'Your LDAP password.';
+$lang['Ldap_Login Test'] = 'Ldap_Login Test';
+$lang['You must save the settings with the Save button just up there before testing here.'] = 'You need to save settings with the Save button just up there before testing them.';
+$lang['Save'] = 'Save';
+$lang['Test Settings'] = 'Test settings';
+
+// new piwigo users
+
+$lang['Do you want admins to be advertised by mail in case of new users creation upon ldap login ?'] = 'Do you want admins to be advertised by mail in case of new users creation upon ldap login ?';
+$lang['Do you want to send mail to the new users, like casual piwigo users receive ?'] = 'Do you want to send mail to the new users, like casual piwigo users receive ?';
+$lang['Do you allow new piwigo users to be created when users authenticate succesfully on the ldap ?'] = 'Do you allow new piwigo users to be created when users authenticate succesfully on the ldap ?';
+$lang['Do you want admins to be advertised by mail in case of new users creation upon ldap login ?'] = 'Do you want admins to be advertised by mail in case of new users creation upon ldap login ?';
+
+?>
Index: /extensions/Ldap_Login/language/fr_CA/plugin.lang.php
===================================================================
--- /extensions/Ldap_Login/language/fr_CA/plugin.lang.php	(revision 27036)
+++ /extensions/Ldap_Login/language/fr_CA/plugin.lang.php	(revision 27036)
@@ -0,0 +1,59 @@
+<?php
+/*
+Plugin Name: Ldap_Login
+Version: 1.0.1
+Description: Permet de se logger via une authentification ldap
+Plugin URI: http://www.22decembre.eu
+Author: 22decembre
+Author URI:http://www.22decembre.eu
+___________________________________
+
+Language Name: Français [FR]
+*/
+
+$lang['All LDAP users can use their ldap password everywhere on piwigo if needed.'] = 'Les utilisateurs ldap peuvent utiler leur mot de passe ldap partout où necessaire dans cette galerie piwigo.';
+$lang['New users when ldap auth is successfull'] = 'Nouveaux utilisateurs piwigo en cas de connection LDAP';
+$lang['Ldap_Login Plugin'] = 'Ldap_Login Plugin';
+$lang['Ldap_Login Plugin configuration'] = 'Configuration du plugin Ldap_Login';
+$lang['Warning: LDAP Extension missing.'] = 'Attention: Extension LDAP manquante.';
+
+// ldap server connection
+
+$lang['Ldap server host connection'] = 'Connection au serveur Ldap';
+$lang['If empty, standard protocol ports will be used by the software.'] = 'Les ports standarts seront utilisés si ce champs est laissé vide.';
+$lang['If empty, localhost and standard protocol ports will be used in configuration.'] = 'Localhost et les ports standard du protocol seront utilisés si ces champs sont laissés vides.';
+$lang['Ldap server host'] = 'Hote du serveur Ldap';
+$lang['Secure connexion'] = 'Connexion sécurisée (ldaps)';
+$lang['Ldap port'] = 'Port a utiliser';
+
+// ldap attributes
+
+$lang['Ldap attributes'] = 'Attributs ldap';
+$lang['Base DN'] = 'Arbre ldap à explorer où rechercher les utilisateurs (ex : ou=users,dc=exemple,dc=com)';
+$lang['Ldap filter'] = 'Filtre de recherche';
+$lang['Attribute corresponding to the user name'] = 'Attribut correspondant au nom d\'utilisateur';
+
+// ldap connection credentials
+
+$lang['Ldap connection credentials'] = 'Identifiants de connection LDAP';
+$lang['Let the fields blank if the ldap accept anonymous connections.'] = 'Laissez les champs vides si le ldap accepte les connexions anonymes.';
+$lang['Bind DN, field in full ldap style'] = 'Identifiant de connection, avec syntaxe LDAP complète (par ex : cn=admin,dc=example,dc=com).';
+$lang['Bind password'] = 'Mot de passe de connection';
+
+// test and save
+
+$lang['Username'] = 'Votre nom d\'utilisateur LDAP';
+$lang['Your password'] = 'Votre mot de passe LDAP.';
+$lang['Ldap_Login Test'] = 'Test du plugin Ldap_Login';
+$lang['You must save the settings with the Save button just up there before testing here.'] = 'Vous devez sauvegarder les paramètres avec le bouton Enregistrer juste au dessus avant de faire ce test.'; 
+$lang['Test Settings'] = 'Tester les paramètres';
+$lang['Save'] = 'Enregistrer';
+
+// new piwigo users
+
+$lang['If the LDAP doesn\'t furnish the mail address, users can set it up in the profile page.'] = 'Si le ldap ne fournit pas l\'adresse courriel, les utilisateurs peuvent l\'enregistrer dans la page de profil.';
+$lang['Do you want to send mail to the new users, like casual piwigo users receive ?'] = 'Voulez-vous envoyer le courriel habituel aux nouveaux utilisateurs de Piwigo crées par le plugin ?';
+$lang['Do you allow new piwigo users to be created when users authenticate succesfully on the ldap ?'] = 'Voulez-vous créer des utilisateurs piwigo lorsque quelqu\'un se connecte avec des identifiants ldap valides ?';
+$lang['Do you want admins to be advertised by mail in case of new users creation upon ldap login ?'] = 'Voulez-vous que les administrateurs du site soient prévenus lors de ces créations d\'utilisateurs ?';
+
+?>
Index: /extensions/Ldap_Login/language/fr_FR/plugin.lang.php
===================================================================
--- /extensions/Ldap_Login/language/fr_FR/plugin.lang.php	(revision 27036)
+++ /extensions/Ldap_Login/language/fr_FR/plugin.lang.php	(revision 27036)
@@ -0,0 +1,59 @@
+<?php
+/*
+Plugin Name: Ldap_Login
+Version: 1.0.1
+Description: Permet de se logger via une authentification ldap
+Plugin URI: http://www.22decembre.eu
+Author: 22decembre
+Author URI:http://www.22decembre.eu
+___________________________________
+
+Language Name: Français [FR]
+*/
+
+$lang['All LDAP users can use their ldap password everywhere on piwigo if needed.'] = 'Les utilisateurs ldap peuvent utiler leur mot de passe ldap partout où necessaire dans cette galerie piwigo.';
+$lang['New users when ldap auth is successfull'] = 'Nouveaux utilisateurs piwigo en cas de connection LDAP';
+$lang['Ldap_Login Plugin'] = 'Ldap_Login Plugin';
+$lang['Ldap_Login Plugin configuration'] = 'Configuration du plugin Ldap_Login';
+$lang['Warning: LDAP Extension missing.'] = 'Attention: Extension LDAP manquante.';
+
+// ldap server connection
+
+$lang['Ldap server host connection'] = 'Connection au serveur Ldap';
+$lang['If empty, standard protocol ports will be used by the software.'] = 'Les ports standarts seront utilisés si ce champs est laissé vide.';
+$lang['If empty, localhost and standard protocol ports will be used in configuration.'] = 'Localhost et les ports standard du protocol seront utilisés si ces champs sont laissés vides.';
+$lang['Ldap server host'] = 'Hote du serveur Ldap';
+$lang['Secure connexion'] = 'Connexion sécurisée (ldaps)';
+$lang['Ldap port'] = 'Port a utiliser';
+
+// ldap attributes
+
+$lang['Ldap attributes'] = 'Attributs ldap';
+$lang['Base DN'] = 'Arbre ldap à explorer où rechercher les utilisateurs (ex : ou=users,dc=exemple,dc=com)';
+$lang['Ldap filter'] = 'Filtre de recherche';
+$lang['Attribute corresponding to the user name'] = 'Attribut correspondant au nom d\'utilisateur';
+
+// ldap connection credentials
+
+$lang['Ldap connection credentials'] = 'Identifiants de connection LDAP';
+$lang['Let the fields blank if the ldap accept anonymous connections.'] = 'Laissez les champs vides si le ldap accepte les connexions anonymes.';
+$lang['Bind DN, field in full ldap style'] = 'Identifiant de connection, avec syntaxe LDAP complète (par ex : cn=admin,dc=example,dc=com).';
+$lang['Bind password'] = 'Mot de passe de connection';
+
+// test and save
+
+$lang['Username'] = 'Votre nom d\'utilisateur LDAP';
+$lang['Your password'] = 'Votre mot de passe LDAP.';
+$lang['Ldap_Login Test'] = 'Test du plugin Ldap_Login';
+$lang['You must save the settings with the Save button just up there before testing here.'] = 'Vous devez sauvegarder les paramètres avec le bouton Enregistrer juste au dessus avant de faire ce test.'; 
+$lang['Test Settings'] = 'Tester les paramètres';
+$lang['Save'] = 'Enregistrer';
+
+// new piwigo users
+
+$lang['If the LDAP doesn\'t furnish the mail address, users can set it up in the profile page.'] = 'Si le ldap ne fournit pas l\'adresse courriel, les utilisateurs peuvent l\'enregistrer dans la page de profil.';
+$lang['Do you want to send mail to the new users, like casual piwigo users receive ?'] = 'Voulez-vous envoyer le courriel habituel aux nouveaux utilisateurs de Piwigo crées par le plugin ?';
+$lang['Do you allow new piwigo users to be created when users authenticate succesfully on the ldap ?'] = 'Voulez-vous créer des utilisateurs piwigo lorsque quelqu\'un se connecte avec des identifiants ldap valides ?';
+$lang['Do you want admins to be advertised by mail in case of new users creation upon ldap login ?'] = 'Voulez-vous que les administrateurs du site soient prévenus lors de ces créations d\'utilisateurs ?';
+
+?>
Index: /extensions/Ldap_Login/language/index.php
===================================================================
--- /extensions/Ldap_Login/language/index.php	(revision 27036)
+++ /extensions/Ldap_Login/language/index.php	(revision 27036)
@@ -0,0 +1,30 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | Piwigo - a PHP based photo gallery                                    |
+// +-----------------------------------------------------------------------+
+// | Copyright(C) 2008-2013 Piwigo Team                  http://piwigo.org |
+// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
+// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+// Recursive call
+$url = '../';
+header( 'Request-URI: '.$url );
+header( 'Content-Location: '.$url );
+header( 'Location: '.$url );
+exit();
+?>
Index: /extensions/Ldap_Login/main.inc.php
===================================================================
--- /extensions/Ldap_Login/main.inc.php	(revision 27035)
+++ /extensions/Ldap_Login/main.inc.php	(revision 27036)
@@ -2,117 +2,113 @@
 /*
 Plugin Name: Ldap_Login
-Version: 0.1
-Description: Permet de se logger via une authentification ldap
-Plugin URI: http://www.22decembre.eu
+Version: 1.0.1
+Description: Allow piwigo authentication along an ldap
+Plugin URI: 
 Author: 22decembre
-Author URI:http://www.22decembre.eu
+Author URI: http://www.22decembre.eu
 */
-
 if (!defined('PHPWG_ROOT_PATH')) die('Hacking attempt!');
 
-add_event_handler('try_login','ldap_login', 0, 4);
+// +-----------------------------------------------------------------------+
+// | Define plugin constants                                               |
+// +-----------------------------------------------------------------------+
+define('LDAP_LOGIN_ID',      basename(dirname(__FILE__)));
+define('LDAP_LOGIN_PATH' ,   PHPWG_PLUGINS_PATH . LDAP_LOGIN_ID . '/');
+define('LDAP_LOGIN_ADMIN',   get_root_url() . 'admin.php?page=plugin-' . LDAP_LOGIN_ID);
+define('LDAP_LOGIN_VERSION', '1.0.1');
 
-function ldap_login($username, $password, $remember_me, $success)
-{
-  #pwg_session_gc();
+include_once(LDAP_LOGIN_PATH.'/class.ldap.php');
 
-  global $conf;
-    $query = '
-SELECT '.$conf['user_fields']['id'].' AS id FROM '.USERS_TABLE.' WHERE '.$conf['user_fields']['username'].' = \''.pwg_db_real_escape_string($username).'\'
-;';
+// +-----------------------------------------------------------------------+
+// | Event handlers                                                        |
+// +-----------------------------------------------------------------------+
+
+add_event_handler('init', 'ld_init');
+
+add_event_handler('try_log_user','login', 0, 4);
+
+add_event_handler('get_admin_plugin_menu_links', array(&$ldap, 'ldap_admin_menu'));
+
+// +-----------------------------------------------------------------------+
+// | Admin menu loading                                                    |
+// +-----------------------------------------------------------------------+
+
+$ldap = new Ldap();
+$ldap->load_config();
+set_plugin_data($plugin['id'], $ldap);
+unset($ldap);
+
+// +-----------------------------------------------------------------------+
+// | functions                                                             |
+// +-----------------------------------------------------------------------+
+
+function random_password( $length = 8 ) {
+    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?";
+    $password = substr( str_shuffle( $chars ), 0, $length );
+    return $password;
+}
+
+function ld_init(){
+	load_language('plugin.lang', LDAP_LOGIN_PATH);
+}
+
+
+function login($success, $username, $password, $remember_me){
+
+	global $conf;
+	
+	$obj = new Ldap();
+	$obj->load_config();
+	$obj->ldap_conn() or die("Unable to connect LDAP server : ".$ldap->getErrorString());
+
+	if (!$obj->ldap_bind_as($username,$password)){ // bind with userdn
+		trigger_action('login_failure', stripslashes($username));
+		return false; // wrong password
+	}
+
+	// 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));
 
-    // Vérification de l'authentification
-    if (ldap_log($username,$password)) {
+  // 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($row['id'], $remember_me);
-	trigger_action('login_success', stripslashes($username));
-	return true;
-	}
-    else
-    {
-    trigger_action('login_failure', stripslashes($username));
-    return false;
-    }
+			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;
+		}
+  	}
 }
 
-function ldap_log($user,$pass)
-{
-$obj = new Ldap();
-$obj->load_config();
-
-// Eléments d'authentification LDAP
-$ldaprdn  = $obj->config['pref'].$user.$obj->config['basedn'];     // DN ou RDN LDAP
-//$ldappass = 'password';  // Mot de passe associé
-
-// Connexion au serveur LDAP
-$ldapconn = ldap_connect($obj->config['host'])
-    or die("Impossible de se connecter au serveur LDAP.");
-    
-ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
-
-if ($ldapconn) {
-
-    // Connexion au serveur LDAP
-    $ldapbind = ldap_bind($ldapconn, $ldaprdn, $pass);
-    
-    // Vérification de l'authentification
-    if ($ldapbind) {
-       // echo "Connexion LDAP réussie...";
-	return true;
-    } else {
-       // echo "Connexion LDAP échouée...";
-      return false;
-    }
-
-}
-}
-
-class Ldap
-{
-    var $config;
-    function load_config()
-    {
-        $x = @file_get_contents( dirname(__FILE__).'/data.dat' );
-        if ($x!==false)
-        {
-            $c = unserialize($x);
-            // do some more tests here
-            $this->config = $c;
-        }
- 
-        if ( !isset($this->config)
-            or empty($this->config['Test']) )
-        {
-            $this->config['host']	= 'localhost';
-	    $this->config['basedn']	= ',ou=utilisateurs,dc=22decembre,dc=eu';
-            $this->config['pref']	= 'uid=';
-            $this->save_config();
-        }
-    }
-    function save_config()
-    {
-        $file = fopen( dirname(__FILE__).'/data.dat', 'w' );
-        fwrite($file, serialize($this->config) );
-        fclose( $file );
-    }
-
-    function ldap_admin_menu($menu)
-    {
-    array_push($menu,
-	array(
-	'NAME' => 'Ldap Login',
-	'URL' => get_admin_plugin_menu_link(dirname(__FILE__).'/admin/ldap_login_plugin_admin.php') )
-	);
-      
-    return $menu;
-    }
-}
-
-$ldap = new Ldap();
-$ldap->load_config();
-add_event_handler('get_admin_plugin_menu_links', array(&$ldap, 'ldap_admin_menu'));
-set_plugin_data($plugin['id'], $ldap);
-
 ?>
