2 /*******************************************************************************
3 * Copyright (C) 2007 Easter-eggs
4 * http://ldapsaisie.labs.libre-entreprise.org
6 * Author: See AUTHORS file in top-level directory.
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License version 2
10 * as published by the Free Software Foundation.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21 ******************************************************************************/
24 * Gestion des sessions
26 * Cette classe gère les sessions d'utilisateurs.
28 * @author Benjamin Renard <brenard@easter-eggs.com>
32 // La configuration du serveur Ldap utilisé
33 public static $ldapServer = NULL;
35 // L'id du serveur Ldap utilisé
36 private static $ldapServerId = NULL;
39 private static $topDn = NULL;
41 // Le DN de l'utilisateur connecté
42 private static $dn = NULL;
44 // Le RDN de l'utilisateur connecté (son identifiant)
45 private static $rdn = NULL;
47 // Les LSprofiles de l'utilisateur
48 private static $LSprofiles = array();
50 // Les droits d'accès de l'utilisateur
51 private static $LSaccess = array();
53 // Les fichiers temporaires
54 private static $tmp_file = array();
56 // Langue et encodage actuel
57 private static $lang = NULL;
58 private static $encoding = NULL;
61 * Constante de classe non stockée en session
63 // Le template à afficher
64 private static $template = NULL;
66 // Les subDn des serveurs Ldap
67 private static $_subDnLdapServer = array();
70 private static $ajaxDisplay = false;
72 // Les fichiers JS à charger dans la page
73 private static $JSscripts = array();
75 // Les paramètres JS à communiquer dans la page
76 private static $_JSconfigParams = array();
78 // Les fichiers CSS à charger dans la page
79 private static $CssFiles = array();
81 // L'objet de l'utilisateur connecté
82 private static $LSuserObject = NULL;
84 // The LSauht object of the session
85 private static $LSauthObject = false;
87 // User LDAP credentials
88 private static $userLDAPcreds = false;
91 * Include un fichier PHP
93 * @author Benjamin Renard <brenard@easter-eggs.com>
95 * @retval true si tout c'est bien passé, false sinon
97 public static function includeFile($file) {
98 if (file_exists(LS_LOCAL_DIR.'/'.$file)) {
99 $file=LS_LOCAL_DIR.'/'.$file;
101 elseif (!file_exists($file)) {
104 if (defined('LSdebug') && constant('LSdebug')) {
105 return include_once($file);
108 return @include_once($file);
114 * Lancement de LSconfig
116 * @author Benjamin Renard <brenard@easter-eggs.com>
118 * @retval true si tout c'est bien passé, false sinon
120 private static function startLSconfig() {
121 if (self :: loadLSclass('LSconfig')) {
122 if (LSconfig :: start()) {
126 die("ERROR : Can't load configuration files.");
131 * Lancement et initialisation de Smarty
133 * @author Benjamin Renard <brenard@easter-eggs.com>
135 * @retval true si tout c'est bien passé, false sinon
137 private static function startLStemplate() {
138 if ( self :: loadLSclass('LStemplate') ) {
139 return LStemplate :: start(
141 'smarty_path' => LSconfig :: get('Smarty'),
142 'template_dir' => LS_TEMPLATES_DIR,
143 'image_dir' => LS_IMAGES_DIR,
144 'css_dir' => LS_CSS_DIR,
145 'compile_dir' => LS_TMP_DIR,
147 'debug_smarty' => (isset($_REQUEST['LStemplate_debug'])),
155 * Retourne le topDn de la session
157 * @author Benjamin Renard <brenard@easter-eggs.com>
159 * @retval string le topDn de la session
161 public static function getTopDn() {
162 if (!is_null(self :: $topDn)) {
163 return self :: $topDn;
166 return self :: getRootDn();
171 * Retourne le rootDn de la session
173 * @author Benjamin Renard <brenard@easter-eggs.com>
175 * @retval string le rootDn de la session
177 public static function getRootDn() {
178 return self :: $ldapServer['ldap_config']['basedn'];
182 * Initialisation de la gestion des erreurs
184 * Création de l'objet LSerror
186 * @author Benjamin Renard <brenard@easter-eggs.com
188 * @retval boolean true si l'initialisation a réussi, false sinon.
190 private static function startLSerror() {
191 if(!self :: loadLSclass('LSerror')) {
194 set_error_handler(array('LSerror','errorHandler'),E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED & ~E_WARNING);
195 self :: defineLSerrors();
200 * Chargement d'une classe d'LdapSaisie
202 * @param[in] $class Nom de la classe à charger (Exemple : LSpeople)
203 * @param[in] $type (Optionnel) Type de classe à charger (Exemple : LSobjects)
205 * @author Benjamin Renard <brenard@easter-eggs.com
207 * @retval boolean true si le chargement a réussi, false sinon.
209 public static function loadLSclass($class,$type='') {
210 if (class_exists($class))
214 return self :: includeFile(LS_CLASS_DIR .'class.'.$type.$class.'.php');
218 * Chargement d'un object LdapSaisie
220 * @param[in] $object Nom de l'objet à charger
222 * @retval boolean true si le chargement a réussi, false sinon.
224 public static function loadLSobject($object) {
225 if(class_exists($object)) {
229 self :: loadLSclass('LSldapObject');
230 if (!self :: loadLSclass($object,'LSobjects')) {
233 if (!self :: includeFile( LS_OBJECTS_DIR . 'config.LSobjects.'.$object.'.php' )) {
237 if (!LSconfig :: set("LSobjects.$object",$GLOBALS['LSobjects'][$object])) {
240 else if (isset($GLOBALS['LSobjects'][$object]['LSaddons'])){
241 if (is_array($GLOBALS['LSobjects'][$object]['LSaddons'])) {
242 foreach ($GLOBALS['LSobjects'][$object]['LSaddons'] as $addon) {
243 if (!self :: loadLSaddon($addon)) {
249 if (!self :: loadLSaddon($GLOBALS['LSobjects'][$object]['LSaddons'])) {
256 LSerror :: addErrorCode('LSsession_04',$object);
263 * Chargement d'un addons d'LdapSaisie
265 * @param[in] $addon Nom de l'addon à charger (Exemple : samba)
267 * @author Benjamin Renard <brenard@easter-eggs.com
269 * @retval boolean true si le chargement a réussi, false sinon.
271 public static function loadLSaddon($addon) {
272 if(self :: includeFile(LS_ADDONS_DIR .'LSaddons.'.$addon.'.php')) {
273 self :: includeFile(LS_CONF_DIR."LSaddons/config.LSaddons.".$addon.".php");
274 if (!call_user_func('LSaddon_'. $addon .'_support')) {
275 LSerror :: addErrorCode('LSsession_02',$addon);
284 * Chargement d'une classe d'authentification d'LdapSaisie
286 * @author Benjamin Renard <brenard@easter-eggs.com
288 * @retval boolean true si le chargement a reussi, false sinon.
290 public static function loadLSauth() {
291 if (self :: loadLSclass('LSauth')) {
295 LSerror :: addErrorCode('LSsession_05','LSauth');
301 * Chargement des addons LdapSaisie
303 * Chargement des LSaddons contenue dans la variable
304 * $GLOBALS['LSaddons']['loads']
306 * @retval boolean true si le chargement a réussi, false sinon.
308 public static function loadLSaddons() {
309 $conf=LSconfig :: get('LSaddons.loads');
310 if(!is_array($conf)) {
311 LSerror :: addErrorCode('LSsession_01',"LSaddons['loads']");
315 foreach ($conf as $addon) {
316 self :: loadLSaddon($addon);
326 public static function setLocale() {
327 if (isset($_REQUEST['lang'])) {
328 $lang = $_REQUEST['lang'];
330 elseif (isset($_SESSION['LSlang'])) {
331 $lang = $_SESSION['LSlang'];
333 elseif (isset(self :: $ldapServer['lang'])) {
334 $lang = self :: $ldapServer['lang'];
337 $lang = LSconfig :: get('lang');
340 if (isset($_REQUEST['encoding'])) {
341 $encoding = $_REQUEST['encoding'];
343 elseif (isset($_SESSION['LSencoding'])) {
344 $encoding = $_SESSION['LSencoding'];
346 elseif (isset(self :: $ldapServer['encoding'])) {
347 $encoding = self :: $ldapServer['encoding'];
350 $encoding = LSconfig :: get('encoding');
353 $_SESSION['LSlang']=$lang;
355 $_SESSION['LSencoding']=$encoding;
356 self :: $encoding=$encoding;
359 if (self :: localeExist($lang,$encoding)) {
361 $lang.='.'.$encoding;
363 setlocale(LC_ALL, $lang);
364 bindtextdomain(LS_TEXT_DOMAIN, LS_I18N_DIR);
365 textdomain(LS_TEXT_DOMAIN);
367 self :: includeFile(LS_I18N_DIR.'/'.$lang.'/lang.php');
369 foreach (listFiles(LS_LOCAL_DIR.'/'.LS_I18N_DIR.'/'.$lang,'/^lang.+\.php$/') as $file) {
370 include(LS_LOCAL_DIR.'/'.LS_I18N_DIR."/$lang/$file");
374 if ($encoding && $lang) {
375 $lang.='.'.$encoding;
377 LSdebug('La locale "'.$lang.'" n\'existe pas, utilisation de la locale par défaut.');
382 * Retourne la liste des langues disponibles
384 * @retval array Tableau/Liste des langues disponibles
386 public static function getLangList() {
387 $list=array('en_US');
388 if (self :: $encoding) {
389 $regex = '^([a-zA-Z_]*)\.'.self :: $encoding.'$';
392 $regex = '^([a-zA-Z_]*)$';
394 if ($handle = opendir(LS_I18N_DIR)) {
395 while (false !== ($file = readdir($handle))) {
396 if(is_dir(LS_I18N_DIR.'/'.$file)) {
397 if (ereg($regex,$file,$regs)) {
398 if (!in_array($regs[1],$list)) {
409 * Retourne la langue courante de la session
411 * @param[in] boolean Si true, le code langue retourné sera court
413 * @retval string La langue de la session
415 public static function getLang($short=false) {
417 return strtolower(self :: $lang[0].self :: $lang[1]);
419 return self :: $lang;
423 * Vérifie si une locale est disponible
425 * @param[in] $lang string La langue (Ex : fr_FR)
426 * @param[in] $encoding string L'encodage de caractère (Ex : UTF8)
428 * @retval boolean True si la locale est disponible, False sinon
430 public static function localeExist($lang,$encoding) {
431 if ( !$lang && !$encoding ) {
434 $locale=$lang.(($encoding)?'.'.$encoding:'');
435 if ($locale=='en_US.UTF8') {
438 return (is_dir(LS_I18N_DIR.'/'.$locale));
442 * Initialisation LdapSaisie
444 * @retval boolean True si l'initialisation à réussi, false sinon.
446 public static function initialize() {
447 if (!self :: startLSconfig()) {
451 self :: startLSerror();
452 self :: startLStemplate();
458 self :: loadLSaddons();
459 self :: loadLSauth();
464 * Initialisation de la session LdapSaisie
466 * Initialisation d'une LSsession :
467 * - Authentification et activation du mécanisme de session de LdapSaisie
468 * - ou Chargement des paramètres de la session à partir de la variable
469 * $_SESSION['LSsession'].
470 * - ou Destruction de la session en cas de $_GET['LSsession_logout'].
472 * @retval boolean True si l'initialisation à réussi (utilisateur authentifié), false sinon.
474 public static function startLSsession() {
475 if (!self :: initialize()) {
479 if(isset($_SESSION['LSsession']['dn']) && !isset($_GET['LSsession_recoverPassword'])) {
480 LSdebug('LSsession : Session existente');
481 // --------------------- Session existante --------------------- //
482 self :: $topDn = $_SESSION['LSsession']['topDn'];
483 self :: $dn = $_SESSION['LSsession']['dn'];
484 self :: $rdn = $_SESSION['LSsession']['rdn'];
485 self :: $ldapServerId = $_SESSION['LSsession']['ldapServerId'];
486 self :: $tmp_file = $_SESSION['LSsession']['tmp_file'];
487 self :: $userLDAPcreds = $_SESSION['LSsession']['userLDAPcreds'];
489 if ( self :: cacheLSprofiles() && !isset($_REQUEST['LSsession_refresh']) ) {
490 self :: setLdapServer(self :: $ldapServerId);
491 if (!LSauth :: start()) {
492 LSdebug("LSsession : can't start LSauth -> stop");
495 self :: $LSprofiles = $_SESSION['LSsession']['LSprofiles'];
496 self :: $LSaccess = $_SESSION['LSsession']['LSaccess'];
497 if (!self :: LSldapConnect())
501 self :: setLdapServer(self :: $ldapServerId);
502 if (!LSauth :: start()) {
503 LSdebug("LSsession : can't start LSauth -> stop");
506 if (!self :: LSldapConnect())
508 self :: loadLSprofiles();
511 if ( self :: cacheSudDn() && (!isset($_REQUEST['LSsession_refresh'])) ) {
512 self :: $_subDnLdapServer = ((isset($_SESSION['LSsession_subDnLdapServer']))?$_SESSION['LSsession_subDnLdapServer']:NULL);
515 if (!self :: loadLSobject(self :: $ldapServer['authObjectType'])) {
519 if (isset($_GET['LSsession_logout'])) {
523 if (is_array($_SESSION['LSsession']['tmp_file'])) {
524 self :: $tmp_file = $_SESSION['LSsession']['tmp_file'];
526 self :: deleteTmpFile();
527 unset($_SESSION['LSsession']);
529 self :: redirect('index.php');
533 if ( !self :: cacheLSprofiles() || isset($_REQUEST['LSsession_refresh']) ) {
534 self :: loadLSaccess();
537 LStemplate :: assign('LSsession_username',self :: getLSuserObject() -> getDisplayName());
539 if (isset ($_POST['LSsession_topDn']) && $_POST['LSsession_topDn']) {
540 if (self :: validSubDnLdapServer($_POST['LSsession_topDn'])) {
541 self :: $topDn = $_POST['LSsession_topDn'];
542 $_SESSION['LSsession']['topDn'] = $_POST['LSsession_topDn'];
550 // --------------------- Session inexistante --------------------- //
551 if (isset($_GET['LSsession_recoverPassword'])) {
554 // Session inexistante
555 if (isset($_POST['LSsession_ldapserver'])) {
556 self :: setLdapServer($_POST['LSsession_ldapserver']);
559 self :: setLdapServer(0);
562 // Connexion au serveur LDAP
563 if (self :: LSldapConnect()) {
566 if (isset($_POST['LSsession_topDn']) && $_POST['LSsession_topDn'] != '' ){
567 self :: $topDn = $_POST['LSsession_topDn'];
570 self :: $topDn = self :: $ldapServer['ldap_config']['basedn'];
572 $_SESSION['LSsession_topDn']=self :: $topDn;
574 if (!LSauth :: start()) {
575 LSdebug("LSsession : can't start LSauth -> stop");
579 if (isset($_GET['LSsession_recoverPassword'])) {
580 $recoveryPasswordInfos = self :: recoverPasswd(
581 $_REQUEST['LSsession_user'],
582 $_GET['recoveryHash']
586 $LSuserObject = LSauth :: forceAuthentication();
588 // Authentication successful
589 self :: $LSuserObject = $LSuserObject;
590 self :: $dn = $LSuserObject->getValue('dn');
591 self :: $rdn = $LSuserObject->getValue('rdn');
592 if (isset(self :: $ldapServer['useUserCredentials']) && self :: $ldapServer['useUserCredentials']) {
593 self :: $userLDAPcreds = LSauth :: getLDAPcredentials($LSuserObject);
594 if (!is_array(self :: $userLDAPcreds)) {
595 LSerror :: addErrorCode('LSsession_14');
596 self :: $userLDAPcreds = false;
599 if (!LSldap :: reconnectAs(self :: $userLDAPcreds['dn'],self :: $userLDAPcreds['pwd'])) {
600 LSerror :: addErrorCode('LSsession_15');
604 self :: loadLSprofiles();
605 self :: loadLSaccess();
606 LStemplate :: assign('LSsession_username',self :: getLSuserObject() -> getDisplayName());
607 $_SESSION['LSsession']=self :: getContextInfos();
613 LSerror :: addErrorCode('LSsession_09');
616 if (self :: $ldapServerId) {
617 LStemplate :: assign('ldapServerId',self :: $ldapServerId);
619 LStemplate :: assign('topDn',self :: $topDn);
620 if (isset($_GET['LSsession_recoverPassword'])) {
621 self :: displayRecoverPasswordForm($recoveryPasswordInfos);
623 elseif(LSauth :: displayLoginForm()) {
624 self :: displayLoginForm();
627 self :: setTemplate('blank.tpl');
628 LSerror :: addErrorCode('LSsession_10');
635 * Do recover password
637 * @param[in] $username string The submited username
638 * @param[in] $recoveryHash string The submited recoveryHash
640 * @retval array The recoveryPassword infos for template
642 private static function recoverPasswd($username,$recoveryHash) {
643 $recoveryPasswordInfos=array();
644 if ( self :: loadLSobject(self :: $ldapServer['authObjectType']) ) {
645 $authobject = new self :: $ldapServer['authObjectType']();
646 if (!empty($recoveryHash)) {
647 $filter=Net_LDAP2_Filter::create(
648 self :: $ldapServer['recoverPassword']['recoveryHashAttr'],
652 $result = $authobject -> listObjects($filter,self :: $topDn);
654 elseif (!empty($username)) {
655 $result = $authobject -> searchObject(
658 self :: $ldapServer['authObjectFilter']
662 return $recoveryPasswordInfos;
665 $nbresult=count($result);
668 LSdebug('hash/username incorrect');
669 LSerror :: addErrorCode('LSsession_06');
671 elseif ($nbresult>1) {
672 LSerror :: addErrorCode('LSsession_07');
675 $rdn = $result[0] -> getValue('rdn');
677 LSdebug('Recover : Id trouvé : '.$username);
678 if (self :: $ldapServer['recoverPassword']) {
679 if (self :: loadLSaddon('mail')) {
680 LSdebug('Récupération active');
682 $emailAddress = $user -> getValue(self :: $ldapServer['recoverPassword']['mailAttr']);
683 $emailAddress = $emailAddress[0];
685 if (checkEmail($emailAddress)) {
686 LSdebug('Email : '.$emailAddress);
687 self :: $dn = $user -> getDn();
689 // 1ère étape : envoie du recoveryHash
690 if (empty($recoveryHash)) {
691 $hash=self :: recoverPasswdFirstStep($user);
693 if (self :: recoverPasswdSendMail($emailAddress,1,$hash)) {
694 // Mail a bien été envoyé
695 $recoveryPasswordInfos['recoveryHashMail']=$emailAddress;
699 // 2nd étape : génération du mot de passe + envoie par mail
701 $pwd=self :: recoverPasswdSecondStep($user);
703 if (self :: recoverPasswdSendMail($emailAddress,2,$pwd)){
704 // Mail a bien été envoyé
705 $recoveryPasswordInfos['newPasswordMail']=$emailAddress;
711 LSerror :: addErrorCode('LSsession_19');
716 LSerror :: addErrorCode('LSsession_18');
720 return $recoveryPasswordInfos;
724 * Send recover password mail
726 * @param[in] $mail string The user's mail
727 * @param[in] $step integer The step
728 * @param[in] $info string The info for formatted message
730 * @retval boolean True on success or False
732 private static function recoverPasswdSendMail($mail,$step,$info) {
735 if (self :: $ldapServer['recoverPassword']['recoveryEmailSender']) {
736 $sendParams['From']=self :: $ldapServer['recoverPassword']['recoveryEmailSender'];
740 if ($_SERVER['HTTPS']=='on') {
741 $recovery_url='https://';
744 $recovery_url='http://';
746 $recovery_url .= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'&recoveryHash='.$info;
748 $subject = self :: $ldapServer['recoverPassword']['recoveryHashMail']['subject'];
750 self :: $ldapServer['recoverPassword']['recoveryHashMail']['msg'],
755 $subject = self :: $ldapServer['recoverPassword']['newPasswordMail']['subject'];
757 self :: $ldapServer['recoverPassword']['newPasswordMail']['msg'],
762 if (!sendMail($mail,$subject,$msg,$sendParams)) {
763 LSdebug("Problème durant l'envoie du mail");
764 LSerror :: addErrorCode('LSsession_20',4);
772 * Do first step of recovering password
774 * @param[in] $user LSldapObject The LSldapObject of the user
776 * @retval string|False The recory hash on success or False
778 private static function recoverPasswdFirstStep($user) {
780 $rdn=$user -> getValue('rdn');
782 $recovery_hash = md5($rdn . strval(time()) . strval(rand()));
784 $lostPasswdForm = $user -> getForm('lostPassword');
785 $lostPasswdForm -> setPostData(
787 self :: $ldapServer['recoverPassword']['recoveryHashAttr'] => $recovery_hash
792 if($lostPasswdForm -> validate()) {
793 if ($user -> updateData('lostPassword')) {
794 // recoveryHash de l'utilisateur mis à jour
795 return $recovery_hash;
798 // Erreur durant la mise à jour de l'objet
799 LSdebug("Erreur durant la mise à jour de l'objet");
800 LSerror :: addErrorCode('LSsession_20',6);
804 // Erreur durant la validation du formulaire de modification de perte de password
805 LSdebug("Erreur durant la validation du formulaire de modification de perte de password");
806 LSerror :: addErrorCode('LSsession_20',5);
812 * Do second step of recovering password
814 * @param[in] $user LSldapObject The LSldapObject of the user
816 * @retval string|False The new password on success or False
818 private static function recoverPasswdSecondStep($user) {
819 $attr=$user -> attrs[self :: $ldapServer['authObjectTypeAttrPwd']];
820 if ($attr instanceof LSattribute) {
821 $mdp = generatePassword(
822 $attr -> config['html_options']['chars'],
823 $attr -> config['html_options']['lenght']
825 LSdebug('Nvx mpd : '.$mdp);
826 $lostPasswdForm = $user -> getForm('lostPassword');
827 $lostPasswdForm -> setPostData(
829 self :: $ldapServer['recoverPassword']['recoveryHashAttr'] => array(''),
830 self :: $ldapServer['authObjectTypeAttrPwd'] => array($mdp)
834 if($lostPasswdForm -> validate()) {
835 if ($user -> updateData('lostPassword')) {
839 // Erreur durant la mise à jour de l'objet
840 LSdebug("Erreur durant la mise à jour de l'objet");
841 LSerror :: addErrorCode('LSsession_20',3);
845 // Erreur durant la validation du formulaire de modification de perte de password
846 LSdebug("Erreur durant la validation du formulaire de modification de perte de password");
847 LSerror :: addErrorCode('LSsession_20',2);
851 // l'attribut password n'existe pas
852 LSdebug("L'attribut password n'existe pas");
853 LSerror :: addErrorCode('LSsession_20',1);
859 * Retourne les informations du contexte
861 * @author Benjamin Renard <brenard@easter-eggs.com
863 * @retval array Tableau associatif des informations du contexte
865 private static function getContextInfos() {
867 'tmp_file' => self :: $tmp_file,
868 'topDn' => self :: $topDn,
870 'rdn' => self :: $rdn,
871 'userLDAPcreds' => self :: $userLDAPcreds,
872 'ldapServerId' => self :: $ldapServerId,
873 'ldapServer' => self :: $ldapServer,
874 'LSprofiles' => self :: $LSprofiles,
875 'LSaccess' => self :: $LSaccess
880 * Retourne l'objet de l'utilisateur connecté
882 * @author Benjamin Renard <brenard@easter-eggs.com
884 * @retval mixed L'objet de l'utilisateur connecté ou false si il n'a pas put
887 public static function getLSuserObject($dn=null) {
891 if (!self :: $LSuserObject) {
892 if (self :: loadLSobject(self :: $ldapServer['authObjectType'])) {
893 self :: $LSuserObject = new self :: $ldapServer['authObjectType']();
894 self :: $LSuserObject -> loadData(self :: $dn);
900 return self :: $LSuserObject;
904 * Retourne le DN de l'utilisateur connecté
906 * @author Benjamin Renard <brenard@easter-eggs.com
908 * @retval string Le DN de l'utilisateur connecté
910 public static function getLSuserObjectDn() {
915 * Modifie l'utilisateur connecté à la volé
917 * @param[in] $object Mixed L'objet Ldap du nouvel utilisateur
918 * le type doit correspondre à
919 * self :: $ldapServer['authObjectType']
921 * @retval boolean True en cas de succès, false sinon
923 public static function changeAuthUser($object) {
924 if ($object instanceof self :: $ldapServer['authObjectType']) {
925 self :: $dn = $object -> getDn();
926 $rdn = $object -> getValue('rdn');
931 self :: $LSuserObject = $object;
933 if(self :: loadLSprofiles()) {
934 self :: loadLSaccess();
935 $_SESSION['LSsession']=self :: getContextInfos();
943 * Définition du serveur Ldap de la session
945 * Définition du serveur Ldap de la session à partir de son ID dans
946 * le tableau LSconfig :: get('ldap_servers').
948 * @param[in] integer Index du serveur Ldap
950 * @retval boolean True sinon false.
952 public static function setLdapServer($id) {
953 $conf = LSconfig :: get("ldap_servers.$id");
954 if ( is_array($conf) ) {
955 self :: $ldapServerId = $id;
956 self :: $ldapServer = $conf;
966 * Connexion au serveur Ldap
968 * @retval boolean True sinon false.
970 public static function LSldapConnect() {
971 if (self :: $ldapServer) {
972 self :: includeFile(LSconfig :: get('NetLDAP2'));
973 if (!self :: loadLSclass('LSldap')) {
976 if (self :: $dn && isset(self :: $ldapServer['useUserCredentials']) && self :: $ldapServer['useUserCredentials']) {
977 LSldap :: reconnectAs(self :: $userLDAPcreds['dn'], self :: $userLDAPcreds['pwd'],self :: $ldapServer['ldap_config']);
980 LSldap :: connect(self :: $ldapServer['ldap_config']);
982 if (LSldap :: isConnected()) {
990 LSerror :: addErrorCode('LSsession_03');
996 * Use this function to know if subDn is enabled for the curent LdapServer
1000 public static function subDnIsEnabled() {
1001 if (!isset(self :: $ldapServer['subDn'])) {
1004 if ( !is_array(self :: $ldapServer['subDn']) ) {
1011 * Retourne les sous-dns du serveur Ldap courant
1013 * @retval mixed Tableau des subDn, false si une erreur est survenue.
1015 public static function getSubDnLdapServer($login=false) {
1016 $login=(bool)$login;
1017 if (self :: cacheSudDn() && isset(self :: $_subDnLdapServer[self :: $ldapServerId][$login])) {
1018 return self :: $_subDnLdapServer[self :: $ldapServerId][$login];
1020 if (!self::subDnIsEnabled()) {
1024 foreach(self :: $ldapServer['subDn'] as $subDn_name => $subDn_config) {
1025 if ($login && isset($subDn_config['nologin']) && $subDn_config['nologin']) continue;
1026 if ($subDn_name == 'LSobject') {
1027 if (is_array($subDn_config)) {
1028 foreach($subDn_config as $LSobject_name => $LSoject_config) {
1029 if (isset($LSoject_config['basedn']) && !empty($LSoject_config['basedn'])) {
1030 $basedn = $LSoject_config['basedn'];
1033 $basedn = self::getRootDn();
1035 if (isset($LSoject_config['displayName']) && !empty($LSoject_config['displayName'])) {
1036 $displayName = $LSoject_config['displayName'];
1039 $displayName = NULL;
1041 if( self :: loadLSobject($LSobject_name) ) {
1042 if ($subdnobject = new $LSobject_name()) {
1043 $tbl_return = $subdnobject -> getSelectArray(NULL,$basedn,$displayName);
1044 if (is_array($tbl_return)) {
1045 $return=array_merge($return,$tbl_return);
1048 LSerror :: addErrorCode('LSsession_17',3);
1052 LSerror :: addErrorCode('LSsession_17',2);
1058 LSerror :: addErrorCode('LSsession_17',1);
1062 if ((isCompatibleDNs($subDn_config['dn'],self :: $ldapServer['ldap_config']['basedn']))&&($subDn_config['dn']!="")) {
1063 $return[$subDn_config['dn']] = __($subDn_name);
1067 if (self :: cacheSudDn()) {
1068 self :: $_subDnLdapServer[self :: $ldapServerId][$login]=$return;
1069 $_SESSION['LSsession_subDnLdapServer'] = self :: $_subDnLdapServer;
1075 * Retourne la liste de subDn du serveur Ldap utilise
1076 * trié par la profondeur dans l'arboressence (ordre décroissant)
1078 * @return array() Tableau des subDn trié
1080 public static function getSortSubDnLdapServer($login=false) {
1081 $subDnLdapServer = self :: getSubDnLdapServer($login);
1082 if (!$subDnLdapServer) {
1085 uksort($subDnLdapServer,"compareDn");
1086 return $subDnLdapServer;
1090 * Retourne les options d'une liste déroulante pour le choix du topDn
1091 * de connexion au serveur Ldap
1093 * Liste les subdn (self :: $ldapServer['subDn'])
1095 * @retval string Les options (<option>) pour la sélection du topDn.
1097 public static function getSubDnLdapServerOptions($selected=NULL,$login=false) {
1098 $list = self :: getSubDnLdapServer($login);
1102 foreach($list as $dn => $txt) {
1103 if ($selected && ($selected==$dn)) {
1104 $selected_txt = ' selected';
1109 $display.="<option value=\"".$dn."\"$selected_txt>".$txt."</option>\n";
1117 * Vérifie qu'un subDn est déclaré
1119 * @param[in] string Un subDn
1121 * @retval boolean True si le subDn existe, False sinon
1123 public static function validSubDnLdapServer($subDn) {
1124 $listTopDn = self :: getSubDnLdapServer();
1125 if(is_array($listTopDn)) {
1126 foreach($listTopDn as $dn => $txt) {
1136 * Test un couple LSobject/pwd
1138 * Test un bind sur le serveur avec le dn de l'objet et le mot de passe fourni.
1140 * @param[in] LSobject L'object "user" pour l'authentification
1141 * @param[in] string Le mot de passe à tester
1143 * @retval boolean True si l'authentification à réussi, false sinon.
1145 public static function checkUserPwd($object,$pwd) {
1146 return LSldap :: checkBind($object -> getValue('dn'),$pwd);
1150 * Affiche le formulaire de login
1152 * Défini les informations pour le template Smarty du formulaire de login.
1156 public static function displayLoginForm() {
1157 LStemplate :: assign('pagetitle',_('Connection'));
1158 if (isset($_GET['LSsession_logout'])) {
1159 LStemplate :: assign('loginform_action','index.php');
1162 LStemplate :: assign('loginform_action',$_SERVER['REQUEST_URI']);
1164 if (count(LSconfig :: get('ldap_servers'))==1) {
1165 LStemplate :: assign('loginform_ldapserver_style','style="display: none"');
1167 LStemplate :: assign('loginform_label_ldapserver',_('LDAP server'));
1168 $ldapservers_name=array();
1169 $ldapservers_index=array();
1170 foreach(LSconfig :: get('ldap_servers') as $id => $infos) {
1171 $ldapservers_index[]=$id;
1172 $ldapservers_name[]=__($infos['name']);
1174 LStemplate :: assign('loginform_ldapservers_name',$ldapservers_name);
1175 LStemplate :: assign('loginform_ldapservers_index',$ldapservers_index);
1177 LStemplate :: assign('loginform_label_level',_('Level'));
1178 LStemplate :: assign('loginform_label_user',_('Identifier'));
1179 LStemplate :: assign('loginform_label_pwd',_('Password'));
1180 LStemplate :: assign('loginform_label_submit',_('Connect'));
1181 LStemplate :: assign('loginform_label_recoverPassword',_('Forgot your password ?'));
1183 self :: setTemplate('login.tpl');
1184 self :: addJSscript('LSsession_login.js');
1188 * Affiche le formulaire de récupération de mot de passe
1190 * Défini les informations pour le template Smarty du formulaire de
1191 * récupération de mot de passe
1193 * @param[in] $infos array() Information sur le status du processus de
1194 * recouvrement de mot de passe
1198 public static function displayRecoverPasswordForm($recoveryPasswordInfos) {
1199 LStemplate :: assign('pagetitle',_('Recovery of your credentials'));
1200 LStemplate :: assign('recoverpasswordform_action','index.php?LSsession_recoverPassword');
1202 if (count(LSconfig :: get('ldap_servers'))==1) {
1203 LStemplate :: assign('recoverpasswordform_ldapserver_style','style="display: none"');
1206 LStemplate :: assign('recoverpasswordform_label_ldapserver',_('LDAP server'));
1207 $ldapservers_name=array();
1208 $ldapservers_index=array();
1209 foreach(LSconfig :: get('ldap_servers') as $id => $infos) {
1210 $ldapservers_index[]=$id;
1211 $ldapservers_name[]=$infos['name'];
1213 LStemplate :: assign('recoverpasswordform_ldapservers_name',$ldapservers_name);
1214 LStemplate :: assign('recoverpasswordform_ldapservers_index',$ldapservers_index);
1216 LStemplate :: assign('recoverpasswordform_label_user',_('Identifier'));
1217 LStemplate :: assign('recoverpasswordform_label_submit',_('Validate'));
1218 LStemplate :: assign('recoverpasswordform_label_back',_('Back'));
1220 $recoverpassword_msg = _('Please fill the identifier field to proceed recovery procedure');
1222 if (isset($recoveryPasswordInfos['recoveryHashMail'])) {
1223 $recoverpassword_msg = getFData(
1224 _("An email has been sent to %{mail}. " .
1225 "Please follow the instructions on it."),
1226 $recoveryPasswordInfos['recoveryHashMail']
1230 if (isset($recoveryPasswordInfos['newPasswordMail'])) {
1231 $recoverpassword_msg = getFData(
1232 _("Your new password has been sent to %{mail}. "),
1233 $recoveryPasswordInfos['newPasswordMail']
1237 LStemplate :: assign('recoverpassword_msg',$recoverpassword_msg);
1239 self :: setTemplate('recoverpassword.tpl');
1240 self :: addJSscript('LSsession_recoverPassword.js');
1244 * Défini le template Smarty à utiliser
1246 * Remarque : les fichiers de templates doivent se trouver dans le dossier
1249 * @param[in] string Le nom du fichier de template
1253 public static function setTemplate($template) {
1254 self :: $template = $template;
1258 * Ajoute un script JS au chargement de la page
1260 * Remarque : les scripts doivents être dans le dossier LS_JS_DIR.
1262 * @param[in] $script Le nom du fichier de script à charger.
1266 public static function addJSscript($file,$path=NULL) {
1271 self :: $JSscripts[$path.$file]=$script;
1275 * Ajouter un paramètre de configuration Javascript
1277 * @param[in] $name string Nom de la variable de configuration
1278 * @param[in] $val mixed Valeur de la variable de configuration
1282 public static function addJSconfigParam($name,$val) {
1283 self :: $_JSconfigParams[$name]=$val;
1287 * Ajoute une feuille de style au chargement de la page
1289 * @param[in] $script Le nom du fichier css à charger.
1293 public static function addCssFile($file,$path=NULL) {
1295 $file = $path.$file;
1298 $file = LStemplate :: getCSSPath($file);
1300 self :: $CssFiles[$file]=$file;
1304 * Affiche le template Smarty
1306 * Charge les dépendances et affiche le template Smarty
1310 public static function displayTemplate() {
1313 foreach ($GLOBALS['defaultJSscipts'] as $script) {
1314 $JSscript_txt.="<script src='".LS_JS_DIR.$script."' type='text/javascript'></script>\n";
1317 foreach (self :: $JSscripts as $script) {
1318 if (!$script['path']) {
1319 $script['path']=LS_JS_DIR;
1322 $script['path'].='/';
1324 $JSscript_txt.="<script src='".$script['path'].$script['file']."' type='text/javascript'></script>\n";
1327 $KAconf = LSconfig :: get('keepLSsessionActive');
1330 (!isset(self :: $ldapServer['keepLSsessionActive']))
1332 (!($KAconf === false))
1335 (self :: $ldapServer['keepLSsessionActive'])
1337 self :: addJSconfigParam('keepLSsessionActive',ini_get('session.gc_maxlifetime'));
1340 LStemplate :: assign('LSjsConfig',json_encode(self :: $_JSconfigParams));
1343 $JSscript_txt.="<script type='text/javascript'>LSdebug_active = 1;</script>\n";
1346 $JSscript_txt.="<script type='text/javascript'>LSdebug_active = 0;</script>\n";
1349 LStemplate :: assign('LSsession_js',$JSscript_txt);
1352 self :: addCssFile("LSdefault.css");
1354 foreach (self :: $CssFiles as $file) {
1355 $Css_txt.="<link rel='stylesheet' type='text/css' href='".$file."' />\n";
1357 LStemplate :: assign('LSsession_css',$Css_txt);
1359 if (isset(self :: $LSaccess[self :: $topDn])) {
1360 LStemplate :: assign('LSaccess',self :: $LSaccess[self :: $topDn]);
1364 $listTopDn = self :: getSubDnLdapServer();
1365 if (is_array($listTopDn)) {
1367 LStemplate :: assign('label_level',self :: getSubDnLabel());
1368 LStemplate :: assign('_refresh',_('Refresh'));
1369 $LSsession_topDn_index = array();
1370 $LSsession_topDn_name = array();
1371 foreach($listTopDn as $index => $name) {
1372 $LSsession_topDn_index[] = $index;
1373 $LSsession_topDn_name[] = $name;
1375 LStemplate :: assign('LSsession_subDn_indexes',$LSsession_topDn_index);
1376 LStemplate :: assign('LSsession_subDn_names',$LSsession_topDn_name);
1377 LStemplate :: assign('LSsession_subDn',self :: $topDn);
1378 LStemplate :: assign('LSsession_subDnName',self :: getSubDnName());
1381 LStemplate :: assign('LSlanguages',self :: getLangList());
1382 LStemplate :: assign('LSlang',self :: $lang);
1383 LStemplate :: assign('LSencoding',self :: $encoding);
1384 LStemplate :: assign('lang_label',_('Language'));
1386 LStemplate :: assign('displayLogoutBtn',LSauth :: displayLogoutBtn());
1387 LStemplate :: assign('displaySelfAccess',LSauth :: displaySelfAccess());
1390 if((!empty($_SESSION['LSsession_infos']))&&(is_array($_SESSION['LSsession_infos']))) {
1391 $txt_infos="<ul>\n";
1392 foreach($_SESSION['LSsession_infos'] as $info) {
1393 $txt_infos.="<li>$info</li>\n";
1395 $txt_infos.="</ul>\n";
1396 LStemplate :: assign('LSinfos',$txt_infos);
1397 $_SESSION['LSsession_infos']=array();
1400 if (self :: $ajaxDisplay) {
1401 LStemplate :: assign('LSerror_txt',LSerror :: getErrors());
1402 LStemplate :: assign('LSdebug_txt',LSdebug_print(true));
1405 LSerror :: display();
1408 if (!self :: $template)
1409 self :: setTemplate('empty.tpl');
1411 LStemplate :: assign('connected_as',_("Connected as"));
1413 LStemplate :: display(self :: $template);
1417 * Défini que l'affichage se fera ou non via un retour Ajax
1419 * @param[in] $val boolean True pour que l'affichage se fasse par un retour
1423 public static function setAjaxDisplay($val=true) {
1424 self :: $ajaxDisplay = (boolean)$val;
1428 * Affiche un retour Ajax
1432 public static function displayAjaxReturn($data=array()) {
1433 if (isset($data['LSredirect']) && (!LSdebugDefined()) ) {
1434 echo json_encode($data);
1438 $data['LSjsConfig'] = self :: $_JSconfigParams;
1441 if((!empty($_SESSION['LSsession_infos']))&&(is_array($_SESSION['LSsession_infos']))) {
1442 $txt_infos="<ul>\n";
1443 foreach($_SESSION['LSsession_infos'] as $info) {
1444 $txt_infos.="<li>$info</li>\n";
1446 $txt_infos.="</ul>\n";
1447 $data['LSinfos'] = $txt_infos;
1448 $_SESSION['LSsession_infos']=array();
1451 if (LSerror :: errorsDefined()) {
1452 $data['LSerror'] = LSerror :: getErrors();
1455 if (isset($_REQUEST['imgload'])) {
1456 $data['imgload'] = $_REQUEST['imgload'];
1459 if (LSdebugDefined()) {
1460 $data['LSdebug'] = LSdebug_print(true,false);
1463 echo json_encode($data);
1467 * Retournne un template Smarty compilé
1469 * @param[in] string $template Le template à retourner
1470 * @param[in] array $variables Variables Smarty à assigner avant l'affichage
1472 * @retval string Le HTML compilé du template
1474 public static function fetchTemplate($template,$variables=array()) {
1475 foreach($variables as $name => $val) {
1476 LStemplate :: assign($name,$val);
1478 return LStemplate :: fetch($template);
1482 * Charge les droits LS de l'utilisateur
1484 * @retval boolean True si le chargement à réussi, false sinon.
1486 private static function loadLSprofiles() {
1487 if (is_array(self :: $ldapServer['LSprofiles'])) {
1488 foreach (self :: $ldapServer['LSprofiles'] as $profile => $profileInfos) {
1489 if (is_array($profileInfos)) {
1490 foreach ($profileInfos as $topDn => $rightsInfos) {
1492 * If $topDn == 'LSobject', we search for each LSobject type to find
1493 * all items on witch the user will have powers.
1495 if ($topDn == 'LSobjects') {
1496 if (is_array($rightsInfos)) {
1497 foreach ($rightsInfos as $LSobject => $listInfos) {
1498 if (self :: loadLSclass('LSsearch')) {
1499 if (isset($listInfos['filter'])) {
1500 $filter = self :: getLSuserObject() -> getFData($listInfos['filter']);
1503 $filter = '('.$listInfos['attr'].'='.self :: getLSuserObject() -> getFData($listInfos['attr_value']).')';
1507 'basedn' => (isset($listInfos['basedn'])?$listInfos['basedn']:null),
1511 if (isset($listInfos['params']) && is_array($listInfos['params'])) {
1512 $params = array_merge($listInfos['params'],$params);
1515 $LSsearch = new LSsearch($LSobject,'LSsession :: loadLSprofiles',$params,true);
1516 $LSsearch -> run(false);
1518 $DNs = $LSsearch -> listObjectsDn();
1519 if (!is_array(self :: $LSprofiles[$profile])) {
1520 self :: $LSprofiles[$profile]=$DNs;
1523 foreach($DNs as $dn) {
1524 if (!in_array($dn,self :: $LSprofiles[$profile])) {
1525 self :: $LSprofiles[$profile][] = $dn;
1533 LSdebug('LSobjects => [] doit etre un tableau');
1537 if (is_array($rightsInfos)) {
1538 foreach($rightsInfos as $dn => $conf) {
1539 if ((isset($conf['attr'])) && (isset($conf['LSobject']))) {
1540 if( self :: loadLSobject($conf['LSobject']) ) {
1541 if ($object = new $conf['LSobject']()) {
1542 if ($object -> loadData($dn)) {
1543 $listDns=$object -> getValue($conf['attr']);
1544 $valKey = (isset($conf['attr_value']))?$conf['attr_value']:'%{dn}';
1545 $val = self :: getLSuserObject() -> getFData($valKey);
1546 if (is_array($listDns)) {
1547 if (in_array($val,$listDns)) {
1548 self :: $LSprofiles[$profile][] = $topDn;
1553 LSdebug('Impossible de chargé le dn : '.$dn);
1557 LSdebug('Impossible de créer l\'objet de type : '.$conf['LSobject']);
1562 if (self :: $dn == $dn) {
1563 self :: $LSprofiles[$profile][] = $topDn;
1569 if ( self :: $dn == $rightsInfos ) {
1570 self :: $LSprofiles[$profile][] = $topDn;
1573 } // fin else ($topDn == 'LSobjects')
1574 } // fin foreach($profileInfos)
1575 } // fin is_array($profileInfos)
1576 } // fin foreach LSprofiles
1577 LSdebug(self :: $LSprofiles);
1586 * Charge les droits d'accès de l'utilisateur pour construire le menu de l'interface
1590 private static function loadLSaccess() {
1592 if (isset(self :: $ldapServer['subDn']) && is_array(self :: $ldapServer['subDn'])) {
1593 foreach(self :: $ldapServer['subDn'] as $name => $config) {
1594 if ($name=='LSobject') {
1595 if (is_array($config)) {
1597 // Définition des subDns
1598 foreach($config as $objectType => $objectConf) {
1599 if (self :: loadLSobject($objectType)) {
1600 if ($subdnobject = new $objectType()) {
1601 $tbl = $subdnobject -> getSelectArray(NULL,self::getRootDn(),NULL,NULL,false);
1602 if (is_array($tbl)) {
1603 // Définition des accès
1605 if (is_array($objectConf['LSobjects'])) {
1606 foreach($objectConf['LSobjects'] as $type) {
1607 if (self :: loadLSobject($type)) {
1608 if (self :: canAccess($type)) {
1609 $access[$type] = LSconfig :: get('LSobjects.'.$type.'.label');
1614 foreach($tbl as $dn => $dn_name) {
1615 $LSaccess[$dn]=$access;
1624 if ((isCompatibleDNs(self :: $ldapServer['ldap_config']['basedn'],$config['dn']))&&($config['dn']!='')) {
1626 if (is_array($config['LSobjects'])) {
1627 foreach($config['LSobjects'] as $objectType) {
1628 if (self :: loadLSobject($objectType)) {
1629 if (self :: canAccess($objectType)) {
1630 $access[$objectType] = LSconfig :: get('LSobjects.'.$objectType.'.label');
1635 $LSaccess[$config['dn']]=$access;
1641 if(is_array(self :: $ldapServer['LSaccess'])) {
1643 foreach(self :: $ldapServer['LSaccess'] as $objectType) {
1644 if (self :: loadLSobject($objectType)) {
1645 if (self :: canAccess($objectType)) {
1646 $access[$objectType] = LSconfig :: get('LSobjects.'.$objectType.'.label');
1650 $LSaccess[self :: $topDn] = $access;
1653 if (LSauth :: displaySelfAccess()) {
1654 foreach($LSaccess as $dn => $access) {
1655 $LSaccess[$dn] = array_merge(
1657 'SELF' => 'My account'
1663 self :: $LSaccess = $LSaccess;
1664 $_SESSION['LSsession']['LSaccess'] = $LSaccess;
1668 * Dit si l'utilisateur est du profil pour le DN spécifié
1670 * @param[in] string $profile de l'objet
1671 * @param[in] string $dn DN de l'objet
1673 * @retval boolean True si l'utilisateur est du profil sur l'objet, false sinon.
1675 public static function isLSprofile($dn,$profile) {
1676 if (is_array(self :: $LSprofiles[$profile])) {
1677 foreach(self :: $LSprofiles[$profile] as $topDn) {
1681 else if ( isCompatibleDNs($dn,$topDn) ) {
1690 * Retourne qui est l'utilisateur par rapport à l'object
1692 * @param[in] string Le DN de l'objet
1694 * @retval string 'admin'/'self'/'user' pour Admin , l'utilisateur lui même ou un simple utilisateur
1696 public static function whoami($dn) {
1697 $retval = array('user');
1699 foreach(self :: $LSprofiles as $profile => $infos) {
1700 if(self :: isLSprofile($dn,$profile)) {
1705 if (self :: $dn == $dn) {
1713 * Retourne le droit de l'utilisateur à accèder à un objet
1715 * @param[in] string $LSobject Le type de l'objet
1716 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1717 * @param[in] string $right Le type de droit d'accès à tester ('r'/'w')
1718 * @param[in] string $attr Le nom de l'attribut auquel on test l'accès
1720 * @retval boolean True si l'utilisateur a accès, false sinon
1722 public static function canAccess($LSobject,$dn=NULL,$right=NULL,$attr=NULL) {
1723 if (!self :: loadLSobject($LSobject)) {
1727 $whoami = self :: whoami($dn);
1728 if ($dn==self :: getLSuserObject() -> getValue('dn')) {
1729 if (!self :: in_menu('SELF')) {
1734 $obj = new $LSobject();
1736 if (!self :: in_menu($LSobject,$obj -> subDnValue)) {
1742 $objectdn=LSconfig :: get('LSobjects.'.$LSobject.'.container_dn').','.self :: $topDn;
1743 $whoami = self :: whoami($objectdn);
1746 // Pour un attribut particulier
1749 $attr=LSconfig :: get('LSobjects.'.$LSobject.'.rdn');
1751 if (!is_array(LSconfig :: get('LSobjects.'.$LSobject.'.attrs.'.$attr))) {
1756 foreach($whoami as $who) {
1757 $nr = LSconfig :: get('LSobjects.'.$LSobject.'.attrs.'.$attr.'.rights.'.$who);
1761 else if($nr == 'r') {
1768 if (($right=='r')||($right=='w')) {
1775 if ( ($r=='r') || ($r=='w') ) {
1782 // Pour un attribut quelconque
1783 $attrs_conf=LSconfig :: get('LSobjects.'.$LSobject.'.attrs');
1784 if (is_array($attrs_conf)) {
1785 if (($right=='r')||($right=='w')) {
1786 foreach($whoami as $who) {
1787 foreach ($attrs_conf as $attr_name => $attr_config) {
1788 if (isset($attr_config['rights'][$who]) && $attr_config['rights'][$who]==$right) {
1795 foreach($whoami as $who) {
1796 foreach ($attrs_conf as $attr_name => $attr_config) {
1797 if ( (isset($attr_config['rights'][$who])) && ( ($attr_config['rights'][$who]=='r') || ($attr_config['rights'][$who]=='w') ) ) {
1808 * Retourne le droit de l'utilisateur à editer à un objet
1810 * @param[in] string $LSobject Le type de l'objet
1811 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1812 * @param[in] string $attr Le nom de l'attribut auquel on test l'accès
1814 * @retval boolean True si l'utilisateur a accès, false sinon
1816 public static function canEdit($LSobject,$dn=NULL,$attr=NULL) {
1817 return self :: canAccess($LSobject,$dn,'w',$attr);
1821 * Retourne le droit de l'utilisateur à supprimer un objet
1823 * @param[in] string $LSobject Le type de l'objet
1824 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1826 * @retval boolean True si l'utilisateur a accès, false sinon
1828 public static function canRemove($LSobject,$dn) {
1829 return self :: canAccess($LSobject,$dn,'w','rdn');
1833 * Retourne le droit de l'utilisateur à créer un objet
1835 * @param[in] string $LSobject Le type de l'objet
1837 * @retval boolean True si l'utilisateur a accès, false sinon
1839 public static function canCreate($LSobject) {
1840 if (!self :: loadLSobject($LSobject)) {
1843 if (LSconfig :: get("LSobjects.$LSobject.disable_creation")) {
1846 return self :: canAccess($LSobject,NULL,'w','rdn');
1850 * Retourne le droit de l'utilisateur à gérer la relation d'objet
1852 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1853 * @param[in] string $LSobject Le type de l'objet
1854 * @param[in] string $relationName Le nom de la relation avec l'objet
1855 * @param[in] string $right Le type de droit a vérifier ('r' ou 'w')
1857 * @retval boolean True si l'utilisateur a accès, false sinon
1859 public static function relationCanAccess($dn,$LSobject,$relationName,$right=NULL) {
1860 $relConf=LSconfig :: get('LSobjects.'.$LSobject.'.LSrelation.'.$relationName);
1861 if (!is_array($relConf))
1863 $whoami = self :: whoami($dn);
1865 if (($right=='w') || ($right=='r')) {
1867 foreach($whoami as $who) {
1868 $nr = ((isset($relConf['rights'][$who]))?$relConf['rights'][$who]:'');
1872 else if($nr == 'r') {
1884 foreach($whoami as $who) {
1885 if ((isset($relConf['rights'][$who])) && ( ($relConf['rights'][$who] == 'w') || ($relConf['rights'][$who] == 'r') ) ) {
1894 * Retourne le droit de l'utilisateur à modifier la relation d'objet
1896 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1897 * @param[in] string $LSobject Le type de l'objet
1898 * @param[in] string $relationName Le nom de la relation avec l'objet
1900 * @retval boolean True si l'utilisateur a accès, false sinon
1902 public static function relationCanEdit($dn,$LSobject,$relationName) {
1903 return self :: relationCanAccess($dn,$LSobject,$relationName,'w');
1907 * Retourne le droit de l'utilisateur a executer une customAction
1909 * @param[in] string $dn Le DN de l'objet
1910 * @param[in] string $LSobject Le type de l'objet
1911 * @param[in] string $customActionName Le nom de la customAction
1913 * @retval boolean True si l'utilisateur peut executer cette customAction, false sinon
1915 public static function canExecuteCustomAction($dn,$LSobject,$customActionName) {
1916 $conf=LSconfig :: get('LSobjects.'.$LSobject.'.customActions.'.$customActionName);
1917 if (!is_array($conf))
1919 $whoami = self :: whoami($dn);
1921 if (isset($conf['rights']) && is_array($conf['rights'])) {
1922 foreach($whoami as $who) {
1923 if (in_array($who,$conf['rights'])) {
1933 * Retourne le droit de l'utilisateur a executer une customAction
1936 * @param[in] string $LSsearch L'objet LSsearch
1937 * @param[in] string $customActionName Le nom de la customAction
1939 * @retval boolean True si l'utilisateur peut executer cette customAction, false sinon
1941 public static function canExecuteLSsearchCustomAction($LSsearch,$customActionName) {
1942 $conf=LSconfig :: get('LSobjects.'.$LSsearch -> LSobject.'.LSsearch.customActions.'.$customActionName);
1943 if (!is_array($conf))
1945 $dn=$LSsearch -> basedn;
1946 if (is_null($dn)) $dn=self::getTopDn();
1948 $whoami = self :: whoami($dn);
1950 if (isset($conf['rights']) && is_array($conf['rights'])) {
1951 foreach($whoami as $who) {
1952 if (in_array($who,$conf['rights'])) {
1962 * Ajoute un fichier temporaire
1964 * @author Benjamin Renard <brenard@easter-eggs.com>
1968 public static function addTmpFile($value,$filePath) {
1969 $hash = mhash(MHASH_MD5,$value);
1970 self :: $tmp_file[$filePath] = $hash;
1971 $_SESSION['LSsession']['tmp_file'][$filePath] = $hash;
1975 * Retourne le chemin du fichier temporaire si l'existe
1977 * @author Benjamin Renard <brenard@easter-eggs.com>
1979 * @param[in] $value La valeur du fichier
1983 public static function tmpFileExist($value) {
1984 $hash = mhash(MHASH_MD5,$value);
1985 foreach(self :: $tmp_file as $filePath => $contentHash) {
1986 if ($hash == $contentHash) {
1994 * Retourne le chemin du fichier temporaire
1996 * Retourne le chemin du fichier temporaire qu'il créera à partir de la valeur
1997 * s'il n'existe pas déjà .
1999 * @author Benjamin Renard <brenard@easter-eggs.com>
2001 * @param[in] $value La valeur du fichier
2005 public static function getTmpFile($value) {
2006 $exist = self :: tmpFileExist($value);
2008 $img_path = LS_TMP_DIR .rand().'.tmp';
2009 $fp = fopen($img_path, "w");
2010 fwrite($fp, $value);
2012 self :: addTmpFile($value,$img_path);
2021 * Supprime les fichiers temporaires
2023 * @author Benjamin Renard <brenard@easter-eggs.com>
2027 public static function deleteTmpFile($filePath=NULL) {
2030 unset(self :: $tmp_file[$filePath]);
2031 unset($_SESSION['LSsession']['tmp_file'][$filePath]);
2034 foreach(self :: $tmp_file as $file => $content) {
2037 self :: $tmp_file = array();
2038 $_SESSION['LSsession']['tmp_file'] = array();
2043 * Retourne true si le cache des droits est activé
2045 * @author Benjamin Renard <brenard@easter-eggs.com>
2047 * @retval boolean True si le cache des droits est activé, false sinon.
2049 public static function cacheLSprofiles() {
2050 return ( (LSconfig :: get('cacheLSprofiles')) || (self :: $ldapServer['cacheLSprofiles']) );
2054 * Retourne true si le cache des subDn est activé
2056 * @author Benjamin Renard <brenard@easter-eggs.com>
2058 * @retval boolean True si le cache des subDn est activé, false sinon.
2060 public static function cacheSudDn() {
2061 return ( (LSconfig :: get('cacheSubDn')) || (self :: $ldapServer['cacheSubDn']));
2065 * Retourne true si le cache des recherches est activé
2067 * @author Benjamin Renard <brenard@easter-eggs.com>
2069 * @retval boolean True si le cache des recherches est activé, false sinon.
2071 public static function cacheSearch() {
2072 return ( (LSconfig :: get('cacheSearch')) || (self :: $ldapServer['cacheSearch']));
2076 * Retourne le label des niveaux pour le serveur ldap courant
2078 * @author Benjamin Renard <brenard@easter-eggs.com>
2080 * @retval string Le label des niveaux pour le serveur ldap dourant
2082 public static function getSubDnLabel() {
2083 return (self :: $ldapServer['subDnLabel']!='')?__(self :: $ldapServer['subDnLabel']):_('Level');
2087 * Retourne le nom du subDn
2089 * @param[in] $subDn string subDn
2091 * @retval string Le nom du subDn ou '' sinon
2093 public static function getSubDnName($subDn=false) {
2095 $subDn = self :: $topDn;
2097 if (self :: getSubDnLdapServer(false)) {
2098 if (isset(self :: $_subDnLdapServer[self :: $ldapServerId][false][$subDn])) {
2099 return self :: $_subDnLdapServer[self :: $ldapServerId][false][$subDn];
2106 * L'objet est t-il utilisé pour listé les subDnS
2108 * @param[in] $type string Le type d'objet
2110 * @retval boolean true si le type d'objet est un subDnObject, false sinon
2112 public static function isSubDnLSobject($type) {
2114 if (isset(self :: $ldapServer['subDn']['LSobject']) && is_array(self :: $ldapServer['subDn']['LSobject'])) {
2115 foreach(self :: $ldapServer['subDn']['LSobject'] as $key => $value) {
2125 * Indique si un type d'objet est dans le menu courant
2127 * @retval boolean true si le type d'objet est dans le menu, false sinon
2129 public static function in_menu($LSobject,$topDn=NULL) {
2131 $topDn=self :: $topDn;
2133 return isset(self :: $LSaccess[$topDn][$LSobject]);
2137 * Indique si le serveur LDAP courant a des subDn
2139 * @retval boolean true si le serveur LDAP courant a des subDn, false sinon
2141 public static function haveSubDn() {
2142 return (isset(self :: $ldapServer['subDn']) && is_array(self :: $ldapServer['subDn']));
2146 * Ajoute une information à afficher
2148 * @param[in] $msg string Le message à afficher
2152 public static function addInfo($msg) {
2153 $_SESSION['LSsession_infos'][]=$msg;
2157 * Redirection de l'utilisateur vers une autre URL
2159 * @param[in] $url string L'URL
2160 * @param[in] $exit boolean Si true, l'execution script s'arrête après la redirection
2164 public static function redirect($url,$exit=true) {
2165 LStemplate :: assign('url',$url);
2166 LStemplate :: display('redirect.tpl');
2173 * Retourne l'adresse mail d'emission configurée pour le serveur courant
2175 * @retval string Adresse mail d'emission
2177 public static function getEmailSender() {
2178 return self :: $ldapServer['emailSender'];
2182 * Ajout d'une information d'aide
2184 * @param[in] $group string Le nom du groupe d'infos dans lequels ajouter
2186 * @param[in] $infos array Tableau array(name => value) des infos
2190 public static function addHelpInfos($group,$infos) {
2191 if (is_array($infos)) {
2192 if (isset(self :: $_JSconfigParams['helpInfos'][$group]) && is_array(self :: $_JSconfigParams['helpInfos'][$group])) {
2193 self :: $_JSconfigParams['helpInfos'][$group] = array_merge(self :: $_JSconfigParams['helpInfos'][$group],$infos);
2196 self :: $_JSconfigParams['helpInfos'][$group] = $infos;
2202 * Défini les codes erreur relative à la classe LSsession
2206 private static function defineLSerrors() {
2210 LSerror :: defineError('LSsession_01',
2211 _("LSsession : The constant %{const} is not defined.")
2213 LSerror :: defineError('LSsession_02',
2214 _("LSsession : The %{addon} support is uncertain. Verify system compatibility and the add-on configuration.")
2216 LSerror :: defineError('LSsession_03',
2217 _("LSsession : LDAP server's configuration data are invalid. Can't connect.")
2219 LSerror :: defineError('LSsession_04',
2220 _("LSsession : Failed to load LSobject type %{type} : unknon type.")
2222 LSerror :: defineError('LSsession_05',
2223 _("LSsession : Failed to load LSclass %{class}.")
2225 LSerror :: defineError('LSsession_06',
2226 _("LSsession : Login or password incorrect.")
2228 LSerror :: defineError('LSsession_07',
2229 _("LSsession : Impossible to identify you : Duplication of identities.")
2231 LSerror :: defineError('LSsession_08',
2232 _("LSsession : Can't load class of authentification (%{class}).")
2234 LSerror :: defineError('LSsession_09',
2235 _("LSsession : Can't connect to LDAP server.")
2237 LSerror :: defineError('LSsession_10',
2238 _("LSsession : Impossible to authenticate you.")
2240 LSerror :: defineError('LSsession_11',
2241 _("LSsession : Your are not authorized to do this action.")
2243 LSerror :: defineError('LSsession_12',
2244 _("LSsession : Some informations are missing to display this page.")
2246 LSerror :: defineError('LSsession_13',
2247 _("LSsession : The function of the custom action %{name} does not exists or is not configured.")
2249 LSerror :: defineError('LSsession_14',
2250 _("LSsession : Fail to retreive user's LDAP credentials from LSauth.")
2252 LSerror :: defineError('LSsession_15',
2253 _("LSsession : Fail to reconnect to LDAP server with user's LDAP credentials.")
2255 // 16 : not yet used
2256 LSerror :: defineError('LSsession_17',
2257 _("LSsession : Error during creation of list of levels. Contact administrators. (Code : %{code})")
2259 LSerror :: defineError('LSsession_18',
2260 _("LSsession : The password recovery is disabled for this LDAP server.")
2262 LSerror :: defineError('LSsession_19',
2263 _("LSsession : Some informations are missing to recover your password. Contact administrators.")
2265 LSerror :: defineError('LSsession_20',
2266 _("LSsession : Error during password recovery. Contact administrators.(Step : %{step})")
2268 // 21 : not yet used
2269 LSerror :: defineError('LSsession_22',
2270 _("LSsession : problem during initialisation.")
2275 * Ajax method when change ldapserver on login form
2277 * @param[in] $data array The return data address
2281 public static function ajax_onLdapServerChangedLogin(&$data) {
2282 if ( isset($_REQUEST['server']) ) {
2283 self :: setLdapServer($_REQUEST['server']);
2285 if ( self :: LSldapConnect() ) {
2286 if (session_id()=="") session_start();
2287 if (isset($_SESSION['LSsession_topDn'])) {
2288 $sel = $_SESSION['LSsession_topDn'];
2293 $list = self :: getSubDnLdapServerOptions($sel,true);
2294 if (is_string($list)) {
2295 $data['list_topDn'] = "<select name='LSsession_topDn' id='LSsession_topDn'>".$list."</select>";
2296 $data['subDnLabel'] = self :: getSubDnLabel();
2299 $data['recoverPassword'] = isset(self :: $ldapServer['recoverPassword']);
2304 * Ajax method when change ldapserver on recoverPassword form
2306 * @param[in] $data array The return data address
2310 public static function ajax_onLdapServerChangedRecoverPassword(&$data) {
2311 if ( isset($_REQUEST['server']) ) {
2312 self :: setLdapServer($_REQUEST['server']);
2313 $data=array('recoverPassword' => isset(self :: $ldapServer['recoverPassword']));