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;
87 // The LSauht object of the session
88 private static $LSauthObject = false;
91 * Include un fichier PHP
93 * @author Benjamin Renard <brenard@easter-eggs.com>
95 * @retval true si tout c'est bien passé, false sinon
97 public static function includeFile($file) {
98 if (!file_exists($file)) {
101 if (defined('LSdebug') && constant('LSdebug')) {
102 return include_once($file);
105 return @include_once($file);
111 * Lancement de LSconfig
113 * @author Benjamin Renard <brenard@easter-eggs.com>
115 * @retval true si tout c'est bien passé, false sinon
117 private static function startLSconfig() {
118 if (self :: loadLSclass('LSconfig')) {
119 if (LSconfig :: start()) {
123 die("ERROR : Can't load configuration files.");
128 * Lancement et initialisation de Smarty
130 * @author Benjamin Renard <brenard@easter-eggs.com>
132 * @retval true si tout c'est bien passé, false sinon
134 private static function startLStemplate() {
135 if ( self :: includeFile(LSconfig :: get('Smarty')) ) {
136 $GLOBALS['Smarty'] = new Smarty();
137 $GLOBALS['Smarty'] -> template_dir = LS_TEMPLATES_DIR;
138 $GLOBALS['Smarty'] -> compile_dir = LS_TMP_DIR;
141 $GLOBALS['Smarty'] -> caching = 0;
142 // cache files are always regenerated
143 $GLOBALS['Smarty'] -> force_compile = TRUE;
144 // recompile template if it is changed
145 $GLOBALS['Smarty'] -> compile_check = TRUE;
146 if (isset($_REQUEST['debug_smarty'])) {
148 $GLOBALS['Smarty'] -> debugging = true;
152 $GLOBALS['Smarty'] -> register_function('getFData','smarty_getFData');
154 $GLOBALS['Smarty'] -> assign('LS_CSS_DIR',LS_CSS_DIR);
155 $GLOBALS['Smarty'] -> assign('LS_IMAGES_DIR',LS_IMAGES_DIR);
157 self :: addJSconfigParam('LS_IMAGES_DIR',LS_IMAGES_DIR);
160 die("ERROR : Can't load Smarty.");
165 * Retourne le topDn de la session
167 * @author Benjamin Renard <brenard@easter-eggs.com>
169 * @retval string le topDn de la session
171 public static function getTopDn() {
172 if (!is_null(self :: $topDn)) {
173 return self :: $topDn;
176 return self :: getRootDn();
181 * Retourne le rootDn de la session
183 * @author Benjamin Renard <brenard@easter-eggs.com>
185 * @retval string le rootDn de la session
187 public static function getRootDn() {
188 return self :: $ldapServer['ldap_config']['basedn'];
192 * Initialisation de la gestion des erreurs
194 * Création de l'objet LSerror
196 * @author Benjamin Renard <brenard@easter-eggs.com
198 * @retval boolean true si l'initialisation a réussi, false sinon.
200 private static function startLSerror() {
201 if(!self :: loadLSclass('LSerror')) {
204 self :: defineLSerrors();
209 * Chargement d'une classe d'LdapSaisie
211 * @param[in] $class Nom de la classe à charger (Exemple : LSpeople)
212 * @param[in] $type (Optionnel) Type de classe à charger (Exemple : LSobjects)
214 * @author Benjamin Renard <brenard@easter-eggs.com
216 * @retval boolean true si le chargement a réussi, false sinon.
218 public static function loadLSclass($class,$type='') {
219 if (class_exists($class))
223 return self :: includeFile(LS_CLASS_DIR .'class.'.$type.$class.'.php');
227 * Chargement d'un object LdapSaisie
229 * @param[in] $object Nom de l'objet à charger
231 * @retval boolean true si le chargement a réussi, false sinon.
233 public static function loadLSobject($object) {
234 if(class_exists($object)) {
238 self :: loadLSclass('LSldapObject');
239 if (!self :: loadLSclass($object,'LSobjects')) {
242 if (!self :: includeFile( LS_OBJECTS_DIR . 'config.LSobjects.'.$object.'.php' )) {
246 if (!LSconfig :: set("LSobjects.$object",$GLOBALS['LSobjects'][$object])) {
249 else if (isset($GLOBALS['LSobjects'][$object]['LSaddons'])){
250 if (is_array($GLOBALS['LSobjects'][$object]['LSaddons'])) {
251 foreach ($GLOBALS['LSobjects'][$object]['LSaddons'] as $addon) {
252 if (!self :: loadLSaddon($addon)) {
258 if (!self :: loadLSaddon($GLOBALS['LSobjects'][$object]['LSaddons'])) {
265 LSerror :: addErrorCode('LSsession_04',$object);
272 * Chargement d'un addons d'LdapSaisie
274 * @param[in] $addon Nom de l'addon à charger (Exemple : samba)
276 * @author Benjamin Renard <brenard@easter-eggs.com
278 * @retval boolean true si le chargement a réussi, false sinon.
280 public static function loadLSaddon($addon) {
281 if(self :: includeFile(LS_ADDONS_DIR .'LSaddons.'.$addon.'.php')) {
282 self :: includeFile(LS_CONF_DIR."LSaddons/config.LSaddons.".$addon.".php");
283 if (!call_user_func('LSaddon_'. $addon .'_support')) {
284 LSerror :: addErrorCode('LSsession_02',$addon);
293 * Chargement d'une classe d'authentification d'LdapSaisie
295 * @param[in] $auth Nom de la classe d'authentification a charger (Exemple : HTTP)
297 * @author Benjamin Renard <brenard@easter-eggs.com
299 * @retval boolean true si le chargement a reussi, false sinon.
301 public static function loadLSauth($auth=false) {
302 if (self :: loadLSclass('LSauth')) {
304 if(self :: includeFile(LS_CLASS_DIR .'class.LSauth'.$auth.'.php')) {
305 self :: includeFile(LS_CONF_DIR."LSauth/config.LSauth".$auth.".php");
314 LSerror :: addErrorCode('LSsession_05','LSauth');
320 * Chargement des addons LdapSaisie
322 * Chargement des LSaddons contenue dans la variable
323 * $GLOBALS['LSaddons']['loads']
325 * @retval boolean true si le chargement a réussi, false sinon.
327 public static function loadLSaddons() {
328 $conf=LSconfig :: get('LSaddons.loads');
329 if(!is_array($conf)) {
330 LSerror :: addErrorCode('LSsession_01',"LSaddons['loads']");
334 foreach ($conf as $addon) {
335 self :: loadLSaddon($addon);
345 public static function setLocale() {
346 if (isset($_REQUEST['lang'])) {
347 $lang = $_REQUEST['lang'];
349 elseif (isset($_SESSION['LSlang'])) {
350 $lang = $_SESSION['LSlang'];
352 elseif (isset(self :: $ldapServer['lang'])) {
353 $lang = self :: $ldapServer['lang'];
356 $lang = LSconfig :: get('lang');
359 if (isset($_REQUEST['encoding'])) {
360 $encoding = $_REQUEST['encoding'];
362 elseif (isset($_SESSION['LSencoding'])) {
363 $encoding = $_SESSION['LSencoding'];
365 elseif (isset(self :: $ldapServer['encoding'])) {
366 $encoding = self :: $ldapServer['encoding'];
369 $encoding = LSconfig :: get('encoding');
372 $_SESSION['LSlang']=$lang;
374 $_SESSION['LSencoding']=$encoding;
375 self :: $encoding=$encoding;
378 if (self :: localeExist($lang,$encoding)) {
380 $lang.='.'.$encoding;
382 setlocale(LC_ALL, $lang);
383 bindtextdomain(LS_TEXT_DOMAIN, LS_I18N_DIR);
384 textdomain(LS_TEXT_DOMAIN);
386 if (is_file(LS_I18N_DIR.'/'.$lang.'/lang.php')) {
387 include(LS_I18N_DIR.'/'.$lang.'/lang.php');
391 if ($encoding && $lang) {
392 $lang.='.'.$encoding;
394 LSdebug('La locale "'.$lang.'" n\'existe pas, utilisation de la locale par défaut.');
399 * Retourne la liste des langues disponibles
401 * @retval array Tableau/Liste des langues disponibles
403 public static function getLangList() {
404 $list=array('en_US');
405 if (self :: $encoding) {
406 $regex = '^([a-zA-Z_]*)\.'.self :: $encoding.'$';
409 $regex = '^([a-zA-Z_]*)$';
411 if ($handle = opendir(LS_I18N_DIR)) {
412 while (false !== ($file = readdir($handle))) {
413 if(is_dir(LS_I18N_DIR.'/'.$file)) {
414 if (ereg($regex,$file,$regs)) {
415 if (!in_array($regs[1],$list)) {
426 * Retourne la langue courante de la session
428 * @param[in] boolean Si true, le code langue retourné sera court
430 * @retval string La langue de la session
432 public static function getLang($short=false) {
434 return strtolower(self :: $lang[0].self :: $lang[1]);
436 return self :: $lang;
440 * Vérifie si une locale est disponible
442 * @param[in] $lang string La langue (Ex : fr_FR)
443 * @param[in] $encoding string L'encodage de caractère (Ex : UTF8)
445 * @retval boolean True si la locale est disponible, False sinon
447 public static function localeExist($lang,$encoding) {
448 if ( !$lang && !$encoding ) {
451 $locale=$lang.(($encoding)?'.'.$encoding:'');
452 if ($locale=='en_US.UTF8') {
455 return (is_dir(LS_I18N_DIR.'/'.$locale));
459 * Initialisation LdapSaisie
461 * @retval boolean True si l'initialisation à réussi, false sinon.
463 public static function initialize() {
464 if (!self :: startLSconfig()) {
468 self :: startLStemplate();
474 self :: startLSerror();
475 self :: loadLSaddons();
480 * Initialisation de la session LdapSaisie
482 * Initialisation d'une LSsession :
483 * - Authentification et activation du mécanisme de session de LdapSaisie
484 * - ou Chargement des paramètres de la session à partir de la variable
485 * $_SESSION['LSsession'].
486 * - ou Destruction de la session en cas de $_GET['LSsession_logout'].
488 * @retval boolean True si l'initialisation à réussi (utilisateur authentifié), false sinon.
490 public static function startLSsession() {
491 if (!self :: initialize()) {
495 if(isset($_SESSION['LSsession']['dn']) && !isset($_GET['LSsession_recoverPassword'])) {
497 self :: $topDn = $_SESSION['LSsession']['topDn'];
498 self :: $dn = $_SESSION['LSsession']['dn'];
499 self :: $rdn = $_SESSION['LSsession']['rdn'];
500 self :: $ldapServerId = $_SESSION['LSsession']['ldapServerId'];
501 self :: $tmp_file = $_SESSION['LSsession']['tmp_file'];
502 self :: $authParams = $_SESSION['LSsession']['authParams'];
504 if ( self :: cacheLSprofiles() && !isset($_REQUEST['LSsession_refresh']) ) {
505 self :: setLdapServer(self :: $ldapServerId);
506 self :: $LSprofiles = $_SESSION['LSsession']['LSprofiles'];
507 self :: $LSaccess = $_SESSION['LSsession']['LSaccess'];
508 if (!self :: LSldapConnect())
512 self :: setLdapServer(self :: $ldapServerId);
513 if (!self :: LSldapConnect())
515 self :: loadLSprofiles();
518 if ( self :: cacheSudDn() && (!isset($_REQUEST['LSsession_refresh'])) ) {
519 self :: $_subDnLdapServer = ((isset($_SESSION['LSsession_subDnLdapServer']))?$_SESSION['LSsession_subDnLdapServer']:NULL);
522 if (!self :: loadLSobject(self :: $ldapServer['authObjectType'])) {
526 if (isset($_GET['LSsession_logout'])) {
527 $authObj = self :: getLSauthObject();
529 $authObj -> logout();
533 if (is_array($_SESSION['LSsession']['tmp_file'])) {
534 self :: $tmp_file = $_SESSION['LSsession']['tmp_file'];
536 self :: deleteTmpFile();
537 unset($_SESSION['LSsession']);
539 self :: redirect('index.php');
543 self :: getLSuserObject();
545 if ( !self :: cacheLSprofiles() || isset($_REQUEST['LSsession_refresh']) ) {
546 self :: loadLSaccess();
549 $GLOBALS['Smarty'] -> assign('LSsession_username',self :: getLSuserObject() -> getDisplayName());
551 if (isset ($_POST['LSsession_topDn']) && $_POST['LSsession_topDn']) {
552 if (self :: validSubDnLdapServer($_POST['LSsession_topDn'])) {
553 self :: $topDn = $_POST['LSsession_topDn'];
554 $_SESSION['LSsession']['topDn'] = $_POST['LSsession_topDn'];
562 if (isset($_GET['LSsession_recoverPassword'])) {
565 // Session inexistante
566 if (isset($_POST['LSsession_ldapserver'])) {
567 self :: setLdapServer($_POST['LSsession_ldapserver']);
570 self :: setLdapServer(0);
573 // Connexion au serveur LDAP
574 if (self :: LSldapConnect()) {
577 if (isset($_POST['LSsession_topDn']) && $_POST['LSsession_topDn'] != '' ){
578 self :: $topDn = $_POST['LSsession_topDn'];
581 self :: $topDn = self :: $ldapServer['ldap_config']['basedn'];
583 $_SESSION['LSsession_topDn']=self :: $topDn;
585 if (isset($_GET['LSsession_recoverPassword'])) {
586 $recoveryPasswordInfos = self :: recoverPasswd(
587 $_REQUEST['LSsession_user'],
588 $_GET['recoveryHash']
592 $authObj=self :: getLSauthObject();
594 if ($authObj -> getPostData()) {
595 $LSuserObject = $authObj -> authenticate();
597 // Authentication successful
598 self :: $LSuserObject = $LSuserObject;
599 self :: $dn = $LSuserObject->getValue('dn');
600 self :: $rdn = $LSuserObject->getValue('rdn');
601 self :: loadLSprofiles();
602 self :: loadLSaccess();
603 $GLOBALS['Smarty'] -> assign('LSsession_username',self :: getLSuserObject() -> getDisplayName());
604 $_SESSION['LSsession']=self :: getContextInfos();
612 LSerror :: addErrorCode('LSsession_09');
615 if (self :: $ldapServerId) {
616 $GLOBALS['Smarty'] -> assign('ldapServerId',self :: $ldapServerId);
618 $GLOBALS['Smarty'] -> assign('topDn',self :: $topDn);
619 if (isset($_GET['LSsession_recoverPassword'])) {
620 self :: displayRecoverPasswordForm($recoveryPasswordInfos);
622 elseif(self :: $authParams['displayLoginForm']) {
623 self :: displayLoginForm();
626 self :: setTemplate('blank.tpl');
627 LSerror :: addErrorCode('LSsession_10');
636 * @retval LSauth object or false
638 private static function getLSauthObject() {
639 if (!self :: $LSauthObject) {
640 if (self :: loadLSauth()) {
641 if (isset(self :: $ldapServer['LSauth']['method'])) {
642 $LSauthClass = 'LSauth'.self :: $ldapServer['LSauth']['method'];
643 if (!self :: loadLSauth(self :: $ldapServer['LSauth']['method'])) {
644 LSerror :: addErrorCode('LSsession_08',self :: $ldapServer['LSauth']['method']);
645 $LSauthClass = 'LSauth';
649 $LSauthClass = 'LSauth';
652 self :: $LSauthObject = new $LSauthClass();
653 self :: $authParams = self :: $LSauthObject->params;
656 return self :: $LSauthObject;
660 * Do recover password
662 * @param[in] $username string The submited username
663 * @param[in] $recoveryHash string The submited recoveryHash
665 * @retval array The recoveryPassword infos for template
667 private static function recoverPasswd($username,$recoveryHash) {
668 $recoveryPasswordInfos=array();
669 if ( self :: loadLSobject(self :: $ldapServer['authObjectType']) ) {
670 $authobject = new self :: $ldapServer['authObjectType']();
671 if (!empty($recoveryHash)) {
672 $filter=Net_LDAP2_Filter::create(
673 self :: $ldapServer['recoverPassword']['recoveryHashAttr'],
677 $result = $authobject -> listObjects($filter,self :: $topDn);
679 elseif (!empty($username)) {
680 $result = $authobject -> searchObject(
683 self :: $ldapServer['authObjectFilter']
687 return $recoveryPasswordInfos;
690 $nbresult=count($result);
693 LSdebug('hash/username incorrect');
694 LSerror :: addErrorCode('LSsession_06');
696 elseif ($nbresult>1) {
697 LSerror :: addErrorCode('LSsession_07');
700 $rdn = $result[0] -> getValue('rdn');
702 LSdebug('Recover : Id trouvé : '.$username);
703 if (self :: $ldapServer['recoverPassword']) {
704 if (self :: loadLSaddon('mail')) {
705 LSdebug('Récupération active');
707 $emailAddress = $user -> getValue(self :: $ldapServer['recoverPassword']['mailAttr']);
708 $emailAddress = $emailAddress[0];
710 if (checkEmail($emailAddress)) {
711 LSdebug('Email : '.$emailAddress);
712 self :: $dn = $user -> getDn();
714 // 1ère étape : envoie du recoveryHash
715 if (empty($recoveryHash)) {
716 $hash=self :: recoverPasswdFirstStep($user);
718 if (self :: recoverPasswdSendMail($emailAddress,1,$hash)) {
719 // Mail a bien été envoyé
720 $recoveryPasswordInfos['recoveryHashMail']=$emailAddress;
724 // 2nd étape : génération du mot de passe + envoie par mail
726 $pwd=self :: recoverPasswdSecondStep($user);
728 if (self :: recoverPasswdSendMail($emailAddress,2,$pwd)){
729 // Mail a bien été envoyé
730 $recoveryPasswordInfos['newPasswordMail']=$emailAddress;
736 LSerror :: addErrorCode('LSsession_19');
741 LSerror :: addErrorCode('LSsession_18');
745 return $recoveryPasswordInfos;
749 * Send recover password mail
751 * @param[in] $mail string The user's mail
752 * @param[in] $step integer The step
753 * @param[in] $info string The info for formatted message
755 * @retval boolean True on success or False
757 private static function recoverPasswdSendMail($mail,$step,$info) {
760 if (self :: $ldapServer['recoverPassword']['recoveryEmailSender']) {
761 $sendParams['From']=self :: $ldapServer['recoverPassword']['recoveryEmailSender'];
765 if ($_SERVER['HTTPS']=='on') {
766 $recovery_url='https://';
769 $recovery_url='http://';
771 $recovery_url .= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'&recoveryHash='.$info;
773 $subject = self :: $ldapServer['recoverPassword']['recoveryHashMail']['subject'];
775 self :: $ldapServer['recoverPassword']['recoveryHashMail']['msg'],
780 $subject = self :: $ldapServer['recoverPassword']['newPasswordMail']['subject'];
782 self :: $ldapServer['recoverPassword']['newPasswordMail']['msg'],
787 if (!sendMail($mail,$subject,$msg,$sendParams)) {
788 LSdebug("Problème durant l'envoie du mail");
789 LSerror :: addErrorCode('LSsession_20',4);
797 * Do first step of recovering password
799 * @param[in] $user LSldapObject The LSldapObject of the user
801 * @retval string|False The recory hash on success or False
803 private static function recoverPasswdFirstStep($user) {
805 $rdn=$user -> getValue('rdn');
807 $recovery_hash = md5($rdn . strval(time()) . strval(rand()));
809 $lostPasswdForm = $user -> getForm('lostPassword');
810 $lostPasswdForm -> setPostData(
812 self :: $ldapServer['recoverPassword']['recoveryHashAttr'] => $recovery_hash
817 if($lostPasswdForm -> validate()) {
818 if ($user -> updateData('lostPassword')) {
819 // recoveryHash de l'utilisateur mis à jour
820 return $recovery_hash;
823 // Erreur durant la mise à jour de l'objet
824 LSdebug("Erreur durant la mise à jour de l'objet");
825 LSerror :: addErrorCode('LSsession_20',6);
829 // Erreur durant la validation du formulaire de modification de perte de password
830 LSdebug("Erreur durant la validation du formulaire de modification de perte de password");
831 LSerror :: addErrorCode('LSsession_20',5);
837 * Do second step of recovering password
839 * @param[in] $user LSldapObject The LSldapObject of the user
841 * @retval string|False The new password on success or False
843 private static function recoverPasswdSecondStep($user) {
844 $attr=$user -> attrs[self :: $ldapServer['authObjectTypeAttrPwd']];
845 if ($attr instanceof LSattribute) {
846 $mdp = generatePassword(
847 $attr -> config['html_options']['chars'],
848 $attr -> config['html_options']['lenght']
850 LSdebug('Nvx mpd : '.$mdp);
851 $lostPasswdForm = $user -> getForm('lostPassword');
852 $lostPasswdForm -> setPostData(
854 self :: $ldapServer['recoverPassword']['recoveryHashAttr'] => array(''),
855 self :: $ldapServer['authObjectTypeAttrPwd'] => array($mdp)
859 if($lostPasswdForm -> validate()) {
860 if ($user -> updateData('lostPassword')) {
864 // Erreur durant la mise à jour de l'objet
865 LSdebug("Erreur durant la mise à jour de l'objet");
866 LSerror :: addErrorCode('LSsession_20',3);
870 // Erreur durant la validation du formulaire de modification de perte de password
871 LSdebug("Erreur durant la validation du formulaire de modification de perte de password");
872 LSerror :: addErrorCode('LSsession_20',2);
876 // l'attribut password n'existe pas
877 LSdebug("L'attribut password n'existe pas");
878 LSerror :: addErrorCode('LSsession_20',1);
884 * Retourne les informations du contexte
886 * @author Benjamin Renard <brenard@easter-eggs.com
888 * @retval array Tableau associatif des informations du contexte
890 private static function getContextInfos() {
892 'tmp_file' => self :: $tmp_file,
893 'topDn' => self :: $topDn,
895 'rdn' => self :: $rdn,
896 'ldapServerId' => self :: $ldapServerId,
897 'ldapServer' => self :: $ldapServer,
898 'LSprofiles' => self :: $LSprofiles,
899 'LSaccess' => self :: $LSaccess,
900 'authParams' => self :: $authParams
905 * Retourne l'objet de l'utilisateur connecté
907 * @author Benjamin Renard <brenard@easter-eggs.com
909 * @retval mixed L'objet de l'utilisateur connecté ou false si il n'a pas put
912 public static function getLSuserObject($dn=null) {
916 if (!self :: $LSuserObject) {
917 if (self :: loadLSobject(self :: $ldapServer['authObjectType'])) {
918 self :: $LSuserObject = new self :: $ldapServer['authObjectType']();
919 self :: $LSuserObject -> loadData(self :: $dn);
925 return self :: $LSuserObject;
929 * Retourne le DN de l'utilisateur connecté
931 * @author Benjamin Renard <brenard@easter-eggs.com
933 * @retval string Le DN de l'utilisateur connecté
935 public static function getLSuserObjectDn() {
940 * Modifie l'utilisateur connecté à la volé
942 * @param[in] $object Mixed L'objet Ldap du nouvel utilisateur
943 * le type doit correspondre à
944 * self :: $ldapServer['authObjectType']
946 * @retval boolean True en cas de succès, false sinon
948 public static function changeAuthUser($object) {
949 if ($object instanceof self :: $ldapServer['authObjectType']) {
950 self :: $dn = $object -> getDn();
951 $rdn = $object -> getValue('rdn');
956 self :: $LSuserObject = $object;
958 if(self :: loadLSprofiles()) {
959 self :: loadLSaccess();
960 $_SESSION['LSsession']=self :: getContextInfos();
968 * Définition du serveur Ldap de la session
970 * Définition du serveur Ldap de la session à partir de son ID dans
971 * le tableau LSconfig :: get('ldap_servers').
973 * @param[in] integer Index du serveur Ldap
975 * @retval boolean True sinon false.
977 public static function setLdapServer($id) {
978 $conf = LSconfig :: get("ldap_servers.$id");
979 if ( is_array($conf) ) {
980 self :: $ldapServerId = $id;
981 self :: $ldapServer = $conf;
991 * Connexion au serveur Ldap
993 * @retval boolean True sinon false.
995 public static function LSldapConnect() {
996 if (self :: $ldapServer) {
997 self :: includeFile(LSconfig :: get('NetLDAP2'));
998 if (!self :: loadLSclass('LSldap')) {
1001 LSldap :: connect(self :: $ldapServer['ldap_config']);
1002 if (LSldap :: isConnected()) {
1010 LSerror :: addErrorCode('LSsession_03');
1016 * Use this function to know if subDn is enabled for the curent LdapServer
1020 public static function subDnIsEnabled() {
1021 if (!isset(self :: $ldapServer['subDn'])) {
1024 if ( !is_array(self :: $ldapServer['subDn']) ) {
1031 * Retourne les sous-dns du serveur Ldap courant
1033 * @retval mixed Tableau des subDn, false si une erreur est survenue.
1035 public static function getSubDnLdapServer($login=false) {
1036 $login=(bool)$login;
1037 if (self :: cacheSudDn() && isset(self :: $_subDnLdapServer[self :: $ldapServerId][$login])) {
1038 return self :: $_subDnLdapServer[self :: $ldapServerId];
1040 if (!self::subDnIsEnabled()) {
1044 foreach(self :: $ldapServer['subDn'] as $subDn_name => $subDn_config) {
1045 if ($login && $subDn_config['nologin']) continue;
1046 if ($subDn_name == 'LSobject') {
1047 if (is_array($subDn_config)) {
1048 foreach($subDn_config as $LSobject_name => $LSoject_config) {
1049 if ($LSoject_config['basedn']) {
1050 $basedn = $LSoject_config['basedn'];
1053 $basedn = self::getRootDn();
1055 if ($LSoject_config['displayName']) {
1056 $displayName = $LSoject_config['displayName'];
1059 $displayName = NULL;
1061 if( self :: loadLSobject($LSobject_name) ) {
1062 if ($subdnobject = new $LSobject_name()) {
1063 $tbl_return = $subdnobject -> getSelectArray(NULL,$basedn,$displayName);
1064 if (is_array($tbl_return)) {
1065 $return=array_merge($return,$tbl_return);
1068 LSerror :: addErrorCode('LSsession_17',3);
1072 LSerror :: addErrorCode('LSsession_17',2);
1078 LSerror :: addErrorCode('LSsession_17',1);
1082 if ((isCompatibleDNs($subDn_config['dn'],self :: $ldapServer['ldap_config']['basedn']))&&($subDn_config['dn']!="")) {
1083 $return[$subDn_config['dn']] = __($subDn_name);
1087 if (self :: cacheSudDn()) {
1088 self :: $_subDnLdapServer[self :: $ldapServerId][$login]=$return;
1089 $_SESSION['LSsession_subDnLdapServer'] = self :: $_subDnLdapServer;
1095 * Retourne la liste de subDn du serveur Ldap utilise
1096 * trié par la profondeur dans l'arboressence (ordre décroissant)
1098 * @return array() Tableau des subDn trié
1100 public static function getSortSubDnLdapServer($login=false) {
1101 $subDnLdapServer = self :: getSubDnLdapServer($login);
1102 if (!$subDnLdapServer) {
1105 uksort($subDnLdapServer,"compareDn");
1106 return $subDnLdapServer;
1110 * Retourne les options d'une liste déroulante pour le choix du topDn
1111 * de connexion au serveur Ldap
1113 * Liste les subdn (self :: $ldapServer['subDn'])
1115 * @retval string Les options (<option>) pour la sélection du topDn.
1117 public static function getSubDnLdapServerOptions($selected=NULL,$login=false) {
1118 $list = self :: getSubDnLdapServer($login);
1122 foreach($list as $dn => $txt) {
1123 if ($selected && ($selected==$dn)) {
1124 $selected_txt = ' selected';
1129 $display.="<option value=\"".$dn."\"$selected_txt>".$txt."</option>\n";
1137 * Vérifie qu'un subDn est déclaré
1139 * @param[in] string Un subDn
1141 * @retval boolean True si le subDn existe, False sinon
1143 public static function validSubDnLdapServer($subDn) {
1144 $listTopDn = self :: getSubDnLdapServer();
1145 if(is_array($listTopDn)) {
1146 foreach($listTopDn as $dn => $txt) {
1156 * Test un couple LSobject/pwd
1158 * Test un bind sur le serveur avec le dn de l'objet et le mot de passe fourni.
1160 * @param[in] LSobject L'object "user" pour l'authentification
1161 * @param[in] string Le mot de passe à tester
1163 * @retval boolean True si l'authentification à réussi, false sinon.
1165 public static function checkUserPwd($object,$pwd) {
1166 return LSldap :: checkBind($object -> getValue('dn'),$pwd);
1170 * Affiche le formulaire de login
1172 * Défini les informations pour le template Smarty du formulaire de login.
1176 public static function displayLoginForm() {
1177 $GLOBALS['Smarty'] -> assign('pagetitle',_('Connection'));
1178 if (isset($_GET['LSsession_logout'])) {
1179 $GLOBALS['Smarty'] -> assign('loginform_action','index.php');
1182 $GLOBALS['Smarty'] -> assign('loginform_action',$_SERVER['REQUEST_URI']);
1184 if (count(LSconfig :: get('ldap_servers'))==1) {
1185 $GLOBALS['Smarty'] -> assign('loginform_ldapserver_style','style="display: none"');
1187 $GLOBALS['Smarty'] -> assign('loginform_label_ldapserver',_('LDAP server'));
1188 $ldapservers_name=array();
1189 $ldapservers_index=array();
1190 foreach(LSconfig :: get('ldap_servers') as $id => $infos) {
1191 $ldapservers_index[]=$id;
1192 $ldapservers_name[]=__($infos['name']);
1194 $GLOBALS['Smarty'] -> assign('loginform_ldapservers_name',$ldapservers_name);
1195 $GLOBALS['Smarty'] -> assign('loginform_ldapservers_index',$ldapservers_index);
1197 $GLOBALS['Smarty'] -> assign('loginform_label_level',_('Level'));
1198 $GLOBALS['Smarty'] -> assign('loginform_label_user',_('Identifier'));
1199 $GLOBALS['Smarty'] -> assign('loginform_label_pwd',_('Password'));
1200 $GLOBALS['Smarty'] -> assign('loginform_label_submit',_('Connect'));
1201 $GLOBALS['Smarty'] -> assign('loginform_label_recoverPassword',_('Forgot your password ?'));
1203 self :: setTemplate('login.tpl');
1204 self :: addJSscript('LSsession_login.js');
1208 * Affiche le formulaire de récupération de mot de passe
1210 * Défini les informations pour le template Smarty du formulaire de
1211 * récupération de mot de passe
1213 * @param[in] $infos array() Information sur le status du processus de
1214 * recouvrement de mot de passe
1218 public static function displayRecoverPasswordForm($recoveryPasswordInfos) {
1219 $GLOBALS['Smarty'] -> assign('pagetitle',_('Recovery of your credentials'));
1220 $GLOBALS['Smarty'] -> assign('recoverpasswordform_action','index.php?LSsession_recoverPassword');
1222 if (count(LSconfig :: get('ldap_servers'))==1) {
1223 $GLOBALS['Smarty'] -> assign('recoverpasswordform_ldapserver_style','style="display: none"');
1226 $GLOBALS['Smarty'] -> assign('recoverpasswordform_label_ldapserver',_('LDAP server'));
1227 $ldapservers_name=array();
1228 $ldapservers_index=array();
1229 foreach(LSconfig :: get('ldap_servers') as $id => $infos) {
1230 $ldapservers_index[]=$id;
1231 $ldapservers_name[]=$infos['name'];
1233 $GLOBALS['Smarty'] -> assign('recoverpasswordform_ldapservers_name',$ldapservers_name);
1234 $GLOBALS['Smarty'] -> assign('recoverpasswordform_ldapservers_index',$ldapservers_index);
1236 $GLOBALS['Smarty'] -> assign('recoverpasswordform_label_user',_('Identifier'));
1237 $GLOBALS['Smarty'] -> assign('recoverpasswordform_label_submit',_('Validate'));
1238 $GLOBALS['Smarty'] -> assign('recoverpasswordform_label_back',_('Back'));
1240 $recoverpassword_msg = _('Please fill the identifier field to proceed recovery procedure');
1242 if (isset($recoveryPasswordInfos['recoveryHashMail'])) {
1243 $recoverpassword_msg = getFData(
1244 _("An email has been sent to %{mail}. " .
1245 "Please follow the instructions on it."),
1246 $recoveryPasswordInfos['recoveryHashMail']
1250 if (isset($recoveryPasswordInfos['newPasswordMail'])) {
1251 $recoverpassword_msg = getFData(
1252 _("Your new password has been sent to %{mail}. "),
1253 $recoveryPasswordInfos['newPasswordMail']
1257 $GLOBALS['Smarty'] -> assign('recoverpassword_msg',$recoverpassword_msg);
1259 self :: setTemplate('recoverpassword.tpl');
1260 self :: addJSscript('LSsession_recoverPassword.js');
1264 * Défini le template Smarty à utiliser
1266 * Remarque : les fichiers de templates doivent se trouver dans le dossier
1269 * @param[in] string Le nom du fichier de template
1273 public static function setTemplate($template) {
1274 self :: $template = $template;
1278 * Ajoute un script JS au chargement de la page
1280 * Remarque : les scripts doivents être dans le dossier LS_JS_DIR.
1282 * @param[in] $script Le nom du fichier de script à charger.
1286 public static function addJSscript($file,$path=NULL) {
1291 self :: $JSscripts[$path.$file]=$script;
1295 * Ajouter un paramètre de configuration Javascript
1297 * @param[in] $name string Nom de la variable de configuration
1298 * @param[in] $val mixed Valeur de la variable de configuration
1302 public static function addJSconfigParam($name,$val) {
1303 self :: $_JSconfigParams[$name]=$val;
1307 * Ajoute une feuille de style au chargement de la page
1309 * Remarque : les scripts doivents être dans le dossier LS_CSS_DIR.
1311 * @param[in] $script Le nom du fichier css à charger.
1315 public static function addCssFile($file,$path=NULL) {
1320 self :: $CssFiles[$path.$file]=$cssFile;
1324 * Affiche le template Smarty
1326 * Charge les dépendances et affiche le template Smarty
1330 public static function displayTemplate() {
1333 foreach ($GLOBALS['defaultJSscipts'] as $script) {
1334 $JSscript_txt.="<script src='".LS_JS_DIR.$script."' type='text/javascript'></script>\n";
1337 foreach (self :: $JSscripts as $script) {
1338 if (!$script['path']) {
1339 $script['path']=LS_JS_DIR;
1342 $script['path'].='/';
1344 $JSscript_txt.="<script src='".$script['path'].$script['file']."' type='text/javascript'></script>\n";
1347 $KAconf = LSconfig :: get('keepLSsessionActive');
1350 (!isset(self :: $ldapServer['keepLSsessionActive']))
1352 (!($KAconf === false))
1355 (self :: $ldapServer['keepLSsessionActive'])
1357 self :: addJSconfigParam('keepLSsessionActive',ini_get('session.gc_maxlifetime'));
1360 $GLOBALS['Smarty'] -> assign('LSjsConfig',json_encode(self :: $_JSconfigParams));
1363 $JSscript_txt.="<script type='text/javascript'>LSdebug_active = 1;</script>\n";
1366 $JSscript_txt.="<script type='text/javascript'>LSdebug_active = 0;</script>\n";
1369 $GLOBALS['Smarty'] -> assign('LSsession_js',$JSscript_txt);
1372 self :: addCssFile("LSdefault.css");
1374 foreach (self :: $CssFiles as $file) {
1375 if (!$file['path']) {
1376 $file['path']=LS_CSS_DIR.'/';
1378 $Css_txt.="<link rel='stylesheet' type='text/css' href='".$file['path'].$file['file']."' />\n";
1380 $GLOBALS['Smarty'] -> assign('LSsession_css',$Css_txt);
1382 if (isset(self :: $LSaccess[self :: $topDn])) {
1383 $GLOBALS['Smarty'] -> assign('LSaccess',self :: $LSaccess[self :: $topDn]);
1387 $listTopDn = self :: getSubDnLdapServer();
1388 if (is_array($listTopDn)) {
1390 $GLOBALS['Smarty'] -> assign('label_level',self :: getSubDnLabel());
1391 $GLOBALS['Smarty'] -> assign('_refresh',_('Refresh'));
1392 $LSsession_topDn_index = array();
1393 $LSsession_topDn_name = array();
1394 foreach($listTopDn as $index => $name) {
1395 $LSsession_topDn_index[] = $index;
1396 $LSsession_topDn_name[] = $name;
1398 $GLOBALS['Smarty'] -> assign('LSsession_subDn_indexes',$LSsession_topDn_index);
1399 $GLOBALS['Smarty'] -> assign('LSsession_subDn_names',$LSsession_topDn_name);
1400 $GLOBALS['Smarty'] -> assign('LSsession_subDn',self :: $topDn);
1401 $GLOBALS['Smarty'] -> assign('LSsession_subDnName',self :: getSubDnName());
1404 $GLOBALS['Smarty'] -> assign('LSlanguages',self :: getLangList());
1405 $GLOBALS['Smarty'] -> assign('LSlang',self :: $lang);
1406 $GLOBALS['Smarty'] -> assign('LSencoding',self :: $encoding);
1407 $GLOBALS['Smarty'] -> assign('lang_label',_('Language'));
1409 $GLOBALS['Smarty'] -> assign('displayLogoutBtn',self :: $authParams['displayLogoutBtn']);
1412 if((!empty($_SESSION['LSsession_infos']))&&(is_array($_SESSION['LSsession_infos']))) {
1413 $txt_infos="<ul>\n";
1414 foreach($_SESSION['LSsession_infos'] as $info) {
1415 $txt_infos.="<li>$info</li>\n";
1417 $txt_infos.="</ul>\n";
1418 $GLOBALS['Smarty'] -> assign('LSinfos',$txt_infos);
1419 $_SESSION['LSsession_infos']=array();
1422 if (self :: $ajaxDisplay) {
1423 $GLOBALS['Smarty'] -> assign('LSerror_txt',LSerror :: getErrors());
1424 $GLOBALS['Smarty'] -> assign('LSdebug_txt',LSdebug_print(true));
1427 LSerror :: display();
1430 if (!self :: $template)
1431 self :: setTemplate('empty.tpl');
1433 $GLOBALS['Smarty'] -> assign('connected_as',_("Connected as"));
1435 $GLOBALS['Smarty'] -> display(self :: $template);
1439 * Défini que l'affichage se fera ou non via un retour Ajax
1441 * @param[in] $val boolean True pour que l'affichage se fasse par un retour
1445 public static function setAjaxDisplay($val=true) {
1446 self :: $ajaxDisplay = (boolean)$val;
1450 * Affiche un retour Ajax
1454 public static function displayAjaxReturn($data=array()) {
1455 if (isset($data['LSredirect']) && (!LSdebugDefined()) ) {
1456 echo json_encode($data);
1460 $data['LSjsConfig'] = self :: $_JSconfigParams;
1463 if((!empty($_SESSION['LSsession_infos']))&&(is_array($_SESSION['LSsession_infos']))) {
1464 $txt_infos="<ul>\n";
1465 foreach($_SESSION['LSsession_infos'] as $info) {
1466 $txt_infos.="<li>$info</li>\n";
1468 $txt_infos.="</ul>\n";
1469 $data['LSinfos'] = $txt_infos;
1470 $_SESSION['LSsession_infos']=array();
1473 if (LSerror :: errorsDefined()) {
1474 $data['LSerror'] = LSerror :: getErrors();
1477 if (isset($_REQUEST['imgload'])) {
1478 $data['imgload'] = $_REQUEST['imgload'];
1481 if (LSdebugDefined()) {
1482 $data['LSdebug'] = LSdebug_print(true,false);
1485 echo json_encode($data);
1489 * Retournne un template Smarty compilé
1491 * @param[in] string $template Le template à retourner
1492 * @param[in] array $variables Variables Smarty à assigner avant l'affichage
1494 * @retval string Le HTML compilé du template
1496 public static function fetchTemplate($template,$variables=array()) {
1497 foreach($variables as $name => $val) {
1498 $GLOBALS['Smarty'] -> assign($name,$val);
1500 return $GLOBALS['Smarty'] -> fetch($template);
1504 * Charge les droits LS de l'utilisateur
1506 * @retval boolean True si le chargement à réussi, false sinon.
1508 private static function loadLSprofiles() {
1509 if (is_array(self :: $ldapServer['LSprofiles'])) {
1510 foreach (self :: $ldapServer['LSprofiles'] as $profile => $profileInfos) {
1511 if (is_array($profileInfos)) {
1512 foreach ($profileInfos as $topDn => $rightsInfos) {
1514 * If $topDn == 'LSobject', we search for each LSobject type to find
1515 * all items on witch the user will have powers.
1517 if ($topDn == 'LSobjects') {
1518 if (is_array($rightsInfos)) {
1519 foreach ($rightsInfos as $LSobject => $listInfos) {
1520 if (self :: loadLSclass('LSsearch')) {
1521 if (isset($listInfos['filter'])) {
1522 $filter = self :: getLSuserObject() -> getFData($listInfos['filter']);
1525 $filter = '('.$listInfos['attr'].'='.self :: getLSuserObject() -> getFData($listInfos['attr_value']).')';
1529 'basedn' => (isset($listInfos['basedn'])?$listInfos['basedn']:null),
1533 if (isset($listInfos['params']) && is_array($listInfos['params'])) {
1534 $params = array_merge($listInfos['params'],$params);
1537 $LSsearch = new LSsearch($LSobject,'LSsession :: loadLSprofiles',$params,true);
1538 $LSsearch -> run(false);
1540 $LSprofiles[$profile] = $LSsearch -> listObjectsDn();
1545 LSdebug('LSobjects => [] doit etre un tableau');
1549 if (is_array($rightsInfos)) {
1550 foreach($rightsInfos as $dn => $conf) {
1551 if ((isset($conf['attr'])) && (isset($conf['LSobject']))) {
1552 if( self :: loadLSobject($conf['LSobject']) ) {
1553 if ($object = new $conf['LSobject']()) {
1554 if ($object -> loadData($dn)) {
1555 $listDns=$object -> getValue($conf['attr']);
1556 $valKey = (isset($conf['attr_value']))?$conf['attr_value']:'%{dn}';
1557 $val = self :: getLSuserObject() -> getFData($valKey);
1558 if (is_array($listDns)) {
1559 if (in_array($val,$listDns)) {
1560 self :: $LSprofiles[$profile][] = $topDn;
1565 LSdebug('Impossible de chargé le dn : '.$dn);
1569 LSdebug('Impossible de créer l\'objet de type : '.$conf['LSobject']);
1574 if (self :: $dn == $dn) {
1575 self :: $LSprofiles[$profile][] = $topDn;
1581 if ( self :: $dn == $rightsInfos ) {
1582 self :: $LSprofiles[$profile][] = $topDn;
1585 } // fin else ($topDn == 'LSobjects')
1586 } // fin foreach($profileInfos)
1587 } // fin is_array($profileInfos)
1588 } // fin foreach LSprofiles
1589 LSdebug(self :: $LSprofiles);
1598 * Charge les droits d'accès de l'utilisateur pour construire le menu de l'interface
1602 private static function loadLSaccess() {
1604 if (isset(self :: $ldapServer['subDn']) && is_array(self :: $ldapServer['subDn'])) {
1605 foreach(self :: $ldapServer['subDn'] as $name => $config) {
1606 if ($name=='LSobject') {
1607 if (is_array($config)) {
1609 // Définition des subDns
1610 foreach($config as $objectType => $objectConf) {
1611 if (self :: loadLSobject($objectType)) {
1612 if ($subdnobject = new $objectType()) {
1613 $tbl = $subdnobject -> getSelectArray(NULL,self::getRootDn(),NULL,NULL,false);
1614 if (is_array($tbl)) {
1615 // Définition des accès
1617 if (is_array($objectConf['LSobjects'])) {
1618 foreach($objectConf['LSobjects'] as $type) {
1619 if (self :: loadLSobject($type)) {
1620 if (self :: canAccess($type)) {
1621 $access[$type] = LSconfig :: get('LSobjects.'.$type.'.label');
1626 foreach($tbl as $dn => $dn_name) {
1627 $LSaccess[$dn]=$access;
1636 if ((isCompatibleDNs(self :: $ldapServer['ldap_config']['basedn'],$config['dn']))&&($config['dn']!='')) {
1638 if (is_array($config['LSobjects'])) {
1639 foreach($config['LSobjects'] as $objectType) {
1640 if (self :: loadLSobject($objectType)) {
1641 if (self :: canAccess($objectType)) {
1642 $access[$objectType] = LSconfig :: get('LSobjects.'.$objectType.'.label');
1647 $LSaccess[$config['dn']]=$access;
1653 if(is_array(self :: $ldapServer['LSaccess'])) {
1655 foreach(self :: $ldapServer['LSaccess'] as $objectType) {
1656 if (self :: loadLSobject($objectType)) {
1657 if (self :: canAccess($objectType)) {
1658 $access[$objectType] = LSconfig :: get('LSobjects.'.$objectType.'.label');
1662 $LSaccess[self :: $topDn] = $access;
1665 foreach($LSaccess as $dn => $access) {
1666 $LSaccess[$dn] = array_merge(
1668 'SELF' => 'My account'
1674 self :: $LSaccess = $LSaccess;
1675 $_SESSION['LSsession']['LSaccess'] = $LSaccess;
1679 * Dit si l'utilisateur est du profil pour le DN spécifié
1681 * @param[in] string $profile de l'objet
1682 * @param[in] string $dn DN de l'objet
1684 * @retval boolean True si l'utilisateur est du profil sur l'objet, false sinon.
1686 public static function isLSprofile($dn,$profile) {
1687 if (is_array(self :: $LSprofiles[$profile])) {
1688 foreach(self :: $LSprofiles[$profile] as $topDn) {
1692 else if ( isCompatibleDNs($dn,$topDn) ) {
1701 * Retourne qui est l'utilisateur par rapport à l'object
1703 * @param[in] string Le DN de l'objet
1705 * @retval string 'admin'/'self'/'user' pour Admin , l'utilisateur lui même ou un simple utilisateur
1707 public static function whoami($dn) {
1708 $retval = array('user');
1710 foreach(self :: $LSprofiles as $profile => $infos) {
1711 if(self :: isLSprofile($dn,$profile)) {
1716 if (self :: $dn == $dn) {
1724 * Retourne le droit de l'utilisateur à accèder à un objet
1726 * @param[in] string $LSobject Le type de l'objet
1727 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1728 * @param[in] string $right Le type de droit d'accès à tester ('r'/'w')
1729 * @param[in] string $attr Le nom de l'attribut auquel on test l'accès
1731 * @retval boolean True si l'utilisateur a accès, false sinon
1733 public static function canAccess($LSobject,$dn=NULL,$right=NULL,$attr=NULL) {
1734 if (!self :: loadLSobject($LSobject)) {
1738 $whoami = self :: whoami($dn);
1739 if ($dn==self :: getLSuserObject() -> getValue('dn')) {
1740 if (!self :: in_menu('SELF')) {
1745 $obj = new $LSobject();
1747 if (!self :: in_menu($LSobject,$obj -> subDnValue)) {
1753 $objectdn=LSconfig :: get('LSobjects.'.$LSobject.'.container_dn').','.self :: $topDn;
1754 $whoami = self :: whoami($objectdn);
1757 // Pour un attribut particulier
1760 $attr=LSconfig :: get('LSobjects.'.$LSobject.'.rdn');
1762 if (!is_array(LSconfig :: get('LSobjects.'.$LSobject.'.attrs.'.$attr))) {
1767 foreach($whoami as $who) {
1768 $nr = LSconfig :: get('LSobjects.'.$LSobject.'.attrs.'.$attr.'.rights.'.$who);
1772 else if($nr == 'r') {
1779 if (($right=='r')||($right=='w')) {
1786 if ( ($r=='r') || ($r=='w') ) {
1793 // Pour un attribut quelconque
1794 $attrs_conf=LSconfig :: get('LSobjects.'.$LSobject.'.attrs');
1795 if (is_array($attrs_conf)) {
1796 if (($right=='r')||($right=='w')) {
1797 foreach($whoami as $who) {
1798 foreach ($attrs_conf as $attr_name => $attr_config) {
1799 if (isset($attr_config['rights'][$who]) && $attr_config['rights'][$who]==$right) {
1806 foreach($whoami as $who) {
1807 foreach ($attrs_conf as $attr_name => $attr_config) {
1808 if ( (isset($attr_config['rights'][$who])) && ( ($attr_config['rights'][$who]=='r') || ($attr_config['rights'][$who]=='w') ) ) {
1819 * Retourne le droit de l'utilisateur à editer à un objet
1821 * @param[in] string $LSobject Le type de l'objet
1822 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1823 * @param[in] string $attr Le nom de l'attribut auquel on test l'accès
1825 * @retval boolean True si l'utilisateur a accès, false sinon
1827 public static function canEdit($LSobject,$dn=NULL,$attr=NULL) {
1828 return self :: canAccess($LSobject,$dn,'w',$attr);
1832 * Retourne le droit de l'utilisateur à supprimer un objet
1834 * @param[in] string $LSobject Le type de l'objet
1835 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1837 * @retval boolean True si l'utilisateur a accès, false sinon
1839 public static function canRemove($LSobject,$dn) {
1840 return self :: canAccess($LSobject,$dn,'w','rdn');
1844 * Retourne le droit de l'utilisateur à créer un objet
1846 * @param[in] string $LSobject Le type de l'objet
1848 * @retval boolean True si l'utilisateur a accès, false sinon
1850 public static function canCreate($LSobject) {
1851 if (!self :: loadLSobject($LSobject)) {
1854 if (LSconfig :: get("LSobjects.$LSobject.disable_creation")) {
1857 return self :: canAccess($LSobject,NULL,'w','rdn');
1861 * Retourne le droit de l'utilisateur à gérer la relation d'objet
1863 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1864 * @param[in] string $LSobject Le type de l'objet
1865 * @param[in] string $relationName Le nom de la relation avec l'objet
1866 * @param[in] string $right Le type de droit a vérifier ('r' ou 'w')
1868 * @retval boolean True si l'utilisateur a accès, false sinon
1870 public static function relationCanAccess($dn,$LSobject,$relationName,$right=NULL) {
1871 $relConf=LSconfig :: get('LSobjects.'.$LSobject.'.LSrelation.'.$relationName);
1872 if (!is_array($relConf))
1874 $whoami = self :: whoami($dn);
1876 if (($right=='w') || ($right=='r')) {
1878 foreach($whoami as $who) {
1879 $nr = ((isset($relConf['rights'][$who]))?$relConf['rights'][$who]:'');
1883 else if($nr == 'r') {
1895 foreach($whoami as $who) {
1896 if ((isset($relConf['rights'][$who])) && ( ($relConf['rights'][$who] == 'w') || ($relConf['rights'][$who] == 'r') ) ) {
1905 * Retourne le droit de l'utilisateur à modifier la relation d'objet
1907 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1908 * @param[in] string $LSobject Le type de l'objet
1909 * @param[in] string $relationName Le nom de la relation avec l'objet
1911 * @retval boolean True si l'utilisateur a accès, false sinon
1913 public static function relationCanEdit($dn,$LSobject,$relationName) {
1914 return self :: relationCanAccess($dn,$LSobject,$relationName,'w');
1918 * Ajoute un fichier temporaire
1920 * @author Benjamin Renard <brenard@easter-eggs.com>
1924 public static function addTmpFile($value,$filePath) {
1925 $hash = mhash(MHASH_MD5,$value);
1926 self :: $tmp_file[$filePath] = $hash;
1927 $_SESSION['LSsession']['tmp_file'][$filePath] = $hash;
1931 * Retourne le chemin du fichier temporaire si l'existe
1933 * @author Benjamin Renard <brenard@easter-eggs.com>
1935 * @param[in] $value La valeur du fichier
1939 public static function tmpFileExist($value) {
1940 $hash = mhash(MHASH_MD5,$value);
1941 foreach(self :: $tmp_file as $filePath => $contentHash) {
1942 if ($hash == $contentHash) {
1950 * Retourne le chemin du fichier temporaire
1952 * Retourne le chemin du fichier temporaire qu'il créera à partir de la valeur
1953 * s'il n'existe pas déjà .
1955 * @author Benjamin Renard <brenard@easter-eggs.com>
1957 * @param[in] $value La valeur du fichier
1961 public static function getTmpFile($value) {
1962 $exist = self :: tmpFileExist($value);
1964 $img_path = LS_TMP_DIR .rand().'.tmp';
1965 $fp = fopen($img_path, "w");
1966 fwrite($fp, $value);
1968 self :: addTmpFile($value,$img_path);
1977 * Supprime les fichiers temporaires
1979 * @author Benjamin Renard <brenard@easter-eggs.com>
1983 public static function deleteTmpFile($filePath=NULL) {
1986 unset(self :: $tmp_file[$filePath]);
1987 unset($_SESSION['LSsession']['tmp_file'][$filePath]);
1990 foreach(self :: $tmp_file as $file => $content) {
1993 self :: $tmp_file = array();
1994 $_SESSION['LSsession']['tmp_file'] = array();
1999 * Retourne true si le cache des droits est activé
2001 * @author Benjamin Renard <brenard@easter-eggs.com>
2003 * @retval boolean True si le cache des droits est activé, false sinon.
2005 public static function cacheLSprofiles() {
2006 return ( (LSconfig :: get('cacheLSprofiles')) || (self :: $ldapServer['cacheLSprofiles']) );
2010 * Retourne true si le cache des subDn est activé
2012 * @author Benjamin Renard <brenard@easter-eggs.com>
2014 * @retval boolean True si le cache des subDn est activé, false sinon.
2016 public static function cacheSudDn() {
2017 return ( (LSconfig :: get('cacheSubDn')) || (self :: $ldapServer['cacheSubDn']));
2021 * Retourne true si le cache des recherches est activé
2023 * @author Benjamin Renard <brenard@easter-eggs.com>
2025 * @retval boolean True si le cache des recherches est activé, false sinon.
2027 public static function cacheSearch() {
2028 return ( (LSconfig :: get('cacheSearch')) || (self :: $ldapServer['cacheSearch']));
2032 * Retourne le label des niveaux pour le serveur ldap courant
2034 * @author Benjamin Renard <brenard@easter-eggs.com>
2036 * @retval string Le label des niveaux pour le serveur ldap dourant
2038 public static function getSubDnLabel() {
2039 return (self :: $ldapServer['subDnLabel']!='')?__(self :: $ldapServer['subDnLabel']):_('Level');
2043 * Retourne le nom du subDn
2045 * @param[in] $subDn string subDn
2047 * @retval string Le nom du subDn ou '' sinon
2049 public static function getSubDnName($subDn=false) {
2051 $subDn = self :: $topDn;
2053 if (self :: getSubDnLdapServer()) {
2054 if (isset(self :: $_subDnLdapServer[self :: $ldapServerId][$subDn])) {
2055 return self :: $_subDnLdapServer[self :: $ldapServerId][$subDn];
2062 * L'objet est t-il utilisé pour listé les subDnS
2064 * @param[in] $type string Le type d'objet
2066 * @retval boolean true si le type d'objet est un subDnObject, false sinon
2068 public static function isSubDnLSobject($type) {
2070 if (isset(self :: $ldapServer['subDn']['LSobject']) && is_array(self :: $ldapServer['subDn']['LSobject'])) {
2071 foreach(self :: $ldapServer['subDn']['LSobject'] as $key => $value) {
2081 * Indique si un type d'objet est dans le menu courant
2083 * @retval boolean true si le type d'objet est dans le menu, false sinon
2085 public static function in_menu($LSobject,$topDn=NULL) {
2087 $topDn=self :: $topDn;
2089 return isset(self :: $LSaccess[$topDn][$LSobject]);
2093 * Indique si le serveur LDAP courant a des subDn
2095 * @retval boolean true si le serveur LDAP courant a des subDn, false sinon
2097 public static function haveSubDn() {
2098 return (isset(self :: $ldapServer['subDn']) && is_array(self :: $ldapServer['subDn']));
2102 * Ajoute une information à afficher
2104 * @param[in] $msg string Le message à afficher
2108 public static function addInfo($msg) {
2109 $_SESSION['LSsession_infos'][]=$msg;
2113 * Redirection de l'utilisateur vers une autre URL
2115 * @param[in] $url string L'URL
2116 * @param[in] $exit boolean Si true, l'execution script s'arrête après la redirection
2120 public static function redirect($url,$exit=true) {
2121 $GLOBALS['Smarty'] -> assign('url',$url);
2122 $GLOBALS['Smarty'] -> display('redirect.tpl');
2129 * Retourne l'adresse mail d'emission configurée pour le serveur courant
2131 * @retval string Adresse mail d'emission
2133 public static function getEmailSender() {
2134 return self :: $ldapServer['emailSender'];
2138 * Ajout d'une information d'aide
2140 * @param[in] $group string Le nom du groupe d'infos dans lequels ajouter
2142 * @param[in] $infos array Tableau array(name => value) des infos
2146 public static function addHelpInfos($group,$infos) {
2147 if (is_array($infos)) {
2148 if (isset(self :: $_JSconfigParams['helpInfos'][$group]) && is_array(self :: $_JSconfigParams['helpInfos'][$group])) {
2149 self :: $_JSconfigParams['helpInfos'][$group] = array_merge(self :: $_JSconfigParams['helpInfos'][$group],$infos);
2152 self :: $_JSconfigParams['helpInfos'][$group] = $infos;
2158 * Défini les codes erreur relative à la classe LSsession
2162 private static function defineLSerrors() {
2166 LSerror :: defineError('LSsession_01',
2167 _("LSsession : The constant %{const} is not defined.")
2169 LSerror :: defineError('LSsession_02',
2170 _("LSsession : The %{addon} support is uncertain. Verify system compatibility and the add-on configuration.")
2172 LSerror :: defineError('LSsession_03',
2173 _("LSsession : LDAP server's configuration data are invalid. Can't connect.")
2175 LSerror :: defineError('LSsession_04',
2176 _("LSsession : Failed to load LSobject type %{type} : unknon type.")
2178 LSerror :: defineError('LSsession_05',
2179 _("LSsession : Failed to load LSclass %{class}.")
2181 LSerror :: defineError('LSsession_06',
2182 _("LSsession : Login or password incorrect.")
2184 LSerror :: defineError('LSsession_07',
2185 _("LSsession : Impossible to identify you : Duplication of identities.")
2187 LSerror :: defineError('LSsession_08',
2188 _("LSsession : Can't load class of authentification (%{class}).")
2190 LSerror :: defineError('LSsession_09',
2191 _("LSsession : Can't connect to LDAP server.")
2193 LSerror :: defineError('LSsession_10',
2194 _("LSsession : Impossible to authenticate you.")
2196 LSerror :: defineError('LSsession_11',
2197 _("LSsession : Your are not authorized to do this action.")
2199 LSerror :: defineError('LSsession_12',
2200 _("LSsession : Some informations are missing to display this page.")
2202 // 13 -> 16 : not yet used
2203 LSerror :: defineError('LSsession_17',
2204 _("LSsession : Error during creation of list of levels. Contact administrators. (Code : %{code})")
2206 LSerror :: defineError('LSsession_18',
2207 _("LSsession : The password recovery is disabled for this LDAP server.")
2209 LSerror :: defineError('LSsession_19',
2210 _("LSsession : Some informations are missing to recover your password. Contact administrators.")
2212 LSerror :: defineError('LSsession_20',
2213 _("LSsession : Error during password recovery. Contact administrators.(Step : %{step})")
2215 // 21 : not yet used
2216 LSerror :: defineError('LSsession_22',
2217 _("LSsession : problem during initialisation.")
2222 * Ajax method when change ldapserver on login form
2224 * @param[in] $data array The return data address
2228 public static function ajax_onLdapServerChangedLogin(&$data) {
2229 if ( isset($_REQUEST['server']) ) {
2230 self :: setLdapServer($_REQUEST['server']);
2232 if ( self :: LSldapConnect() ) {
2234 if (isset($_SESSION['LSsession_topDn'])) {
2235 $sel = $_SESSION['LSsession_topDn'];
2240 $list = self :: getSubDnLdapServerOptions($sel,true);
2241 if (is_string($list)) {
2242 $data['list_topDn'] = "<select name='LSsession_topDn' id='LSsession_topDn'>".$list."</select>";
2243 $data['subDnLabel'] = self :: getSubDnLabel();
2246 $data['recoverPassword'] = isset(self :: $ldapServer['recoverPassword']);
2251 * Ajax method when change ldapserver on recoverPassword form
2253 * @param[in] $data array The return data address
2257 public static function ajax_onLdapServerChangedRecoverPassword(&$data) {
2258 if ( isset($_REQUEST['server']) ) {
2259 self :: setLdapServer($_REQUEST['server']);
2260 $data=array('recoverPassword' => isset(self :: $ldapServer['recoverPassword']));