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 // Authentification parameters
54 private static $authParams = array();
56 // Les fichiers temporaires
57 private static $tmp_file = array();
59 // Langue et encodage actuel
60 private static $lang = NULL;
61 private static $encoding = NULL;
64 * Constante de classe non stockée en session
66 // Le template à afficher
67 private static $template = NULL;
69 // Les subDn des serveurs Ldap
70 private static $_subDnLdapServer = array();
73 private static $ajaxDisplay = false;
75 // Les fichiers JS à charger dans la page
76 private static $JSscripts = array();
78 // Les paramètres JS à communiquer dans la page
79 private static $_JSconfigParams = array();
81 // Les fichiers CSS à charger dans la page
82 private static $CssFiles = array();
84 // L'objet de l'utilisateur connecté
85 private static $LSuserObject = NULL;
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)) {
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'] -> assign('LS_CSS_DIR',LS_CSS_DIR);
150 $GLOBALS['Smarty'] -> assign('LS_IMAGES_DIR',LS_IMAGES_DIR);
152 self :: addJSconfigParam('LS_IMAGES_DIR',LS_IMAGES_DIR);
155 die("ERROR : Can't load Smarty.");
160 * Retourne le topDn de la session
162 * @author Benjamin Renard <brenard@easter-eggs.com>
164 * @retval string le topDn de la session
166 public static function getTopDn() {
167 if (!is_null(self :: $topDn)) {
168 return self :: $topDn;
171 return self :: getRootDn();
176 * Retourne le rootDn de la session
178 * @author Benjamin Renard <brenard@easter-eggs.com>
180 * @retval string le rootDn de la session
182 public static function getRootDn() {
183 return self :: $ldapServer['ldap_config']['basedn'];
187 * Initialisation de la gestion des erreurs
189 * Création de l'objet LSerror
191 * @author Benjamin Renard <brenard@easter-eggs.com
193 * @retval boolean true si l'initialisation a réussi, false sinon.
195 private static function startLSerror() {
196 if(!self :: loadLSclass('LSerror')) {
199 self :: defineLSerrors();
204 * Chargement d'une classe d'LdapSaisie
206 * @param[in] $class Nom de la classe à charger (Exemple : LSpeople)
207 * @param[in] $type (Optionnel) Type de classe à charger (Exemple : LSobjects)
209 * @author Benjamin Renard <brenard@easter-eggs.com
211 * @retval boolean true si le chargement a réussi, false sinon.
213 public static function loadLSclass($class,$type='') {
214 if (class_exists($class))
218 return self :: includeFile(LS_CLASS_DIR .'class.'.$type.$class.'.php');
222 * Chargement d'un object LdapSaisie
224 * @param[in] $object Nom de l'objet à charger
226 * @retval boolean true si le chargement a réussi, false sinon.
228 public static function loadLSobject($object) {
229 if(class_exists($object)) {
233 self :: loadLSclass('LSldapObject');
234 if (!self :: loadLSclass($object,'LSobjects')) {
237 if (!self :: includeFile( LS_OBJECTS_DIR . 'config.LSobjects.'.$object.'.php' )) {
241 if (!LSconfig :: set("LSobjects.$object",$GLOBALS['LSobjects'][$object])) {
244 else if (isset($GLOBALS['LSobjects'][$object]['LSaddons'])){
245 if (is_array($GLOBALS['LSobjects'][$object]['LSaddons'])) {
246 foreach ($GLOBALS['LSobjects'][$object]['LSaddons'] as $addon) {
247 if (!self :: loadLSaddon($addon)) {
253 if (!self :: loadLSaddon($GLOBALS['LSobjects'][$object]['LSaddons'])) {
260 LSerror :: addErrorCode('LSsession_04',$object);
267 * Chargement d'un addons d'LdapSaisie
269 * @param[in] $addon Nom de l'addon à charger (Exemple : samba)
271 * @author Benjamin Renard <brenard@easter-eggs.com
273 * @retval boolean true si le chargement a réussi, false sinon.
275 public static function loadLSaddon($addon) {
276 if(self :: includeFile(LS_ADDONS_DIR .'LSaddons.'.$addon.'.php')) {
277 self :: includeFile(LS_CONF_DIR."LSaddons/config.LSaddons.".$addon.".php");
278 if (!call_user_func('LSaddon_'. $addon .'_support')) {
279 LSerror :: addErrorCode('LSsession_02',$addon);
288 * Chargement d'une classe d'authentification d'LdapSaisie
290 * @param[in] $auth Nom de la classe d'authentification a charger (Exemple : HTTP)
292 * @author Benjamin Renard <brenard@easter-eggs.com
294 * @retval boolean true si le chargement a reussi, false sinon.
296 public static function loadLSauth($auth=false) {
297 if (self :: loadLSclass('LSauth')) {
299 if(self :: includeFile(LS_CLASS_DIR .'class.LSauth'.$auth.'.php')) {
300 self :: includeFile(LS_CONF_DIR."LSauth/config.LSauth".$auth.".php");
309 LSerror :: addErrorCode('LSsession_05','LSauth');
315 * Chargement des addons LdapSaisie
317 * Chargement des LSaddons contenue dans la variable
318 * $GLOBALS['LSaddons']['loads']
320 * @retval boolean true si le chargement a réussi, false sinon.
322 public static function loadLSaddons() {
323 $conf=LSconfig :: get('LSaddons.loads');
324 if(!is_array($conf)) {
325 LSerror :: addErrorCode('LSsession_01',"LSaddons['loads']");
329 foreach ($conf as $addon) {
330 self :: loadLSaddon($addon);
340 public static function setLocale() {
341 if (isset($_REQUEST['lang'])) {
342 $lang = $_REQUEST['lang'];
344 elseif (isset($_SESSION['LSlang'])) {
345 $lang = $_SESSION['LSlang'];
347 elseif (isset(self :: $ldapServer['lang'])) {
348 $lang = self :: $ldapServer['lang'];
351 $lang = LSconfig :: get('lang');
354 if (isset($_REQUEST['encoding'])) {
355 $encoding = $_REQUEST['encoding'];
357 elseif (isset($_SESSION['LSencoding'])) {
358 $encoding = $_SESSION['LSencoding'];
360 elseif (isset(self :: $ldapServer['encoding'])) {
361 $encoding = self :: $ldapServer['encoding'];
364 $encoding = LSconfig :: get('encoding');
367 $_SESSION['LSlang']=$lang;
369 $_SESSION['LSencoding']=$encoding;
370 self :: $encoding=$encoding;
373 if (self :: localeExist($lang,$encoding)) {
375 $lang.='.'.$encoding;
377 setlocale(LC_ALL, $lang);
378 bindtextdomain(LS_TEXT_DOMAIN, LS_I18N_DIR);
379 textdomain(LS_TEXT_DOMAIN);
381 if (is_file(LS_I18N_DIR.'/'.$lang.'/lang.php')) {
382 include(LS_I18N_DIR.'/'.$lang.'/lang.php');
386 if ($encoding && $lang) {
387 $lang.='.'.$encoding;
389 LSdebug('La locale "'.$lang.'" n\'existe pas, utilisation de la locale par défaut.');
394 * Retourne la liste des langues disponibles
396 * @retval array Tableau/Liste des langues disponibles
398 public static function getLangList() {
399 $list=array('en_US');
400 if (self :: $encoding) {
401 $regex = '^([a-zA-Z_]*)\.'.self :: $encoding.'$';
404 $regex = '^([a-zA-Z_]*)$';
406 if ($handle = opendir(LS_I18N_DIR)) {
407 while (false !== ($file = readdir($handle))) {
408 if(is_dir(LS_I18N_DIR.'/'.$file)) {
409 if (ereg($regex,$file,$regs)) {
410 if (!in_array($regs[1],$list)) {
421 * Retourne la langue courante de la session
423 * @param[in] boolean Si true, le code langue retourné sera court
425 * @retval string La langue de la session
427 public static function getLang($short=false) {
429 return strtolower(self :: $lang[0].self :: $lang[1]);
431 return self :: $lang;
435 * Vérifie si une locale est disponible
437 * @param[in] $lang string La langue (Ex : fr_FR)
438 * @param[in] $encoding string L'encodage de caractère (Ex : UTF8)
440 * @retval boolean True si la locale est disponible, False sinon
442 public static function localeExist($lang,$encoding) {
443 if ( !$lang && !$encoding ) {
446 $locale=$lang.(($encoding)?'.'.$encoding:'');
447 if ($locale=='en_US.UTF8') {
450 return (is_dir(LS_I18N_DIR.'/'.$locale));
454 * Initialisation LdapSaisie
456 * @retval boolean True si l'initialisation à réussi, false sinon.
458 public static function initialize() {
459 if (!self :: startLSconfig()) {
463 self :: startLStemplate();
469 self :: startLSerror();
470 self :: loadLSaddons();
475 * Initialisation de la session LdapSaisie
477 * Initialisation d'une LSsession :
478 * - Authentification et activation du mécanisme de session de LdapSaisie
479 * - ou Chargement des paramètres de la session à partir de la variable
480 * $_SESSION['LSsession'].
481 * - ou Destruction de la session en cas de $_GET['LSsession_logout'].
483 * @retval boolean True si l'initialisation à réussi (utilisateur authentifié), false sinon.
485 public static function startLSsession() {
486 if (!self :: initialize()) {
491 if (isset($_GET['LSsession_logout'])||isset($_GET['LSsession_recoverPassword'])) {
494 if (is_array($_SESSION['LSsession']['tmp_file'])) {
495 self :: $tmp_file = $_SESSION['LSsession']['tmp_file'];
497 self :: deleteTmpFile();
498 unset($_SESSION['LSsession']);
501 // Récupération de mot de passe
502 if (isset($_GET['recoveryHash'])) {
503 $_POST['LSsession_user'] = 'a determiner plus tard';
506 if(isset($_SESSION['LSsession']['dn'])) {
508 self :: $topDn = $_SESSION['LSsession']['topDn'];
509 self :: $dn = $_SESSION['LSsession']['dn'];
510 self :: $rdn = $_SESSION['LSsession']['rdn'];
511 self :: $ldapServerId = $_SESSION['LSsession']['ldapServerId'];
512 self :: $tmp_file = $_SESSION['LSsession']['tmp_file'];
513 self :: $authParams = $_SESSION['LSsession']['authParams'];
515 if ( self :: cacheLSprofiles() && !isset($_REQUEST['LSsession_refresh']) ) {
516 self :: setLdapServer(self :: $ldapServerId);
517 self :: $LSprofiles = $_SESSION['LSsession']['LSprofiles'];
518 self :: $LSaccess = $_SESSION['LSsession']['LSaccess'];
519 if (!self :: LSldapConnect())
523 self :: setLdapServer(self :: $ldapServerId);
524 if (!self :: LSldapConnect())
526 self :: loadLSprofiles();
529 if ( self :: cacheSudDn() && (!isset($_REQUEST['LSsession_refresh'])) ) {
530 self :: $_subDnLdapServer = $_SESSION['LSsession_subDnLdapServer'];
533 if (!self :: loadLSobject(self :: $ldapServer['authObjectType'])) {
537 self :: getLSuserObject();
539 if ( !self :: cacheLSprofiles() || isset($_REQUEST['LSsession_refresh']) ) {
540 self :: loadLSaccess();
543 $GLOBALS['Smarty'] -> assign('LSsession_username',self :: getLSuserObject() -> getDisplayName());
545 if ($_POST['LSsession_topDn']) {
546 if (self :: validSubDnLdapServer($_POST['LSsession_topDn'])) {
547 self :: $topDn = $_POST['LSsession_topDn'];
548 $_SESSION['LSsession']['topDn'] = $_POST['LSsession_topDn'];
556 // Session inexistante
557 if (isset($_POST['LSsession_ldapserver'])) {
558 self :: setLdapServer($_POST['LSsession_ldapserver']);
561 self :: setLdapServer(0);
564 // Connexion au serveur LDAP
565 if (self :: LSldapConnect()) {
568 if ( $_POST['LSsession_topDn'] != '' ){
569 self :: $topDn = $_POST['LSsession_topDn'];
572 self :: $topDn = self :: $ldapServer['ldap_config']['basedn'];
574 $_SESSION['LSsession_topDn']=self :: $topDn;
576 if (isset($_GET['LSsession_recoverPassword'])) {
577 $recoveryPasswordInfos = self :: recoverPasswd(
578 $_REQUEST['LSsession_user'],
579 $_GET['recoveryHash']
583 if (self :: loadLSauth()) {
584 if (isset(self :: $ldapServer['LSauth']['method'])) {
585 $LSauthClass = 'LSauth'.self :: $ldapServer['LSauth']['method'];
586 if (!self :: loadLSauth(self :: $ldapServer['LSauth']['method'])) {
587 LSerror :: addErrorCode('LSsession_08',self :: $ldapServer['LSauth']['method']);
588 $LSauthClass = 'LSauth';
592 $LSauthClass = 'LSauth';
595 $authObj = new $LSauthClass();
596 self :: $authParams = $authObj->params;
597 if ($authObj -> getPostData()) {
598 $LSuserObject = $authObj -> authenticate();
600 // Authentification réussi
601 self :: $LSuserObject = $LSuserObject;
602 self :: $dn = $LSuserObject->getValue('dn');
603 self :: $rdn = $LSuserObject->getValue('rdn');
604 self :: loadLSprofiles();
605 self :: loadLSaccess();
606 $GLOBALS['Smarty'] -> assign('LSsession_username',self :: getLSuserObject() -> getDisplayName());
607 $_SESSION['LSsession']=self :: getContextInfos();
615 LSerror :: addErrorCode('LSsession_09');
617 if (self :: $ldapServerId) {
618 $GLOBALS['Smarty'] -> assign('ldapServerId',self :: $ldapServerId);
620 $GLOBALS['Smarty'] -> assign('topDn',self :: $topDn);
621 if (isset($_GET['LSsession_recoverPassword'])) {
622 self :: displayRecoverPasswordForm($recoveryPasswordInfos);
624 elseif(self :: $authParams['displayLoginForm']) {
625 self :: displayLoginForm();
628 self :: setTemplate('blank.tpl');
629 LSerror :: addErrorCode('LSsession_10');
636 * Do recover password
638 * @param[in] $username string The submited username
639 * @param[in] $recoveryHash string The submited recoveryHash
641 * @retval array The recoveryPassword infos for template
643 private static function recoverPasswd($username,$recoveryHash) {
644 $recoveryPasswordInfos=array();
645 if ( self :: loadLSobject(self :: $ldapServer['authObjectType']) ) {
646 $authobject = new self :: $ldapServer['authObjectType']();
647 if (!empty($recoveryHash)) {
648 $filter=Net_LDAP2_Filter::create(
649 self :: $ldapServer['recoverPassword']['recoveryHashAttr'],
653 $result = $authobject -> listObjects($filter,self :: $topDn);
656 $result = $authobject -> searchObject(
659 self :: $ldapServer['authObjectFilter']
663 $nbresult=count($result);
666 LSdebug('hash/username incorrect');
667 LSerror :: addErrorCode('LSsession_06');
669 elseif ($nbresult>1) {
670 LSerror :: addErrorCode('LSsession_07');
673 $rdn = $result[0] -> getValue('rdn');
675 LSdebug('Recover : Id trouvé : '.$username);
676 if (self :: $ldapServer['recoverPassword']) {
677 if (self :: loadLSaddon('mail')) {
678 LSdebug('Récupération active');
680 $emailAddress = $user -> getValue(self :: $ldapServer['recoverPassword']['mailAttr']);
681 $emailAddress = $emailAddress[0];
683 if (checkEmail($emailAddress)) {
684 LSdebug('Email : '.$emailAddress);
685 self :: $dn = $user -> getDn();
687 // 1ère étape : envoie du recoveryHash
688 if (empty($recoveryHash)) {
689 $hash=self :: recoverPasswdFirstStep($user);
691 if (self :: recoverPasswdSendMail($emailAddress,1,$hash)) {
692 // Mail a bien été envoyé
693 $recoveryPasswordInfos['recoveryHashMail']=$emailAddress;
697 // 2nd étape : génération du mot de passe + envoie par mail
699 $pwd=self :: recoverPasswdSecondStep($user);
701 if (self :: recoverPasswdSendMail($emailAddress,2,$pwd)){
702 // Mail a bien été envoyé
703 $recoveryPasswordInfos['newPasswordMail']=$emailAddress;
709 LSerror :: addErrorCode('LSsession_19');
714 LSerror :: addErrorCode('LSsession_18');
718 return $recoveryPasswordInfos;
722 * Send recover password mail
724 * @param[in] $mail string The user's mail
725 * @param[in] $step integer The step
726 * @param[in] $info string The info for formatted message
728 * @retval boolean True on success or False
730 private static function recoverPasswdSendMail($mail,$step,$info) {
733 if (self :: $ldapServer['recoverPassword']['recoveryEmailSender']) {
734 $sendParams['From']=self :: $ldapServer['recoverPassword']['recoveryEmailSender'];
738 if ($_SERVER['HTTPS']=='on') {
739 $recovery_url='https://';
742 $recovery_url='http://';
744 $recovery_url .= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'&recoveryHash='.$info;
746 $subject = self :: $ldapServer['recoverPassword']['recoveryHashMail']['subject'];
748 self :: $ldapServer['recoverPassword']['recoveryHashMail']['msg'],
753 $subject = self :: $ldapServer['recoverPassword']['newPasswordMail']['subject'];
755 self :: $ldapServer['recoverPassword']['newPasswordMail']['msg'],
760 if (!sendMail($mail,$subject,$msg,$sendParams)) {
761 LSdebug("Problème durant l'envoie du mail");
762 LSerror :: addErrorCode('LSsession_20',4);
770 * Do first step of recovering password
772 * @param[in] $user LSldapObject The LSldapObject of the user
774 * @retval string|False The recory hash on success or False
776 private static function recoverPasswdFirstStep($user) {
778 $rdn=$user -> getValue('rdn');
780 $recovery_hash = md5($rdn . strval(time()) . strval(rand()));
782 $lostPasswdForm = $user -> getForm('lostPassword');
783 $lostPasswdForm -> setPostData(
785 self :: $ldapServer['recoverPassword']['recoveryHashAttr'] => $recovery_hash
790 if($lostPasswdForm -> validate()) {
791 if ($user -> updateData('lostPassword')) {
792 // recoveryHash de l'utilisateur mis à jour
793 return $recovery_hash;
796 // Erreur durant la mise à jour de l'objet
797 LSdebug("Erreur durant la mise à jour de l'objet");
798 LSerror :: addErrorCode('LSsession_20',6);
802 // Erreur durant la validation du formulaire de modification de perte de password
803 LSdebug("Erreur durant la validation du formulaire de modification de perte de password");
804 LSerror :: addErrorCode('LSsession_20',5);
810 * Do second step of recovering password
812 * @param[in] $user LSldapObject The LSldapObject of the user
814 * @retval string|False The new password on success or False
816 private static function recoverPasswdSecondStep($user) {
817 $attr=$user -> attrs[self :: $ldapServer['authObjectTypeAttrPwd']];
818 if ($attr instanceof LSattribute) {
819 $mdp = generatePassword(
820 $attr -> config['html_options']['chars'],
821 $attr -> config['html_options']['lenght']
823 LSdebug('Nvx mpd : '.$mdp);
824 $lostPasswdForm = $user -> getForm('lostPassword');
825 $lostPasswdForm -> setPostData(
827 self :: $ldapServer['recoverPassword']['recoveryHashAttr'] => array(''),
828 self :: $ldapServer['authObjectTypeAttrPwd'] => array($mdp)
832 if($lostPasswdForm -> validate()) {
833 if ($user -> updateData('lostPassword')) {
837 // Erreur durant la mise à jour de l'objet
838 LSdebug("Erreur durant la mise à jour de l'objet");
839 LSerror :: addErrorCode('LSsession_20',3);
843 // Erreur durant la validation du formulaire de modification de perte de password
844 LSdebug("Erreur durant la validation du formulaire de modification de perte de password");
845 LSerror :: addErrorCode('LSsession_20',2);
849 // l'attribut password n'existe pas
850 LSdebug("L'attribut password n'existe pas");
851 LSerror :: addErrorCode('LSsession_20',1);
857 * Retourne les informations du contexte
859 * @author Benjamin Renard <brenard@easter-eggs.com
861 * @retval array Tableau associatif des informations du contexte
863 private static function getContextInfos() {
865 'tmp_file' => self :: $tmp_file,
866 'topDn' => self :: $topDn,
868 'rdn' => self :: $rdn,
869 'ldapServerId' => self :: $ldapServerId,
870 'ldapServer' => self :: $ldapServer,
871 'LSprofiles' => self :: $LSprofiles,
872 'LSaccess' => self :: $LSaccess,
873 'authParams' => self :: $authParams
878 * Retourne l'objet de l'utilisateur connecté
880 * @author Benjamin Renard <brenard@easter-eggs.com
882 * @retval mixed L'objet de l'utilisateur connecté ou false si il n'a pas put
885 public static function getLSuserObject($dn=null) {
889 if (!self :: $LSuserObject) {
890 if (self :: loadLSobject(self :: $ldapServer['authObjectType'])) {
891 self :: $LSuserObject = new self :: $ldapServer['authObjectType']();
892 self :: $LSuserObject -> loadData(self :: $dn);
898 return self :: $LSuserObject;
902 * Retourne le DN de l'utilisateur connecté
904 * @author Benjamin Renard <brenard@easter-eggs.com
906 * @retval string Le DN de l'utilisateur connecté
908 public static function getLSuserObjectDn() {
913 * Modifie l'utilisateur connecté à la volé
915 * @param[in] $object Mixed L'objet Ldap du nouvel utilisateur
916 * le type doit correspondre à
917 * self :: $ldapServer['authObjectType']
919 * @retval boolean True en cas de succès, false sinon
921 public static function changeAuthUser($object) {
922 if ($object instanceof self :: $ldapServer['authObjectType']) {
923 self :: $dn = $object -> getDn();
924 $rdn = $object -> getValue('rdn');
929 self :: $LSuserObject = $object;
931 if(self :: loadLSprofiles()) {
932 self :: loadLSaccess();
933 $_SESSION['LSsession']=self :: getContextInfos();
941 * Définition du serveur Ldap de la session
943 * Définition du serveur Ldap de la session à partir de son ID dans
944 * le tableau LSconfig :: get('ldap_servers').
946 * @param[in] integer Index du serveur Ldap
948 * @retval boolean True sinon false.
950 public static function setLdapServer($id) {
951 $conf = LSconfig :: get("ldap_servers.$id");
952 if ( is_array($conf) ) {
953 self :: $ldapServerId = $id;
954 self :: $ldapServer = $conf;
964 * Connexion au serveur Ldap
966 * @retval boolean True sinon false.
968 public static function LSldapConnect() {
969 if (self :: $ldapServer) {
970 self :: includeFile(LSconfig :: get('NetLDAP2'));
971 if (!self :: loadLSclass('LSldap')) {
974 LSldap :: connect(self :: $ldapServer['ldap_config']);
975 if (LSldap :: isConnected()) {
983 LSerror :: addErrorCode('LSsession_03');
989 * Use this function to know if subDn is enabled for the curent LdapServer
993 public static function subDnIsEnabled() {
994 if (!isset(self :: $ldapServer['subDn'])) {
997 if ( !is_array(self :: $ldapServer['subDn']) ) {
1004 * Retourne les sous-dns du serveur Ldap courant
1006 * @retval mixed Tableau des subDn, false si une erreur est survenue.
1008 public static function getSubDnLdapServer() {
1009 if (self :: cacheSudDn() && isset(self :: $_subDnLdapServer[self :: $ldapServerId])) {
1010 return self :: $_subDnLdapServer[self :: $ldapServerId];
1012 if (!self::subDnIsEnabled()) {
1016 foreach(self :: $ldapServer['subDn'] as $subDn_name => $subDn_config) {
1017 if ($subDn_name == 'LSobject') {
1018 if (is_array($subDn_config)) {
1019 foreach($subDn_config as $LSobject_name => $LSoject_config) {
1020 if ($LSoject_config['basedn']) {
1021 $basedn = $LSoject_config['basedn'];
1024 $basedn = self::getRootDn();
1026 if ($LSoject_config['displayName']) {
1027 $displayName = $LSoject_config['displayName'];
1030 $displayName = NULL;
1032 if( self :: loadLSobject($LSobject_name) ) {
1033 if ($subdnobject = new $LSobject_name()) {
1034 $tbl_return = $subdnobject -> getSelectArray(NULL,$basedn,$displayName);
1035 if (is_array($tbl_return)) {
1036 $return=array_merge($return,$tbl_return);
1039 LSerror :: addErrorCode('LSsession_17',3);
1043 LSerror :: addErrorCode('LSsession_17',2);
1049 LSerror :: addErrorCode('LSsession_17',1);
1053 if ((isCompatibleDNs($subDn_config['dn'],self :: $ldapServer['ldap_config']['basedn']))&&($subDn_config['dn']!="")) {
1054 $return[$subDn_config['dn']] = __($subDn_name);
1058 if (self :: cacheSudDn()) {
1059 self :: $_subDnLdapServer[self :: $ldapServerId]=$return;
1060 $_SESSION['LSsession_subDnLdapServer'] = self :: $_subDnLdapServer;
1066 * Retourne la liste de subDn du serveur Ldap utilise
1067 * trié par la profondeur dans l'arboressence (ordre décroissant)
1069 * @return array() Tableau des subDn trié
1071 public static function getSortSubDnLdapServer() {
1072 $subDnLdapServer = self :: getSubDnLdapServer();
1073 if (!$subDnLdapServer) {
1076 uksort($subDnLdapServer,"compareDn");
1077 return $subDnLdapServer;
1081 * Retourne les options d'une liste déroulante pour le choix du topDn
1082 * de connexion au serveur Ldap
1084 * Liste les subdn (self :: $ldapServer['subDn'])
1086 * @retval string Les options (<option>) pour la sélection du topDn.
1088 public static function getSubDnLdapServerOptions($selected=NULL) {
1089 $list = self :: getSubDnLdapServer();
1093 foreach($list as $dn => $txt) {
1094 if ($selected && ($selected==$dn)) {
1095 $selected_txt = ' selected';
1100 $display.="<option value=\"".$dn."\"$selected_txt>".$txt."</option>\n";
1108 * Vérifie qu'un subDn est déclaré
1110 * @param[in] string Un subDn
1112 * @retval boolean True si le subDn existe, False sinon
1114 public static function validSubDnLdapServer($subDn) {
1115 $listTopDn = self :: getSubDnLdapServer();
1116 if(is_array($listTopDn)) {
1117 foreach($listTopDn as $dn => $txt) {
1127 * Test un couple LSobject/pwd
1129 * Test un bind sur le serveur avec le dn de l'objet et le mot de passe fourni.
1131 * @param[in] LSobject L'object "user" pour l'authentification
1132 * @param[in] string Le mot de passe à tester
1134 * @retval boolean True si l'authentification à réussi, false sinon.
1136 public static function checkUserPwd($object,$pwd) {
1137 return LSldap :: checkBind($object -> getValue('dn'),$pwd);
1141 * Affiche le formulaire de login
1143 * Défini les informations pour le template Smarty du formulaire de login.
1147 public static function displayLoginForm() {
1148 $GLOBALS['Smarty'] -> assign('pagetitle',_('Connection'));
1149 if (isset($_GET['LSsession_logout'])) {
1150 $GLOBALS['Smarty'] -> assign('loginform_action','index.php');
1153 $GLOBALS['Smarty'] -> assign('loginform_action',$_SERVER['REQUEST_URI']);
1155 if (count(LSconfig :: get('ldap_servers'))==1) {
1156 $GLOBALS['Smarty'] -> assign('loginform_ldapserver_style','style="display: none"');
1158 $GLOBALS['Smarty'] -> assign('loginform_label_ldapserver',_('LDAP server'));
1159 $ldapservers_name=array();
1160 $ldapservers_index=array();
1161 foreach(LSconfig :: get('ldap_servers') as $id => $infos) {
1162 $ldapservers_index[]=$id;
1163 $ldapservers_name[]=__($infos['name']);
1165 $GLOBALS['Smarty'] -> assign('loginform_ldapservers_name',$ldapservers_name);
1166 $GLOBALS['Smarty'] -> assign('loginform_ldapservers_index',$ldapservers_index);
1168 $GLOBALS['Smarty'] -> assign('loginform_label_level',_('Level'));
1169 $GLOBALS['Smarty'] -> assign('loginform_label_user',_('Identifier'));
1170 $GLOBALS['Smarty'] -> assign('loginform_label_pwd',_('Password'));
1171 $GLOBALS['Smarty'] -> assign('loginform_label_submit',_('Connect'));
1172 $GLOBALS['Smarty'] -> assign('loginform_label_recoverPassword',_('Forgot your password ?'));
1174 self :: setTemplate('login.tpl');
1175 self :: addJSscript('LSsession_login.js');
1179 * Affiche le formulaire de récupération de mot de passe
1181 * Défini les informations pour le template Smarty du formulaire de
1182 * récupération de mot de passe
1184 * @param[in] $infos array() Information sur le status du processus de
1185 * recouvrement de mot de passe
1189 public static function displayRecoverPasswordForm($recoveryPasswordInfos) {
1190 $GLOBALS['Smarty'] -> assign('pagetitle',_('Recovery of your credentials'));
1191 $GLOBALS['Smarty'] -> assign('recoverpasswordform_action','index.php?LSsession_recoverPassword');
1193 if (count(LSconfig :: get('ldap_servers'))==1) {
1194 $GLOBALS['Smarty'] -> assign('recoverpasswordform_ldapserver_style','style="display: none"');
1197 $GLOBALS['Smarty'] -> assign('recoverpasswordform_label_ldapserver',_('LDAP server'));
1198 $ldapservers_name=array();
1199 $ldapservers_index=array();
1200 foreach(LSconfig :: get('ldap_servers') as $id => $infos) {
1201 $ldapservers_index[]=$id;
1202 $ldapservers_name[]=$infos['name'];
1204 $GLOBALS['Smarty'] -> assign('recoverpasswordform_ldapservers_name',$ldapservers_name);
1205 $GLOBALS['Smarty'] -> assign('recoverpasswordform_ldapservers_index',$ldapservers_index);
1207 $GLOBALS['Smarty'] -> assign('recoverpasswordform_label_user',_('Identifier'));
1208 $GLOBALS['Smarty'] -> assign('recoverpasswordform_label_submit',_('Validate'));
1209 $GLOBALS['Smarty'] -> assign('recoverpasswordform_label_back',_('Back'));
1211 $recoverpassword_msg = _('Please fill the identifier field to proceed recovery procedure');
1213 if (isset($recoveryPasswordInfos['recoveryHashMail'])) {
1214 $recoverpassword_msg = getFData(
1215 _("An email has been sent to %{mail}. " .
1216 "Please follow the instructions on it."),
1217 $recoveryPasswordInfos['recoveryHashMail']
1221 if (isset($recoveryPasswordInfos['newPasswordMail'])) {
1222 $recoverpassword_msg = getFData(
1223 _("Your new password has been sent to %{mail}. "),
1224 $recoveryPasswordInfos['newPasswordMail']
1228 $GLOBALS['Smarty'] -> assign('recoverpassword_msg',$recoverpassword_msg);
1230 self :: setTemplate('recoverpassword.tpl');
1231 self :: addJSscript('LSsession_recoverPassword.js');
1235 * Défini le template Smarty à utiliser
1237 * Remarque : les fichiers de templates doivent se trouver dans le dossier
1240 * @param[in] string Le nom du fichier de template
1244 public static function setTemplate($template) {
1245 self :: $template = $template;
1249 * Ajoute un script JS au chargement de la page
1251 * Remarque : les scripts doivents être dans le dossier LS_JS_DIR.
1253 * @param[in] $script Le nom du fichier de script à charger.
1257 public static function addJSscript($file,$path=NULL) {
1262 self :: $JSscripts[$path.$file]=$script;
1266 * Ajouter un paramètre de configuration Javascript
1268 * @param[in] $name string Nom de la variable de configuration
1269 * @param[in] $val mixed Valeur de la variable de configuration
1273 public static function addJSconfigParam($name,$val) {
1274 self :: $_JSconfigParams[$name]=$val;
1278 * Ajoute une feuille de style au chargement de la page
1280 * Remarque : les scripts doivents être dans le dossier LS_CSS_DIR.
1282 * @param[in] $script Le nom du fichier css à charger.
1286 public static function addCssFile($file,$path=NULL) {
1291 self :: $CssFiles[$path.$file]=$cssFile;
1295 * Affiche le template Smarty
1297 * Charge les dépendances et affiche le template Smarty
1301 public static function displayTemplate() {
1304 foreach ($GLOBALS['defaultJSscipts'] as $script) {
1305 $JSscript_txt.="<script src='".LS_JS_DIR.$script."' type='text/javascript'></script>\n";
1308 foreach (self :: $JSscripts as $script) {
1309 if (!$script['path']) {
1310 $script['path']=LS_JS_DIR;
1313 $script['path'].='/';
1315 $JSscript_txt.="<script src='".$script['path'].$script['file']."' type='text/javascript'></script>\n";
1318 $KAconf = LSconfig :: get('keepLSsessionActive');
1321 (!isset(self :: $ldapServer['keepLSsessionActive']))
1323 (!($KAconf === false))
1326 (self :: $ldapServer['keepLSsessionActive'])
1328 self :: addJSconfigParam('keepLSsessionActive',ini_get('session.gc_maxlifetime'));
1331 $GLOBALS['Smarty'] -> assign('LSjsConfig',json_encode(self :: $_JSconfigParams));
1334 $JSscript_txt.="<script type='text/javascript'>LSdebug_active = 1;</script>\n";
1337 $JSscript_txt.="<script type='text/javascript'>LSdebug_active = 0;</script>\n";
1340 $GLOBALS['Smarty'] -> assign('LSsession_js',$JSscript_txt);
1343 self :: addCssFile("LSdefault.css");
1345 foreach (self :: $CssFiles as $file) {
1346 if (!$file['path']) {
1347 $file['path']=LS_CSS_DIR.'/';
1349 $Css_txt.="<link rel='stylesheet' type='text/css' href='".$file['path'].$file['file']."' />\n";
1351 $GLOBALS['Smarty'] -> assign('LSsession_css',$Css_txt);
1353 if (isset(self :: $LSaccess[self :: $topDn])) {
1354 $GLOBALS['Smarty'] -> assign('LSaccess',self :: $LSaccess[self :: $topDn]);
1358 $listTopDn = self :: getSubDnLdapServer();
1359 if (is_array($listTopDn)) {
1361 $GLOBALS['Smarty'] -> assign('label_level',self :: getSubDnLabel());
1362 $GLOBALS['Smarty'] -> assign('_refresh',_('Refresh'));
1363 $LSsession_topDn_index = array();
1364 $LSsession_topDn_name = array();
1365 foreach($listTopDn as $index => $name) {
1366 $LSsession_topDn_index[] = $index;
1367 $LSsession_topDn_name[] = $name;
1369 $GLOBALS['Smarty'] -> assign('LSsession_subDn_indexes',$LSsession_topDn_index);
1370 $GLOBALS['Smarty'] -> assign('LSsession_subDn_names',$LSsession_topDn_name);
1371 $GLOBALS['Smarty'] -> assign('LSsession_subDn',self :: $topDn);
1372 $GLOBALS['Smarty'] -> assign('LSsession_subDnName',self :: getSubDnName());
1375 $GLOBALS['Smarty'] -> assign('LSlanguages',self :: getLangList());
1376 $GLOBALS['Smarty'] -> assign('LSlang',self :: $lang);
1377 $GLOBALS['Smarty'] -> assign('LSencoding',self :: $encoding);
1378 $GLOBALS['Smarty'] -> assign('lang_label',_('Language'));
1380 $GLOBALS['Smarty'] -> assign('displayLogoutBtn',self :: $authParams['displayLogoutBtn']);
1383 if((!empty($_SESSION['LSsession_infos']))&&(is_array($_SESSION['LSsession_infos']))) {
1384 $txt_infos="<ul>\n";
1385 foreach($_SESSION['LSsession_infos'] as $info) {
1386 $txt_infos.="<li>$info</li>\n";
1388 $txt_infos.="</ul>\n";
1389 $GLOBALS['Smarty'] -> assign('LSinfos',$txt_infos);
1390 $_SESSION['LSsession_infos']=array();
1393 if (self :: $ajaxDisplay) {
1394 $GLOBALS['Smarty'] -> assign('LSerror_txt',LSerror :: getErrors());
1395 $GLOBALS['Smarty'] -> assign('LSdebug_txt',LSdebug_print(true));
1398 LSerror :: display();
1401 if (!self :: $template)
1402 self :: setTemplate('empty.tpl');
1404 $GLOBALS['Smarty'] -> assign('connected_as',_("Connected as"));
1406 $GLOBALS['Smarty'] -> display(self :: $template);
1410 * Défini que l'affichage se fera ou non via un retour Ajax
1412 * @param[in] $val boolean True pour que l'affichage se fasse par un retour
1416 public static function setAjaxDisplay($val=true) {
1417 self :: $ajaxDisplay = (boolean)$val;
1421 * Affiche un retour Ajax
1425 public static function displayAjaxReturn($data=array()) {
1426 if (isset($data['LSredirect']) && (!LSdebugDefined()) ) {
1427 echo json_encode($data);
1431 $data['LSjsConfig'] = self :: $_JSconfigParams;
1434 if((!empty($_SESSION['LSsession_infos']))&&(is_array($_SESSION['LSsession_infos']))) {
1435 $txt_infos="<ul>\n";
1436 foreach($_SESSION['LSsession_infos'] as $info) {
1437 $txt_infos.="<li>$info</li>\n";
1439 $txt_infos.="</ul>\n";
1440 $data['LSinfos'] = $txt_infos;
1441 $_SESSION['LSsession_infos']=array();
1444 if (LSerror :: errorsDefined()) {
1445 $data['LSerror'] = LSerror :: getErrors();
1448 if (isset($_REQUEST['imgload'])) {
1449 $data['imgload'] = $_REQUEST['imgload'];
1452 if (LSdebugDefined()) {
1453 $data['LSdebug'] = LSdebug_print(true,false);
1456 echo json_encode($data);
1460 * Retournne un template Smarty compilé
1462 * @param[in] string $template Le template à retourner
1463 * @param[in] array $variables Variables Smarty à assigner avant l'affichage
1465 * @retval string Le HTML compilé du template
1467 public static function fetchTemplate($template,$variables=array()) {
1468 foreach($variables as $name => $val) {
1469 $GLOBALS['Smarty'] -> assign($name,$val);
1471 return $GLOBALS['Smarty'] -> fetch($template);
1475 * Charge les droits LS de l'utilisateur
1477 * @retval boolean True si le chargement à réussi, false sinon.
1479 private static function loadLSprofiles() {
1480 if (is_array(self :: $ldapServer['LSprofiles'])) {
1481 foreach (self :: $ldapServer['LSprofiles'] as $profile => $profileInfos) {
1482 if (is_array($profileInfos)) {
1483 foreach ($profileInfos as $topDn => $rightsInfos) {
1485 * If $topDn == 'LSobject', we search for each LSobject type to find
1486 * all items on witch the user will have powers.
1488 if ($topDn == 'LSobjects') {
1489 if (is_array($rightsInfos)) {
1490 foreach ($rightsInfos as $LSobject => $listInfos) {
1491 if (self :: loadLSclass('LSsearch')) {
1492 if ($listInfos['filter']) {
1493 $filter = self :: getLSuserObject() -> getFData($listInfos['filter']);
1496 $filter = '('.$listInfos['attr'].'='.self :: getLSuserObject() -> getFData($listInfos['attr_value']).')';
1500 'basedn' => $listInfos['basedn'],
1504 if (is_array($listInfos['params'])) {
1505 $params = array_merge($listInfos['params'],$params);
1508 $LSsearch = new LSsearch($LSobject,'LSsession :: loadLSprofiles',$params,true);
1509 $LSsearch -> run(false);
1511 $LSprofiles[$profile] = $LSsearch -> listObjectsDn();
1516 LSdebug('LSobjects => [] doit etre un tableau');
1520 if (is_array($rightsInfos)) {
1521 foreach($rightsInfos as $dn => $conf) {
1522 if ((isset($conf['attr'])) && (isset($conf['LSobject']))) {
1523 if( self :: loadLSobject($conf['LSobject']) ) {
1524 if ($object = new $conf['LSobject']()) {
1525 if ($object -> loadData($dn)) {
1526 $listDns=$object -> getValue($conf['attr']);
1527 $valKey = (isset($conf['attr_value']))?$conf['attr_value']:'%{dn}';
1528 $val = self :: getLSuserObject() -> getFData($valKey);
1529 if (is_array($listDns)) {
1530 if (in_array($val,$listDns)) {
1531 self :: $LSprofiles[$profile][] = $topDn;
1536 LSdebug('Impossible de chargé le dn : '.$dn);
1540 LSdebug('Impossible de créer l\'objet de type : '.$conf['LSobject']);
1545 if (self :: $dn == $dn) {
1546 self :: $LSprofiles[$profile][] = $topDn;
1552 if ( self :: $dn == $rightsInfos ) {
1553 self :: $LSprofiles[$profile][] = $topDn;
1556 } // fin else ($topDn == 'LSobjects')
1557 } // fin foreach($profileInfos)
1558 } // fin is_array($profileInfos)
1559 } // fin foreach LSprofiles
1560 LSdebug(self :: $LSprofiles);
1569 * Charge les droits d'accès de l'utilisateur pour construire le menu de l'interface
1573 private static function loadLSaccess() {
1575 if (is_array(self :: $ldapServer['subDn'])) {
1576 foreach(self :: $ldapServer['subDn'] as $name => $config) {
1577 if ($name=='LSobject') {
1578 if (is_array($config)) {
1580 // Définition des subDns
1581 foreach($config as $objectType => $objectConf) {
1582 if (self :: loadLSobject($objectType)) {
1583 if ($subdnobject = new $objectType()) {
1584 $tbl = $subdnobject -> getSelectArray(NULL,self::getRootDn(),NULL,NULL,false);
1585 if (is_array($tbl)) {
1586 // Définition des accès
1588 if (is_array($objectConf['LSobjects'])) {
1589 foreach($objectConf['LSobjects'] as $type) {
1590 if (self :: loadLSobject($type)) {
1591 if (self :: canAccess($type)) {
1592 $access[$type] = LSconfig :: get('LSobjects.'.$type.'.label');
1597 foreach($tbl as $dn => $dn_name) {
1598 $LSaccess[$dn]=$access;
1607 if ((isCompatibleDNs(self :: $ldapServer['ldap_config']['basedn'],$config['dn']))&&($config['dn']!='')) {
1609 if (is_array($config['LSobjects'])) {
1610 foreach($config['LSobjects'] as $objectType) {
1611 if (self :: loadLSobject($objectType)) {
1612 if (self :: canAccess($objectType)) {
1613 $access[$objectType] = LSconfig :: get('LSobjects.'.$objectType.'.label');
1618 $LSaccess[$config['dn']]=$access;
1624 if(is_array(self :: $ldapServer['LSaccess'])) {
1626 foreach(self :: $ldapServer['LSaccess'] as $objectType) {
1627 if (self :: loadLSobject($objectType)) {
1628 if (self :: canAccess($objectType)) {
1629 $access[$objectType] = LSconfig :: get('LSobjects.'.$objectType.'.label');
1633 $LSaccess[self :: $topDn] = $access;
1636 foreach($LSaccess as $dn => $access) {
1637 $LSaccess[$dn] = array_merge(
1639 'SELF' => 'My account'
1645 self :: $LSaccess = $LSaccess;
1646 $_SESSION['LSsession']['LSaccess'] = $LSaccess;
1650 * Dit si l'utilisateur est du profil pour le DN spécifié
1652 * @param[in] string $profile de l'objet
1653 * @param[in] string $dn DN de l'objet
1655 * @retval boolean True si l'utilisateur est du profil sur l'objet, false sinon.
1657 public static function isLSprofile($dn,$profile) {
1658 if (is_array(self :: $LSprofiles[$profile])) {
1659 foreach(self :: $LSprofiles[$profile] as $topDn) {
1663 else if ( isCompatibleDNs($dn,$topDn) ) {
1672 * Retourne qui est l'utilisateur par rapport à l'object
1674 * @param[in] string Le DN de l'objet
1676 * @retval string 'admin'/'self'/'user' pour Admin , l'utilisateur lui même ou un simple utilisateur
1678 public static function whoami($dn) {
1679 $retval = array('user');
1681 foreach(self :: $LSprofiles as $profile => $infos) {
1682 if(self :: isLSprofile($dn,$profile)) {
1687 if (self :: $dn == $dn) {
1695 * Retourne le droit de l'utilisateur à accèder à un objet
1697 * @param[in] string $LSobject Le type de l'objet
1698 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1699 * @param[in] string $right Le type de droit d'accès à tester ('r'/'w')
1700 * @param[in] string $attr Le nom de l'attribut auquel on test l'accès
1702 * @retval boolean True si l'utilisateur a accès, false sinon
1704 public static function canAccess($LSobject,$dn=NULL,$right=NULL,$attr=NULL) {
1705 if (!self :: loadLSobject($LSobject)) {
1709 $whoami = self :: whoami($dn);
1710 if ($dn==self :: getLSuserObject() -> getValue('dn')) {
1711 if (!self :: in_menu('SELF')) {
1716 $obj = new $LSobject();
1718 if (!self :: in_menu($LSobject,$obj -> subDnValue)) {
1724 $objectdn=LSconfig :: get('LSobjects.'.$LSobject.'.container_dn').','.self :: $topDn;
1725 $whoami = self :: whoami($objectdn);
1728 // Pour un attribut particulier
1731 $attr=LSconfig :: get('LSobjects.'.$LSobject.'.rdn');
1733 if (!is_array(LSconfig :: get('LSobjects.'.$LSobject.'.attrs.'.$attr))) {
1738 foreach($whoami as $who) {
1739 $nr = LSconfig :: get('LSobjects.'.$LSobject.'.attrs.'.$attr.'.rights.'.$who);
1743 else if($nr == 'r') {
1750 if (($right=='r')||($right=='w')) {
1757 if ( ($r=='r') || ($r=='w') ) {
1764 // Pour un attribut quelconque
1765 $attrs_conf=LSconfig :: get('LSobjects.'.$LSobject.'.attrs');
1766 if (is_array($attrs_conf)) {
1767 if (($right=='r')||($right=='w')) {
1768 foreach($whoami as $who) {
1769 foreach ($attrs_conf as $attr_name => $attr_config) {
1770 if ($attr_config['rights'][$who]==$right) {
1777 foreach($whoami as $who) {
1778 foreach ($attrs_conf as $attr_name => $attr_config) {
1779 if ( ($attr_config['rights'][$who]=='r') || ($attr_config['rights'][$who]=='w') ) {
1790 * Retourne le droit de l'utilisateur à editer à un objet
1792 * @param[in] string $LSobject Le type de l'objet
1793 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1794 * @param[in] string $attr Le nom de l'attribut auquel on test l'accès
1796 * @retval boolean True si l'utilisateur a accès, false sinon
1798 public static function canEdit($LSobject,$dn=NULL,$attr=NULL) {
1799 return self :: canAccess($LSobject,$dn,'w',$attr);
1803 * Retourne le droit de l'utilisateur à supprimer un objet
1805 * @param[in] string $LSobject Le type de l'objet
1806 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1808 * @retval boolean True si l'utilisateur a accès, false sinon
1810 public static function canRemove($LSobject,$dn) {
1811 return self :: canAccess($LSobject,$dn,'w','rdn');
1815 * Retourne le droit de l'utilisateur à créer un objet
1817 * @param[in] string $LSobject Le type de l'objet
1819 * @retval boolean True si l'utilisateur a accès, false sinon
1821 public static function canCreate($LSobject) {
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 = $relConf['rights'][$who];
1848 else if($nr == 'r') {
1860 foreach($whoami as $who) {
1861 if (($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 (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 (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 (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() ) {
2199 if (isset($_SESSION['LSsession_topDn'])) {
2200 $sel = $_SESSION['LSsession_topDn'];
2205 $list = self :: getSubDnLdapServerOptions($sel);
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']));