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;
88 * Include un fichier PHP
90 * @author Benjamin Renard <brenard@easter-eggs.com>
92 * @retval true si tout c'est bien passé, false sinon
94 public static function includeFile($file) {
95 if (!file_exists($file)) {
98 if (defined('LSdebug') && constant('LSdebug')) {
99 return include_once($file);
102 return @include_once($file);
108 * Lancement de LSconfig
110 * @author Benjamin Renard <brenard@easter-eggs.com>
112 * @retval true si tout c'est bien passé, false sinon
114 private static function startLSconfig() {
115 if (self :: loadLSclass('LSconfig')) {
116 if (LSconfig :: start()) {
120 die("ERROR : Can't load configuration files.");
125 * Lancement et initialisation de Smarty
127 * @author Benjamin Renard <brenard@easter-eggs.com>
129 * @retval true si tout c'est bien passé, false sinon
131 private static function startLStemplate() {
132 if ( self :: includeFile(LSconfig :: get('Smarty')) ) {
133 $GLOBALS['Smarty'] = new Smarty();
134 $GLOBALS['Smarty'] -> template_dir = LS_TEMPLATES_DIR;
135 $GLOBALS['Smarty'] -> compile_dir = LS_TMP_DIR;
138 $GLOBALS['Smarty'] -> caching = 0;
139 // cache files are always regenerated
140 $GLOBALS['Smarty'] -> force_compile = TRUE;
141 // recompile template if it is changed
142 $GLOBALS['Smarty'] -> compile_check = TRUE;
143 if (isset($_REQUEST['debug_smarty'])) {
145 $GLOBALS['Smarty'] -> debugging = true;
149 $GLOBALS['Smarty'] -> register_function('getFData','smarty_getFData');
151 $GLOBALS['Smarty'] -> assign('LS_CSS_DIR',LS_CSS_DIR);
152 $GLOBALS['Smarty'] -> assign('LS_IMAGES_DIR',LS_IMAGES_DIR);
154 self :: addJSconfigParam('LS_IMAGES_DIR',LS_IMAGES_DIR);
157 die("ERROR : Can't load Smarty.");
162 * Retourne le topDn de la session
164 * @author Benjamin Renard <brenard@easter-eggs.com>
166 * @retval string le topDn de la session
168 public static function getTopDn() {
169 if (!is_null(self :: $topDn)) {
170 return self :: $topDn;
173 return self :: getRootDn();
178 * Retourne le rootDn de la session
180 * @author Benjamin Renard <brenard@easter-eggs.com>
182 * @retval string le rootDn de la session
184 public static function getRootDn() {
185 return self :: $ldapServer['ldap_config']['basedn'];
189 * Initialisation de la gestion des erreurs
191 * Création de l'objet LSerror
193 * @author Benjamin Renard <brenard@easter-eggs.com
195 * @retval boolean true si l'initialisation a réussi, false sinon.
197 private static function startLSerror() {
198 if(!self :: loadLSclass('LSerror')) {
201 self :: defineLSerrors();
206 * Chargement d'une classe d'LdapSaisie
208 * @param[in] $class Nom de la classe à charger (Exemple : LSpeople)
209 * @param[in] $type (Optionnel) Type de classe à charger (Exemple : LSobjects)
211 * @author Benjamin Renard <brenard@easter-eggs.com
213 * @retval boolean true si le chargement a réussi, false sinon.
215 public static function loadLSclass($class,$type='') {
216 if (class_exists($class))
220 return self :: includeFile(LS_CLASS_DIR .'class.'.$type.$class.'.php');
224 * Chargement d'un object LdapSaisie
226 * @param[in] $object Nom de l'objet à charger
228 * @retval boolean true si le chargement a réussi, false sinon.
230 public static function loadLSobject($object) {
231 if(class_exists($object)) {
235 self :: loadLSclass('LSldapObject');
236 if (!self :: loadLSclass($object,'LSobjects')) {
239 if (!self :: includeFile( LS_OBJECTS_DIR . 'config.LSobjects.'.$object.'.php' )) {
243 if (!LSconfig :: set("LSobjects.$object",$GLOBALS['LSobjects'][$object])) {
246 else if (isset($GLOBALS['LSobjects'][$object]['LSaddons'])){
247 if (is_array($GLOBALS['LSobjects'][$object]['LSaddons'])) {
248 foreach ($GLOBALS['LSobjects'][$object]['LSaddons'] as $addon) {
249 if (!self :: loadLSaddon($addon)) {
255 if (!self :: loadLSaddon($GLOBALS['LSobjects'][$object]['LSaddons'])) {
262 LSerror :: addErrorCode('LSsession_04',$object);
269 * Chargement d'un addons d'LdapSaisie
271 * @param[in] $addon Nom de l'addon à charger (Exemple : samba)
273 * @author Benjamin Renard <brenard@easter-eggs.com
275 * @retval boolean true si le chargement a réussi, false sinon.
277 public static function loadLSaddon($addon) {
278 if(self :: includeFile(LS_ADDONS_DIR .'LSaddons.'.$addon.'.php')) {
279 self :: includeFile(LS_CONF_DIR."LSaddons/config.LSaddons.".$addon.".php");
280 if (!call_user_func('LSaddon_'. $addon .'_support')) {
281 LSerror :: addErrorCode('LSsession_02',$addon);
290 * Chargement d'une classe d'authentification d'LdapSaisie
292 * @author Benjamin Renard <brenard@easter-eggs.com
294 * @retval boolean true si le chargement a reussi, false sinon.
296 public static function loadLSauth() {
297 if (self :: loadLSclass('LSauth')) {
301 LSerror :: addErrorCode('LSsession_05','LSauth');
307 * Chargement des addons LdapSaisie
309 * Chargement des LSaddons contenue dans la variable
310 * $GLOBALS['LSaddons']['loads']
312 * @retval boolean true si le chargement a réussi, false sinon.
314 public static function loadLSaddons() {
315 $conf=LSconfig :: get('LSaddons.loads');
316 if(!is_array($conf)) {
317 LSerror :: addErrorCode('LSsession_01',"LSaddons['loads']");
321 foreach ($conf as $addon) {
322 self :: loadLSaddon($addon);
332 public static function setLocale() {
333 if (isset($_REQUEST['lang'])) {
334 $lang = $_REQUEST['lang'];
336 elseif (isset($_SESSION['LSlang'])) {
337 $lang = $_SESSION['LSlang'];
339 elseif (isset(self :: $ldapServer['lang'])) {
340 $lang = self :: $ldapServer['lang'];
343 $lang = LSconfig :: get('lang');
346 if (isset($_REQUEST['encoding'])) {
347 $encoding = $_REQUEST['encoding'];
349 elseif (isset($_SESSION['LSencoding'])) {
350 $encoding = $_SESSION['LSencoding'];
352 elseif (isset(self :: $ldapServer['encoding'])) {
353 $encoding = self :: $ldapServer['encoding'];
356 $encoding = LSconfig :: get('encoding');
359 $_SESSION['LSlang']=$lang;
361 $_SESSION['LSencoding']=$encoding;
362 self :: $encoding=$encoding;
365 if (self :: localeExist($lang,$encoding)) {
367 $lang.='.'.$encoding;
369 setlocale(LC_ALL, $lang);
370 bindtextdomain(LS_TEXT_DOMAIN, LS_I18N_DIR);
371 textdomain(LS_TEXT_DOMAIN);
373 if (is_file(LS_I18N_DIR.'/'.$lang.'/lang.php')) {
374 include(LS_I18N_DIR.'/'.$lang.'/lang.php');
378 if ($encoding && $lang) {
379 $lang.='.'.$encoding;
381 LSdebug('La locale "'.$lang.'" n\'existe pas, utilisation de la locale par défaut.');
386 * Retourne la liste des langues disponibles
388 * @retval array Tableau/Liste des langues disponibles
390 public static function getLangList() {
391 $list=array('en_US');
392 if (self :: $encoding) {
393 $regex = '^([a-zA-Z_]*)\.'.self :: $encoding.'$';
396 $regex = '^([a-zA-Z_]*)$';
398 if ($handle = opendir(LS_I18N_DIR)) {
399 while (false !== ($file = readdir($handle))) {
400 if(is_dir(LS_I18N_DIR.'/'.$file)) {
401 if (ereg($regex,$file,$regs)) {
402 if (!in_array($regs[1],$list)) {
413 * Retourne la langue courante de la session
415 * @param[in] boolean Si true, le code langue retourné sera court
417 * @retval string La langue de la session
419 public static function getLang($short=false) {
421 return strtolower(self :: $lang[0].self :: $lang[1]);
423 return self :: $lang;
427 * Vérifie si une locale est disponible
429 * @param[in] $lang string La langue (Ex : fr_FR)
430 * @param[in] $encoding string L'encodage de caractère (Ex : UTF8)
432 * @retval boolean True si la locale est disponible, False sinon
434 public static function localeExist($lang,$encoding) {
435 if ( !$lang && !$encoding ) {
438 $locale=$lang.(($encoding)?'.'.$encoding:'');
439 if ($locale=='en_US.UTF8') {
442 return (is_dir(LS_I18N_DIR.'/'.$locale));
446 * Initialisation LdapSaisie
448 * @retval boolean True si l'initialisation à réussi, false sinon.
450 public static function initialize() {
451 if (!self :: startLSconfig()) {
455 self :: startLStemplate();
461 self :: startLSerror();
462 self :: loadLSaddons();
463 self :: loadLSauth();
468 * Initialisation de la session LdapSaisie
470 * Initialisation d'une LSsession :
471 * - Authentification et activation du mécanisme de session de LdapSaisie
472 * - ou Chargement des paramètres de la session à partir de la variable
473 * $_SESSION['LSsession'].
474 * - ou Destruction de la session en cas de $_GET['LSsession_logout'].
476 * @retval boolean True si l'initialisation à réussi (utilisateur authentifié), false sinon.
478 public static function startLSsession() {
479 if (!self :: initialize()) {
483 if(isset($_SESSION['LSsession']['dn']) && !isset($_GET['LSsession_recoverPassword'])) {
484 LSdebug('LSsession : Session existente');
485 // --------------------- Session existante --------------------- //
486 self :: $topDn = $_SESSION['LSsession']['topDn'];
487 self :: $dn = $_SESSION['LSsession']['dn'];
488 self :: $rdn = $_SESSION['LSsession']['rdn'];
489 self :: $ldapServerId = $_SESSION['LSsession']['ldapServerId'];
490 self :: $tmp_file = $_SESSION['LSsession']['tmp_file'];
492 if ( self :: cacheLSprofiles() && !isset($_REQUEST['LSsession_refresh']) ) {
493 self :: setLdapServer(self :: $ldapServerId);
494 if (!LSauth :: start()) {
495 LSdebug("LSsession : can't start LSauth -> stop");
498 self :: $LSprofiles = $_SESSION['LSsession']['LSprofiles'];
499 self :: $LSaccess = $_SESSION['LSsession']['LSaccess'];
500 if (!self :: LSldapConnect())
504 self :: setLdapServer(self :: $ldapServerId);
505 if (!LSauth :: start()) {
506 LSdebug("LSsession : can't start LSauth -> stop");
509 if (!self :: LSldapConnect())
511 self :: loadLSprofiles();
514 if ( self :: cacheSudDn() && (!isset($_REQUEST['LSsession_refresh'])) ) {
515 self :: $_subDnLdapServer = ((isset($_SESSION['LSsession_subDnLdapServer']))?$_SESSION['LSsession_subDnLdapServer']:NULL);
518 if (!self :: loadLSobject(self :: $ldapServer['authObjectType'])) {
522 if (isset($_GET['LSsession_logout'])) {
526 if (is_array($_SESSION['LSsession']['tmp_file'])) {
527 self :: $tmp_file = $_SESSION['LSsession']['tmp_file'];
529 self :: deleteTmpFile();
530 unset($_SESSION['LSsession']);
532 self :: redirect('index.php');
536 if ( !self :: cacheLSprofiles() || isset($_REQUEST['LSsession_refresh']) ) {
537 self :: loadLSaccess();
540 $GLOBALS['Smarty'] -> assign('LSsession_username',self :: getLSuserObject() -> getDisplayName());
542 if (isset ($_POST['LSsession_topDn']) && $_POST['LSsession_topDn']) {
543 if (self :: validSubDnLdapServer($_POST['LSsession_topDn'])) {
544 self :: $topDn = $_POST['LSsession_topDn'];
545 $_SESSION['LSsession']['topDn'] = $_POST['LSsession_topDn'];
553 // --------------------- Session inexistante --------------------- //
554 if (isset($_GET['LSsession_recoverPassword'])) {
557 // Session inexistante
558 if (isset($_POST['LSsession_ldapserver'])) {
559 self :: setLdapServer($_POST['LSsession_ldapserver']);
562 self :: setLdapServer(0);
565 // Connexion au serveur LDAP
566 if (self :: LSldapConnect()) {
569 if (isset($_POST['LSsession_topDn']) && $_POST['LSsession_topDn'] != '' ){
570 self :: $topDn = $_POST['LSsession_topDn'];
573 self :: $topDn = self :: $ldapServer['ldap_config']['basedn'];
575 $_SESSION['LSsession_topDn']=self :: $topDn;
577 if (!LSauth :: start()) {
578 LSdebug("LSsession : can't start LSauth -> stop");
582 if (isset($_GET['LSsession_recoverPassword'])) {
583 $recoveryPasswordInfos = self :: recoverPasswd(
584 $_REQUEST['LSsession_user'],
585 $_GET['recoveryHash']
589 $LSuserObject = LSauth :: forceAuthentication();
591 // Authentication successful
592 self :: $LSuserObject = $LSuserObject;
593 self :: $dn = $LSuserObject->getValue('dn');
594 self :: $rdn = $LSuserObject->getValue('rdn');
595 self :: loadLSprofiles();
596 self :: loadLSaccess();
597 $GLOBALS['Smarty'] -> assign('LSsession_username',self :: getLSuserObject() -> getDisplayName());
598 $_SESSION['LSsession']=self :: getContextInfos();
604 LSerror :: addErrorCode('LSsession_09');
607 if (self :: $ldapServerId) {
608 $GLOBALS['Smarty'] -> assign('ldapServerId',self :: $ldapServerId);
610 $GLOBALS['Smarty'] -> assign('topDn',self :: $topDn);
611 if (isset($_GET['LSsession_recoverPassword'])) {
612 self :: displayRecoverPasswordForm($recoveryPasswordInfos);
614 elseif(LSauth :: displayLoginForm()) {
615 self :: displayLoginForm();
618 self :: setTemplate('blank.tpl');
619 LSerror :: addErrorCode('LSsession_10');
626 * Do recover password
628 * @param[in] $username string The submited username
629 * @param[in] $recoveryHash string The submited recoveryHash
631 * @retval array The recoveryPassword infos for template
633 private static function recoverPasswd($username,$recoveryHash) {
634 $recoveryPasswordInfos=array();
635 if ( self :: loadLSobject(self :: $ldapServer['authObjectType']) ) {
636 $authobject = new self :: $ldapServer['authObjectType']();
637 if (!empty($recoveryHash)) {
638 $filter=Net_LDAP2_Filter::create(
639 self :: $ldapServer['recoverPassword']['recoveryHashAttr'],
643 $result = $authobject -> listObjects($filter,self :: $topDn);
645 elseif (!empty($username)) {
646 $result = $authobject -> searchObject(
649 self :: $ldapServer['authObjectFilter']
653 return $recoveryPasswordInfos;
656 $nbresult=count($result);
659 LSdebug('hash/username incorrect');
660 LSerror :: addErrorCode('LSsession_06');
662 elseif ($nbresult>1) {
663 LSerror :: addErrorCode('LSsession_07');
666 $rdn = $result[0] -> getValue('rdn');
668 LSdebug('Recover : Id trouvé : '.$username);
669 if (self :: $ldapServer['recoverPassword']) {
670 if (self :: loadLSaddon('mail')) {
671 LSdebug('Récupération active');
673 $emailAddress = $user -> getValue(self :: $ldapServer['recoverPassword']['mailAttr']);
674 $emailAddress = $emailAddress[0];
676 if (checkEmail($emailAddress)) {
677 LSdebug('Email : '.$emailAddress);
678 self :: $dn = $user -> getDn();
680 // 1ère étape : envoie du recoveryHash
681 if (empty($recoveryHash)) {
682 $hash=self :: recoverPasswdFirstStep($user);
684 if (self :: recoverPasswdSendMail($emailAddress,1,$hash)) {
685 // Mail a bien été envoyé
686 $recoveryPasswordInfos['recoveryHashMail']=$emailAddress;
690 // 2nd étape : génération du mot de passe + envoie par mail
692 $pwd=self :: recoverPasswdSecondStep($user);
694 if (self :: recoverPasswdSendMail($emailAddress,2,$pwd)){
695 // Mail a bien été envoyé
696 $recoveryPasswordInfos['newPasswordMail']=$emailAddress;
702 LSerror :: addErrorCode('LSsession_19');
707 LSerror :: addErrorCode('LSsession_18');
711 return $recoveryPasswordInfos;
715 * Send recover password mail
717 * @param[in] $mail string The user's mail
718 * @param[in] $step integer The step
719 * @param[in] $info string The info for formatted message
721 * @retval boolean True on success or False
723 private static function recoverPasswdSendMail($mail,$step,$info) {
726 if (self :: $ldapServer['recoverPassword']['recoveryEmailSender']) {
727 $sendParams['From']=self :: $ldapServer['recoverPassword']['recoveryEmailSender'];
731 if ($_SERVER['HTTPS']=='on') {
732 $recovery_url='https://';
735 $recovery_url='http://';
737 $recovery_url .= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'&recoveryHash='.$info;
739 $subject = self :: $ldapServer['recoverPassword']['recoveryHashMail']['subject'];
741 self :: $ldapServer['recoverPassword']['recoveryHashMail']['msg'],
746 $subject = self :: $ldapServer['recoverPassword']['newPasswordMail']['subject'];
748 self :: $ldapServer['recoverPassword']['newPasswordMail']['msg'],
753 if (!sendMail($mail,$subject,$msg,$sendParams)) {
754 LSdebug("Problème durant l'envoie du mail");
755 LSerror :: addErrorCode('LSsession_20',4);
763 * Do first step of recovering password
765 * @param[in] $user LSldapObject The LSldapObject of the user
767 * @retval string|False The recory hash on success or False
769 private static function recoverPasswdFirstStep($user) {
771 $rdn=$user -> getValue('rdn');
773 $recovery_hash = md5($rdn . strval(time()) . strval(rand()));
775 $lostPasswdForm = $user -> getForm('lostPassword');
776 $lostPasswdForm -> setPostData(
778 self :: $ldapServer['recoverPassword']['recoveryHashAttr'] => $recovery_hash
783 if($lostPasswdForm -> validate()) {
784 if ($user -> updateData('lostPassword')) {
785 // recoveryHash de l'utilisateur mis à jour
786 return $recovery_hash;
789 // Erreur durant la mise à jour de l'objet
790 LSdebug("Erreur durant la mise à jour de l'objet");
791 LSerror :: addErrorCode('LSsession_20',6);
795 // Erreur durant la validation du formulaire de modification de perte de password
796 LSdebug("Erreur durant la validation du formulaire de modification de perte de password");
797 LSerror :: addErrorCode('LSsession_20',5);
803 * Do second step of recovering password
805 * @param[in] $user LSldapObject The LSldapObject of the user
807 * @retval string|False The new password on success or False
809 private static function recoverPasswdSecondStep($user) {
810 $attr=$user -> attrs[self :: $ldapServer['authObjectTypeAttrPwd']];
811 if ($attr instanceof LSattribute) {
812 $mdp = generatePassword(
813 $attr -> config['html_options']['chars'],
814 $attr -> config['html_options']['lenght']
816 LSdebug('Nvx mpd : '.$mdp);
817 $lostPasswdForm = $user -> getForm('lostPassword');
818 $lostPasswdForm -> setPostData(
820 self :: $ldapServer['recoverPassword']['recoveryHashAttr'] => array(''),
821 self :: $ldapServer['authObjectTypeAttrPwd'] => array($mdp)
825 if($lostPasswdForm -> validate()) {
826 if ($user -> updateData('lostPassword')) {
830 // Erreur durant la mise à jour de l'objet
831 LSdebug("Erreur durant la mise à jour de l'objet");
832 LSerror :: addErrorCode('LSsession_20',3);
836 // Erreur durant la validation du formulaire de modification de perte de password
837 LSdebug("Erreur durant la validation du formulaire de modification de perte de password");
838 LSerror :: addErrorCode('LSsession_20',2);
842 // l'attribut password n'existe pas
843 LSdebug("L'attribut password n'existe pas");
844 LSerror :: addErrorCode('LSsession_20',1);
850 * Retourne les informations du contexte
852 * @author Benjamin Renard <brenard@easter-eggs.com
854 * @retval array Tableau associatif des informations du contexte
856 private static function getContextInfos() {
858 'tmp_file' => self :: $tmp_file,
859 'topDn' => self :: $topDn,
861 'rdn' => self :: $rdn,
862 'ldapServerId' => self :: $ldapServerId,
863 'ldapServer' => self :: $ldapServer,
864 'LSprofiles' => self :: $LSprofiles,
865 'LSaccess' => self :: $LSaccess
870 * Retourne l'objet de l'utilisateur connecté
872 * @author Benjamin Renard <brenard@easter-eggs.com
874 * @retval mixed L'objet de l'utilisateur connecté ou false si il n'a pas put
877 public static function getLSuserObject($dn=null) {
881 if (!self :: $LSuserObject) {
882 if (self :: loadLSobject(self :: $ldapServer['authObjectType'])) {
883 self :: $LSuserObject = new self :: $ldapServer['authObjectType']();
884 self :: $LSuserObject -> loadData(self :: $dn);
890 return self :: $LSuserObject;
894 * Retourne le DN de l'utilisateur connecté
896 * @author Benjamin Renard <brenard@easter-eggs.com
898 * @retval string Le DN de l'utilisateur connecté
900 public static function getLSuserObjectDn() {
905 * Modifie l'utilisateur connecté à la volé
907 * @param[in] $object Mixed L'objet Ldap du nouvel utilisateur
908 * le type doit correspondre à
909 * self :: $ldapServer['authObjectType']
911 * @retval boolean True en cas de succès, false sinon
913 public static function changeAuthUser($object) {
914 if ($object instanceof self :: $ldapServer['authObjectType']) {
915 self :: $dn = $object -> getDn();
916 $rdn = $object -> getValue('rdn');
921 self :: $LSuserObject = $object;
923 if(self :: loadLSprofiles()) {
924 self :: loadLSaccess();
925 $_SESSION['LSsession']=self :: getContextInfos();
933 * Définition du serveur Ldap de la session
935 * Définition du serveur Ldap de la session à partir de son ID dans
936 * le tableau LSconfig :: get('ldap_servers').
938 * @param[in] integer Index du serveur Ldap
940 * @retval boolean True sinon false.
942 public static function setLdapServer($id) {
943 $conf = LSconfig :: get("ldap_servers.$id");
944 if ( is_array($conf) ) {
945 self :: $ldapServerId = $id;
946 self :: $ldapServer = $conf;
956 * Connexion au serveur Ldap
958 * @retval boolean True sinon false.
960 public static function LSldapConnect() {
961 if (self :: $ldapServer) {
962 self :: includeFile(LSconfig :: get('NetLDAP2'));
963 if (!self :: loadLSclass('LSldap')) {
966 LSldap :: connect(self :: $ldapServer['ldap_config']);
967 if (LSldap :: isConnected()) {
975 LSerror :: addErrorCode('LSsession_03');
981 * Use this function to know if subDn is enabled for the curent LdapServer
985 public static function subDnIsEnabled() {
986 if (!isset(self :: $ldapServer['subDn'])) {
989 if ( !is_array(self :: $ldapServer['subDn']) ) {
996 * Retourne les sous-dns du serveur Ldap courant
998 * @retval mixed Tableau des subDn, false si une erreur est survenue.
1000 public static function getSubDnLdapServer($login=false) {
1001 $login=(bool)$login;
1002 if (self :: cacheSudDn() && isset(self :: $_subDnLdapServer[self :: $ldapServerId][$login])) {
1003 return self :: $_subDnLdapServer[self :: $ldapServerId];
1005 if (!self::subDnIsEnabled()) {
1009 foreach(self :: $ldapServer['subDn'] as $subDn_name => $subDn_config) {
1010 if ($login && $subDn_config['nologin']) continue;
1011 if ($subDn_name == 'LSobject') {
1012 if (is_array($subDn_config)) {
1013 foreach($subDn_config as $LSobject_name => $LSoject_config) {
1014 if ($LSoject_config['basedn']) {
1015 $basedn = $LSoject_config['basedn'];
1018 $basedn = self::getRootDn();
1020 if ($LSoject_config['displayName']) {
1021 $displayName = $LSoject_config['displayName'];
1024 $displayName = NULL;
1026 if( self :: loadLSobject($LSobject_name) ) {
1027 if ($subdnobject = new $LSobject_name()) {
1028 $tbl_return = $subdnobject -> getSelectArray(NULL,$basedn,$displayName);
1029 if (is_array($tbl_return)) {
1030 $return=array_merge($return,$tbl_return);
1033 LSerror :: addErrorCode('LSsession_17',3);
1037 LSerror :: addErrorCode('LSsession_17',2);
1043 LSerror :: addErrorCode('LSsession_17',1);
1047 if ((isCompatibleDNs($subDn_config['dn'],self :: $ldapServer['ldap_config']['basedn']))&&($subDn_config['dn']!="")) {
1048 $return[$subDn_config['dn']] = __($subDn_name);
1052 if (self :: cacheSudDn()) {
1053 self :: $_subDnLdapServer[self :: $ldapServerId][$login]=$return;
1054 $_SESSION['LSsession_subDnLdapServer'] = self :: $_subDnLdapServer;
1060 * Retourne la liste de subDn du serveur Ldap utilise
1061 * trié par la profondeur dans l'arboressence (ordre décroissant)
1063 * @return array() Tableau des subDn trié
1065 public static function getSortSubDnLdapServer($login=false) {
1066 $subDnLdapServer = self :: getSubDnLdapServer($login);
1067 if (!$subDnLdapServer) {
1070 uksort($subDnLdapServer,"compareDn");
1071 return $subDnLdapServer;
1075 * Retourne les options d'une liste déroulante pour le choix du topDn
1076 * de connexion au serveur Ldap
1078 * Liste les subdn (self :: $ldapServer['subDn'])
1080 * @retval string Les options (<option>) pour la sélection du topDn.
1082 public static function getSubDnLdapServerOptions($selected=NULL,$login=false) {
1083 $list = self :: getSubDnLdapServer($login);
1087 foreach($list as $dn => $txt) {
1088 if ($selected && ($selected==$dn)) {
1089 $selected_txt = ' selected';
1094 $display.="<option value=\"".$dn."\"$selected_txt>".$txt."</option>\n";
1102 * Vérifie qu'un subDn est déclaré
1104 * @param[in] string Un subDn
1106 * @retval boolean True si le subDn existe, False sinon
1108 public static function validSubDnLdapServer($subDn) {
1109 $listTopDn = self :: getSubDnLdapServer();
1110 if(is_array($listTopDn)) {
1111 foreach($listTopDn as $dn => $txt) {
1121 * Test un couple LSobject/pwd
1123 * Test un bind sur le serveur avec le dn de l'objet et le mot de passe fourni.
1125 * @param[in] LSobject L'object "user" pour l'authentification
1126 * @param[in] string Le mot de passe à tester
1128 * @retval boolean True si l'authentification à réussi, false sinon.
1130 public static function checkUserPwd($object,$pwd) {
1131 return LSldap :: checkBind($object -> getValue('dn'),$pwd);
1135 * Affiche le formulaire de login
1137 * Défini les informations pour le template Smarty du formulaire de login.
1141 public static function displayLoginForm() {
1142 $GLOBALS['Smarty'] -> assign('pagetitle',_('Connection'));
1143 if (isset($_GET['LSsession_logout'])) {
1144 $GLOBALS['Smarty'] -> assign('loginform_action','index.php');
1147 $GLOBALS['Smarty'] -> assign('loginform_action',$_SERVER['REQUEST_URI']);
1149 if (count(LSconfig :: get('ldap_servers'))==1) {
1150 $GLOBALS['Smarty'] -> assign('loginform_ldapserver_style','style="display: none"');
1152 $GLOBALS['Smarty'] -> assign('loginform_label_ldapserver',_('LDAP server'));
1153 $ldapservers_name=array();
1154 $ldapservers_index=array();
1155 foreach(LSconfig :: get('ldap_servers') as $id => $infos) {
1156 $ldapservers_index[]=$id;
1157 $ldapservers_name[]=__($infos['name']);
1159 $GLOBALS['Smarty'] -> assign('loginform_ldapservers_name',$ldapservers_name);
1160 $GLOBALS['Smarty'] -> assign('loginform_ldapservers_index',$ldapservers_index);
1162 $GLOBALS['Smarty'] -> assign('loginform_label_level',_('Level'));
1163 $GLOBALS['Smarty'] -> assign('loginform_label_user',_('Identifier'));
1164 $GLOBALS['Smarty'] -> assign('loginform_label_pwd',_('Password'));
1165 $GLOBALS['Smarty'] -> assign('loginform_label_submit',_('Connect'));
1166 $GLOBALS['Smarty'] -> assign('loginform_label_recoverPassword',_('Forgot your password ?'));
1168 self :: setTemplate('login.tpl');
1169 self :: addJSscript('LSsession_login.js');
1173 * Affiche le formulaire de récupération de mot de passe
1175 * Défini les informations pour le template Smarty du formulaire de
1176 * récupération de mot de passe
1178 * @param[in] $infos array() Information sur le status du processus de
1179 * recouvrement de mot de passe
1183 public static function displayRecoverPasswordForm($recoveryPasswordInfos) {
1184 $GLOBALS['Smarty'] -> assign('pagetitle',_('Recovery of your credentials'));
1185 $GLOBALS['Smarty'] -> assign('recoverpasswordform_action','index.php?LSsession_recoverPassword');
1187 if (count(LSconfig :: get('ldap_servers'))==1) {
1188 $GLOBALS['Smarty'] -> assign('recoverpasswordform_ldapserver_style','style="display: none"');
1191 $GLOBALS['Smarty'] -> assign('recoverpasswordform_label_ldapserver',_('LDAP server'));
1192 $ldapservers_name=array();
1193 $ldapservers_index=array();
1194 foreach(LSconfig :: get('ldap_servers') as $id => $infos) {
1195 $ldapservers_index[]=$id;
1196 $ldapservers_name[]=$infos['name'];
1198 $GLOBALS['Smarty'] -> assign('recoverpasswordform_ldapservers_name',$ldapservers_name);
1199 $GLOBALS['Smarty'] -> assign('recoverpasswordform_ldapservers_index',$ldapservers_index);
1201 $GLOBALS['Smarty'] -> assign('recoverpasswordform_label_user',_('Identifier'));
1202 $GLOBALS['Smarty'] -> assign('recoverpasswordform_label_submit',_('Validate'));
1203 $GLOBALS['Smarty'] -> assign('recoverpasswordform_label_back',_('Back'));
1205 $recoverpassword_msg = _('Please fill the identifier field to proceed recovery procedure');
1207 if (isset($recoveryPasswordInfos['recoveryHashMail'])) {
1208 $recoverpassword_msg = getFData(
1209 _("An email has been sent to %{mail}. " .
1210 "Please follow the instructions on it."),
1211 $recoveryPasswordInfos['recoveryHashMail']
1215 if (isset($recoveryPasswordInfos['newPasswordMail'])) {
1216 $recoverpassword_msg = getFData(
1217 _("Your new password has been sent to %{mail}. "),
1218 $recoveryPasswordInfos['newPasswordMail']
1222 $GLOBALS['Smarty'] -> assign('recoverpassword_msg',$recoverpassword_msg);
1224 self :: setTemplate('recoverpassword.tpl');
1225 self :: addJSscript('LSsession_recoverPassword.js');
1229 * Défini le template Smarty à utiliser
1231 * Remarque : les fichiers de templates doivent se trouver dans le dossier
1234 * @param[in] string Le nom du fichier de template
1238 public static function setTemplate($template) {
1239 self :: $template = $template;
1243 * Ajoute un script JS au chargement de la page
1245 * Remarque : les scripts doivents être dans le dossier LS_JS_DIR.
1247 * @param[in] $script Le nom du fichier de script à charger.
1251 public static function addJSscript($file,$path=NULL) {
1256 self :: $JSscripts[$path.$file]=$script;
1260 * Ajouter un paramètre de configuration Javascript
1262 * @param[in] $name string Nom de la variable de configuration
1263 * @param[in] $val mixed Valeur de la variable de configuration
1267 public static function addJSconfigParam($name,$val) {
1268 self :: $_JSconfigParams[$name]=$val;
1272 * Ajoute une feuille de style au chargement de la page
1274 * Remarque : les scripts doivents être dans le dossier LS_CSS_DIR.
1276 * @param[in] $script Le nom du fichier css à charger.
1280 public static function addCssFile($file,$path=NULL) {
1285 self :: $CssFiles[$path.$file]=$cssFile;
1289 * Affiche le template Smarty
1291 * Charge les dépendances et affiche le template Smarty
1295 public static function displayTemplate() {
1298 foreach ($GLOBALS['defaultJSscipts'] as $script) {
1299 $JSscript_txt.="<script src='".LS_JS_DIR.$script."' type='text/javascript'></script>\n";
1302 foreach (self :: $JSscripts as $script) {
1303 if (!$script['path']) {
1304 $script['path']=LS_JS_DIR;
1307 $script['path'].='/';
1309 $JSscript_txt.="<script src='".$script['path'].$script['file']."' type='text/javascript'></script>\n";
1312 $KAconf = LSconfig :: get('keepLSsessionActive');
1315 (!isset(self :: $ldapServer['keepLSsessionActive']))
1317 (!($KAconf === false))
1320 (self :: $ldapServer['keepLSsessionActive'])
1322 self :: addJSconfigParam('keepLSsessionActive',ini_get('session.gc_maxlifetime'));
1325 $GLOBALS['Smarty'] -> assign('LSjsConfig',json_encode(self :: $_JSconfigParams));
1328 $JSscript_txt.="<script type='text/javascript'>LSdebug_active = 1;</script>\n";
1331 $JSscript_txt.="<script type='text/javascript'>LSdebug_active = 0;</script>\n";
1334 $GLOBALS['Smarty'] -> assign('LSsession_js',$JSscript_txt);
1337 self :: addCssFile("LSdefault.css");
1339 foreach (self :: $CssFiles as $file) {
1340 if (!$file['path']) {
1341 $file['path']=LS_CSS_DIR.'/';
1343 $Css_txt.="<link rel='stylesheet' type='text/css' href='".$file['path'].$file['file']."' />\n";
1345 $GLOBALS['Smarty'] -> assign('LSsession_css',$Css_txt);
1347 if (isset(self :: $LSaccess[self :: $topDn])) {
1348 $GLOBALS['Smarty'] -> assign('LSaccess',self :: $LSaccess[self :: $topDn]);
1352 $listTopDn = self :: getSubDnLdapServer();
1353 if (is_array($listTopDn)) {
1355 $GLOBALS['Smarty'] -> assign('label_level',self :: getSubDnLabel());
1356 $GLOBALS['Smarty'] -> assign('_refresh',_('Refresh'));
1357 $LSsession_topDn_index = array();
1358 $LSsession_topDn_name = array();
1359 foreach($listTopDn as $index => $name) {
1360 $LSsession_topDn_index[] = $index;
1361 $LSsession_topDn_name[] = $name;
1363 $GLOBALS['Smarty'] -> assign('LSsession_subDn_indexes',$LSsession_topDn_index);
1364 $GLOBALS['Smarty'] -> assign('LSsession_subDn_names',$LSsession_topDn_name);
1365 $GLOBALS['Smarty'] -> assign('LSsession_subDn',self :: $topDn);
1366 $GLOBALS['Smarty'] -> assign('LSsession_subDnName',self :: getSubDnName());
1369 $GLOBALS['Smarty'] -> assign('LSlanguages',self :: getLangList());
1370 $GLOBALS['Smarty'] -> assign('LSlang',self :: $lang);
1371 $GLOBALS['Smarty'] -> assign('LSencoding',self :: $encoding);
1372 $GLOBALS['Smarty'] -> assign('lang_label',_('Language'));
1374 $GLOBALS['Smarty'] -> assign('displayLogoutBtn',LSauth :: displayLogoutBtn());
1377 if((!empty($_SESSION['LSsession_infos']))&&(is_array($_SESSION['LSsession_infos']))) {
1378 $txt_infos="<ul>\n";
1379 foreach($_SESSION['LSsession_infos'] as $info) {
1380 $txt_infos.="<li>$info</li>\n";
1382 $txt_infos.="</ul>\n";
1383 $GLOBALS['Smarty'] -> assign('LSinfos',$txt_infos);
1384 $_SESSION['LSsession_infos']=array();
1387 if (self :: $ajaxDisplay) {
1388 $GLOBALS['Smarty'] -> assign('LSerror_txt',LSerror :: getErrors());
1389 $GLOBALS['Smarty'] -> assign('LSdebug_txt',LSdebug_print(true));
1392 LSerror :: display();
1395 if (!self :: $template)
1396 self :: setTemplate('empty.tpl');
1398 $GLOBALS['Smarty'] -> assign('connected_as',_("Connected as"));
1400 $GLOBALS['Smarty'] -> display(self :: $template);
1404 * Défini que l'affichage se fera ou non via un retour Ajax
1406 * @param[in] $val boolean True pour que l'affichage se fasse par un retour
1410 public static function setAjaxDisplay($val=true) {
1411 self :: $ajaxDisplay = (boolean)$val;
1415 * Affiche un retour Ajax
1419 public static function displayAjaxReturn($data=array()) {
1420 if (isset($data['LSredirect']) && (!LSdebugDefined()) ) {
1421 echo json_encode($data);
1425 $data['LSjsConfig'] = self :: $_JSconfigParams;
1428 if((!empty($_SESSION['LSsession_infos']))&&(is_array($_SESSION['LSsession_infos']))) {
1429 $txt_infos="<ul>\n";
1430 foreach($_SESSION['LSsession_infos'] as $info) {
1431 $txt_infos.="<li>$info</li>\n";
1433 $txt_infos.="</ul>\n";
1434 $data['LSinfos'] = $txt_infos;
1435 $_SESSION['LSsession_infos']=array();
1438 if (LSerror :: errorsDefined()) {
1439 $data['LSerror'] = LSerror :: getErrors();
1442 if (isset($_REQUEST['imgload'])) {
1443 $data['imgload'] = $_REQUEST['imgload'];
1446 if (LSdebugDefined()) {
1447 $data['LSdebug'] = LSdebug_print(true,false);
1450 echo json_encode($data);
1454 * Retournne un template Smarty compilé
1456 * @param[in] string $template Le template à retourner
1457 * @param[in] array $variables Variables Smarty à assigner avant l'affichage
1459 * @retval string Le HTML compilé du template
1461 public static function fetchTemplate($template,$variables=array()) {
1462 foreach($variables as $name => $val) {
1463 $GLOBALS['Smarty'] -> assign($name,$val);
1465 return $GLOBALS['Smarty'] -> fetch($template);
1469 * Charge les droits LS de l'utilisateur
1471 * @retval boolean True si le chargement à réussi, false sinon.
1473 private static function loadLSprofiles() {
1474 if (is_array(self :: $ldapServer['LSprofiles'])) {
1475 foreach (self :: $ldapServer['LSprofiles'] as $profile => $profileInfos) {
1476 if (is_array($profileInfos)) {
1477 foreach ($profileInfos as $topDn => $rightsInfos) {
1479 * If $topDn == 'LSobject', we search for each LSobject type to find
1480 * all items on witch the user will have powers.
1482 if ($topDn == 'LSobjects') {
1483 if (is_array($rightsInfos)) {
1484 foreach ($rightsInfos as $LSobject => $listInfos) {
1485 if (self :: loadLSclass('LSsearch')) {
1486 if (isset($listInfos['filter'])) {
1487 $filter = self :: getLSuserObject() -> getFData($listInfos['filter']);
1490 $filter = '('.$listInfos['attr'].'='.self :: getLSuserObject() -> getFData($listInfos['attr_value']).')';
1494 'basedn' => (isset($listInfos['basedn'])?$listInfos['basedn']:null),
1498 if (isset($listInfos['params']) && is_array($listInfos['params'])) {
1499 $params = array_merge($listInfos['params'],$params);
1502 $LSsearch = new LSsearch($LSobject,'LSsession :: loadLSprofiles',$params,true);
1503 $LSsearch -> run(false);
1505 $LSprofiles[$profile] = $LSsearch -> listObjectsDn();
1510 LSdebug('LSobjects => [] doit etre un tableau');
1514 if (is_array($rightsInfos)) {
1515 foreach($rightsInfos as $dn => $conf) {
1516 if ((isset($conf['attr'])) && (isset($conf['LSobject']))) {
1517 if( self :: loadLSobject($conf['LSobject']) ) {
1518 if ($object = new $conf['LSobject']()) {
1519 if ($object -> loadData($dn)) {
1520 $listDns=$object -> getValue($conf['attr']);
1521 $valKey = (isset($conf['attr_value']))?$conf['attr_value']:'%{dn}';
1522 $val = self :: getLSuserObject() -> getFData($valKey);
1523 if (is_array($listDns)) {
1524 if (in_array($val,$listDns)) {
1525 self :: $LSprofiles[$profile][] = $topDn;
1530 LSdebug('Impossible de chargé le dn : '.$dn);
1534 LSdebug('Impossible de créer l\'objet de type : '.$conf['LSobject']);
1539 if (self :: $dn == $dn) {
1540 self :: $LSprofiles[$profile][] = $topDn;
1546 if ( self :: $dn == $rightsInfos ) {
1547 self :: $LSprofiles[$profile][] = $topDn;
1550 } // fin else ($topDn == 'LSobjects')
1551 } // fin foreach($profileInfos)
1552 } // fin is_array($profileInfos)
1553 } // fin foreach LSprofiles
1554 LSdebug(self :: $LSprofiles);
1563 * Charge les droits d'accès de l'utilisateur pour construire le menu de l'interface
1567 private static function loadLSaccess() {
1569 if (isset(self :: $ldapServer['subDn']) && is_array(self :: $ldapServer['subDn'])) {
1570 foreach(self :: $ldapServer['subDn'] as $name => $config) {
1571 if ($name=='LSobject') {
1572 if (is_array($config)) {
1574 // Définition des subDns
1575 foreach($config as $objectType => $objectConf) {
1576 if (self :: loadLSobject($objectType)) {
1577 if ($subdnobject = new $objectType()) {
1578 $tbl = $subdnobject -> getSelectArray(NULL,self::getRootDn(),NULL,NULL,false);
1579 if (is_array($tbl)) {
1580 // Définition des accès
1582 if (is_array($objectConf['LSobjects'])) {
1583 foreach($objectConf['LSobjects'] as $type) {
1584 if (self :: loadLSobject($type)) {
1585 if (self :: canAccess($type)) {
1586 $access[$type] = LSconfig :: get('LSobjects.'.$type.'.label');
1591 foreach($tbl as $dn => $dn_name) {
1592 $LSaccess[$dn]=$access;
1601 if ((isCompatibleDNs(self :: $ldapServer['ldap_config']['basedn'],$config['dn']))&&($config['dn']!='')) {
1603 if (is_array($config['LSobjects'])) {
1604 foreach($config['LSobjects'] as $objectType) {
1605 if (self :: loadLSobject($objectType)) {
1606 if (self :: canAccess($objectType)) {
1607 $access[$objectType] = LSconfig :: get('LSobjects.'.$objectType.'.label');
1612 $LSaccess[$config['dn']]=$access;
1618 if(is_array(self :: $ldapServer['LSaccess'])) {
1620 foreach(self :: $ldapServer['LSaccess'] as $objectType) {
1621 if (self :: loadLSobject($objectType)) {
1622 if (self :: canAccess($objectType)) {
1623 $access[$objectType] = LSconfig :: get('LSobjects.'.$objectType.'.label');
1627 $LSaccess[self :: $topDn] = $access;
1630 foreach($LSaccess as $dn => $access) {
1631 $LSaccess[$dn] = array_merge(
1633 'SELF' => 'My account'
1639 self :: $LSaccess = $LSaccess;
1640 $_SESSION['LSsession']['LSaccess'] = $LSaccess;
1644 * Dit si l'utilisateur est du profil pour le DN spécifié
1646 * @param[in] string $profile de l'objet
1647 * @param[in] string $dn DN de l'objet
1649 * @retval boolean True si l'utilisateur est du profil sur l'objet, false sinon.
1651 public static function isLSprofile($dn,$profile) {
1652 if (is_array(self :: $LSprofiles[$profile])) {
1653 foreach(self :: $LSprofiles[$profile] as $topDn) {
1657 else if ( isCompatibleDNs($dn,$topDn) ) {
1666 * Retourne qui est l'utilisateur par rapport à l'object
1668 * @param[in] string Le DN de l'objet
1670 * @retval string 'admin'/'self'/'user' pour Admin , l'utilisateur lui même ou un simple utilisateur
1672 public static function whoami($dn) {
1673 $retval = array('user');
1675 foreach(self :: $LSprofiles as $profile => $infos) {
1676 if(self :: isLSprofile($dn,$profile)) {
1681 if (self :: $dn == $dn) {
1689 * Retourne le droit de l'utilisateur à accèder à un objet
1691 * @param[in] string $LSobject Le type de l'objet
1692 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1693 * @param[in] string $right Le type de droit d'accès à tester ('r'/'w')
1694 * @param[in] string $attr Le nom de l'attribut auquel on test l'accès
1696 * @retval boolean True si l'utilisateur a accès, false sinon
1698 public static function canAccess($LSobject,$dn=NULL,$right=NULL,$attr=NULL) {
1699 if (!self :: loadLSobject($LSobject)) {
1703 $whoami = self :: whoami($dn);
1704 if ($dn==self :: getLSuserObject() -> getValue('dn')) {
1705 if (!self :: in_menu('SELF')) {
1710 $obj = new $LSobject();
1712 if (!self :: in_menu($LSobject,$obj -> subDnValue)) {
1718 $objectdn=LSconfig :: get('LSobjects.'.$LSobject.'.container_dn').','.self :: $topDn;
1719 $whoami = self :: whoami($objectdn);
1722 // Pour un attribut particulier
1725 $attr=LSconfig :: get('LSobjects.'.$LSobject.'.rdn');
1727 if (!is_array(LSconfig :: get('LSobjects.'.$LSobject.'.attrs.'.$attr))) {
1732 foreach($whoami as $who) {
1733 $nr = LSconfig :: get('LSobjects.'.$LSobject.'.attrs.'.$attr.'.rights.'.$who);
1737 else if($nr == 'r') {
1744 if (($right=='r')||($right=='w')) {
1751 if ( ($r=='r') || ($r=='w') ) {
1758 // Pour un attribut quelconque
1759 $attrs_conf=LSconfig :: get('LSobjects.'.$LSobject.'.attrs');
1760 if (is_array($attrs_conf)) {
1761 if (($right=='r')||($right=='w')) {
1762 foreach($whoami as $who) {
1763 foreach ($attrs_conf as $attr_name => $attr_config) {
1764 if (isset($attr_config['rights'][$who]) && $attr_config['rights'][$who]==$right) {
1771 foreach($whoami as $who) {
1772 foreach ($attrs_conf as $attr_name => $attr_config) {
1773 if ( (isset($attr_config['rights'][$who])) && ( ($attr_config['rights'][$who]=='r') || ($attr_config['rights'][$who]=='w') ) ) {
1784 * Retourne le droit de l'utilisateur à editer à un objet
1786 * @param[in] string $LSobject Le type de l'objet
1787 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1788 * @param[in] string $attr Le nom de l'attribut auquel on test l'accès
1790 * @retval boolean True si l'utilisateur a accès, false sinon
1792 public static function canEdit($LSobject,$dn=NULL,$attr=NULL) {
1793 return self :: canAccess($LSobject,$dn,'w',$attr);
1797 * Retourne le droit de l'utilisateur à supprimer un objet
1799 * @param[in] string $LSobject Le type de l'objet
1800 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1802 * @retval boolean True si l'utilisateur a accès, false sinon
1804 public static function canRemove($LSobject,$dn) {
1805 return self :: canAccess($LSobject,$dn,'w','rdn');
1809 * Retourne le droit de l'utilisateur à créer un objet
1811 * @param[in] string $LSobject Le type de l'objet
1813 * @retval boolean True si l'utilisateur a accès, false sinon
1815 public static function canCreate($LSobject) {
1816 if (!self :: loadLSobject($LSobject)) {
1819 if (LSconfig :: get("LSobjects.$LSobject.disable_creation")) {
1822 return self :: canAccess($LSobject,NULL,'w','rdn');
1826 * Retourne le droit de l'utilisateur à gérer la relation d'objet
1828 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1829 * @param[in] string $LSobject Le type de l'objet
1830 * @param[in] string $relationName Le nom de la relation avec l'objet
1831 * @param[in] string $right Le type de droit a vérifier ('r' ou 'w')
1833 * @retval boolean True si l'utilisateur a accès, false sinon
1835 public static function relationCanAccess($dn,$LSobject,$relationName,$right=NULL) {
1836 $relConf=LSconfig :: get('LSobjects.'.$LSobject.'.LSrelation.'.$relationName);
1837 if (!is_array($relConf))
1839 $whoami = self :: whoami($dn);
1841 if (($right=='w') || ($right=='r')) {
1843 foreach($whoami as $who) {
1844 $nr = ((isset($relConf['rights'][$who]))?$relConf['rights'][$who]:'');
1848 else if($nr == 'r') {
1860 foreach($whoami as $who) {
1861 if ((isset($relConf['rights'][$who])) && ( ($relConf['rights'][$who] == 'w') || ($relConf['rights'][$who] == 'r') ) ) {
1870 * Retourne le droit de l'utilisateur à modifier la relation d'objet
1872 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1873 * @param[in] string $LSobject Le type de l'objet
1874 * @param[in] string $relationName Le nom de la relation avec l'objet
1876 * @retval boolean True si l'utilisateur a accès, false sinon
1878 public static function relationCanEdit($dn,$LSobject,$relationName) {
1879 return self :: relationCanAccess($dn,$LSobject,$relationName,'w');
1883 * Ajoute un fichier temporaire
1885 * @author Benjamin Renard <brenard@easter-eggs.com>
1889 public static function addTmpFile($value,$filePath) {
1890 $hash = mhash(MHASH_MD5,$value);
1891 self :: $tmp_file[$filePath] = $hash;
1892 $_SESSION['LSsession']['tmp_file'][$filePath] = $hash;
1896 * Retourne le chemin du fichier temporaire si l'existe
1898 * @author Benjamin Renard <brenard@easter-eggs.com>
1900 * @param[in] $value La valeur du fichier
1904 public static function tmpFileExist($value) {
1905 $hash = mhash(MHASH_MD5,$value);
1906 foreach(self :: $tmp_file as $filePath => $contentHash) {
1907 if ($hash == $contentHash) {
1915 * Retourne le chemin du fichier temporaire
1917 * Retourne le chemin du fichier temporaire qu'il créera à partir de la valeur
1918 * s'il n'existe pas déjà .
1920 * @author Benjamin Renard <brenard@easter-eggs.com>
1922 * @param[in] $value La valeur du fichier
1926 public static function getTmpFile($value) {
1927 $exist = self :: tmpFileExist($value);
1929 $img_path = LS_TMP_DIR .rand().'.tmp';
1930 $fp = fopen($img_path, "w");
1931 fwrite($fp, $value);
1933 self :: addTmpFile($value,$img_path);
1942 * Supprime les fichiers temporaires
1944 * @author Benjamin Renard <brenard@easter-eggs.com>
1948 public static function deleteTmpFile($filePath=NULL) {
1951 unset(self :: $tmp_file[$filePath]);
1952 unset($_SESSION['LSsession']['tmp_file'][$filePath]);
1955 foreach(self :: $tmp_file as $file => $content) {
1958 self :: $tmp_file = array();
1959 $_SESSION['LSsession']['tmp_file'] = array();
1964 * Retourne true si le cache des droits est activé
1966 * @author Benjamin Renard <brenard@easter-eggs.com>
1968 * @retval boolean True si le cache des droits est activé, false sinon.
1970 public static function cacheLSprofiles() {
1971 return ( (LSconfig :: get('cacheLSprofiles')) || (self :: $ldapServer['cacheLSprofiles']) );
1975 * Retourne true si le cache des subDn est activé
1977 * @author Benjamin Renard <brenard@easter-eggs.com>
1979 * @retval boolean True si le cache des subDn est activé, false sinon.
1981 public static function cacheSudDn() {
1982 return ( (LSconfig :: get('cacheSubDn')) || (self :: $ldapServer['cacheSubDn']));
1986 * Retourne true si le cache des recherches est activé
1988 * @author Benjamin Renard <brenard@easter-eggs.com>
1990 * @retval boolean True si le cache des recherches est activé, false sinon.
1992 public static function cacheSearch() {
1993 return ( (LSconfig :: get('cacheSearch')) || (self :: $ldapServer['cacheSearch']));
1997 * Retourne le label des niveaux pour le serveur ldap courant
1999 * @author Benjamin Renard <brenard@easter-eggs.com>
2001 * @retval string Le label des niveaux pour le serveur ldap dourant
2003 public static function getSubDnLabel() {
2004 return (self :: $ldapServer['subDnLabel']!='')?__(self :: $ldapServer['subDnLabel']):_('Level');
2008 * Retourne le nom du subDn
2010 * @param[in] $subDn string subDn
2012 * @retval string Le nom du subDn ou '' sinon
2014 public static function getSubDnName($subDn=false) {
2016 $subDn = self :: $topDn;
2018 if (self :: getSubDnLdapServer()) {
2019 if (isset(self :: $_subDnLdapServer[self :: $ldapServerId][$subDn])) {
2020 return self :: $_subDnLdapServer[self :: $ldapServerId][$subDn];
2027 * L'objet est t-il utilisé pour listé les subDnS
2029 * @param[in] $type string Le type d'objet
2031 * @retval boolean true si le type d'objet est un subDnObject, false sinon
2033 public static function isSubDnLSobject($type) {
2035 if (isset(self :: $ldapServer['subDn']['LSobject']) && is_array(self :: $ldapServer['subDn']['LSobject'])) {
2036 foreach(self :: $ldapServer['subDn']['LSobject'] as $key => $value) {
2046 * Indique si un type d'objet est dans le menu courant
2048 * @retval boolean true si le type d'objet est dans le menu, false sinon
2050 public static function in_menu($LSobject,$topDn=NULL) {
2052 $topDn=self :: $topDn;
2054 return isset(self :: $LSaccess[$topDn][$LSobject]);
2058 * Indique si le serveur LDAP courant a des subDn
2060 * @retval boolean true si le serveur LDAP courant a des subDn, false sinon
2062 public static function haveSubDn() {
2063 return (isset(self :: $ldapServer['subDn']) && is_array(self :: $ldapServer['subDn']));
2067 * Ajoute une information à afficher
2069 * @param[in] $msg string Le message à afficher
2073 public static function addInfo($msg) {
2074 $_SESSION['LSsession_infos'][]=$msg;
2078 * Redirection de l'utilisateur vers une autre URL
2080 * @param[in] $url string L'URL
2081 * @param[in] $exit boolean Si true, l'execution script s'arrête après la redirection
2085 public static function redirect($url,$exit=true) {
2086 $GLOBALS['Smarty'] -> assign('url',$url);
2087 $GLOBALS['Smarty'] -> display('redirect.tpl');
2094 * Retourne l'adresse mail d'emission configurée pour le serveur courant
2096 * @retval string Adresse mail d'emission
2098 public static function getEmailSender() {
2099 return self :: $ldapServer['emailSender'];
2103 * Ajout d'une information d'aide
2105 * @param[in] $group string Le nom du groupe d'infos dans lequels ajouter
2107 * @param[in] $infos array Tableau array(name => value) des infos
2111 public static function addHelpInfos($group,$infos) {
2112 if (is_array($infos)) {
2113 if (isset(self :: $_JSconfigParams['helpInfos'][$group]) && is_array(self :: $_JSconfigParams['helpInfos'][$group])) {
2114 self :: $_JSconfigParams['helpInfos'][$group] = array_merge(self :: $_JSconfigParams['helpInfos'][$group],$infos);
2117 self :: $_JSconfigParams['helpInfos'][$group] = $infos;
2123 * Défini les codes erreur relative à la classe LSsession
2127 private static function defineLSerrors() {
2131 LSerror :: defineError('LSsession_01',
2132 _("LSsession : The constant %{const} is not defined.")
2134 LSerror :: defineError('LSsession_02',
2135 _("LSsession : The %{addon} support is uncertain. Verify system compatibility and the add-on configuration.")
2137 LSerror :: defineError('LSsession_03',
2138 _("LSsession : LDAP server's configuration data are invalid. Can't connect.")
2140 LSerror :: defineError('LSsession_04',
2141 _("LSsession : Failed to load LSobject type %{type} : unknon type.")
2143 LSerror :: defineError('LSsession_05',
2144 _("LSsession : Failed to load LSclass %{class}.")
2146 LSerror :: defineError('LSsession_06',
2147 _("LSsession : Login or password incorrect.")
2149 LSerror :: defineError('LSsession_07',
2150 _("LSsession : Impossible to identify you : Duplication of identities.")
2152 LSerror :: defineError('LSsession_08',
2153 _("LSsession : Can't load class of authentification (%{class}).")
2155 LSerror :: defineError('LSsession_09',
2156 _("LSsession : Can't connect to LDAP server.")
2158 LSerror :: defineError('LSsession_10',
2159 _("LSsession : Impossible to authenticate you.")
2161 LSerror :: defineError('LSsession_11',
2162 _("LSsession : Your are not authorized to do this action.")
2164 LSerror :: defineError('LSsession_12',
2165 _("LSsession : Some informations are missing to display this page.")
2167 // 13 -> 16 : not yet used
2168 LSerror :: defineError('LSsession_17',
2169 _("LSsession : Error during creation of list of levels. Contact administrators. (Code : %{code})")
2171 LSerror :: defineError('LSsession_18',
2172 _("LSsession : The password recovery is disabled for this LDAP server.")
2174 LSerror :: defineError('LSsession_19',
2175 _("LSsession : Some informations are missing to recover your password. Contact administrators.")
2177 LSerror :: defineError('LSsession_20',
2178 _("LSsession : Error during password recovery. Contact administrators.(Step : %{step})")
2180 // 21 : not yet used
2181 LSerror :: defineError('LSsession_22',
2182 _("LSsession : problem during initialisation.")
2187 * Ajax method when change ldapserver on login form
2189 * @param[in] $data array The return data address
2193 public static function ajax_onLdapServerChangedLogin(&$data) {
2194 if ( isset($_REQUEST['server']) ) {
2195 self :: setLdapServer($_REQUEST['server']);
2197 if ( self :: LSldapConnect() ) {
2198 if (session_id()=="") session_start();
2199 if (isset($_SESSION['LSsession_topDn'])) {
2200 $sel = $_SESSION['LSsession_topDn'];
2205 $list = self :: getSubDnLdapServerOptions($sel,true);
2206 if (is_string($list)) {
2207 $data['list_topDn'] = "<select name='LSsession_topDn' id='LSsession_topDn'>".$list."</select>";
2208 $data['subDnLabel'] = self :: getSubDnLabel();
2211 $data['recoverPassword'] = isset(self :: $ldapServer['recoverPassword']);
2216 * Ajax method when change ldapserver on recoverPassword form
2218 * @param[in] $data array The return data address
2222 public static function ajax_onLdapServerChangedRecoverPassword(&$data) {
2223 if ( isset($_REQUEST['server']) ) {
2224 self :: setLdapServer($_REQUEST['server']);
2225 $data=array('recoverPassword' => isset(self :: $ldapServer['recoverPassword']));