2 /*******************************************************************************
3 * Copyright (C) 2007 Easter-eggs
4 * http://ldapsaisie.labs.libre-entreprise.org
6 * Author: See AUTHORS file in top-level directory.
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License version 2
10 * as published by the Free Software Foundation.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21 ******************************************************************************/
24 * Gestion des sessions
26 * Cette classe gère les sessions d'utilisateurs.
28 * @author Benjamin Renard <brenard@easter-eggs.com>
32 // La configuration du serveur Ldap utilisé
33 public static $ldapServer = NULL;
35 // L'id du serveur Ldap utilisé
36 private static $ldapServerId = NULL;
39 private static $topDn = NULL;
41 // Le DN de l'utilisateur connecté
42 private static $dn = NULL;
44 // Le RDN de l'utilisateur connecté (son identifiant)
45 private static $rdn = NULL;
47 // Les LSprofiles de l'utilisateur
48 private static $LSprofiles = array();
50 // Les droits d'accès de l'utilisateur
51 private static $LSaccess = array();
53 // Les fichiers temporaires
54 private static $tmp_file = array();
56 // Langue et encodage actuel
57 private static $lang = NULL;
58 private static $encoding = NULL;
61 * Constante de classe non stockée en session
63 // Le template à afficher
64 private static $template = NULL;
66 // Les subDn des serveurs Ldap
67 private static $_subDnLdapServer = array();
70 private static $ajaxDisplay = false;
72 // Les fichiers JS à charger dans la page
73 private static $JSscripts = array();
75 // Les paramètres JS à communiquer dans la page
76 private static $_JSconfigParams = array();
78 // Les fichiers CSS à charger dans la page
79 private static $CssFiles = array();
81 // L'objet de l'utilisateur connecté
82 private static $LSuserObject = NULL;
84 // The LSauht object of the session
85 private static $LSauthObject = false;
88 * Include un fichier PHP
90 * @author Benjamin Renard <brenard@easter-eggs.com>
92 * @retval true si tout c'est bien passé, false sinon
94 public static function includeFile($file) {
95 if (file_exists(LS_LOCAL_DIR.'/'.$file)) {
96 $file=LS_LOCAL_DIR.'/'.$file;
98 elseif (!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 :: loadLSclass('LStemplate') ) {
136 self :: addJSconfigParam('LS_IMAGES_DIR',LS_IMAGES_DIR);
137 return LStemplate :: start(
139 'smarty_path' => LSconfig :: get('Smarty'),
140 'template_dir' => LS_TEMPLATES_DIR,
141 'compile_dir' => LS_TMP_DIR,
143 'debug_smarty' => (isset($_REQUEST['LStemplate_debug'])),
151 * Retourne le topDn de la session
153 * @author Benjamin Renard <brenard@easter-eggs.com>
155 * @retval string le topDn de la session
157 public static function getTopDn() {
158 if (!is_null(self :: $topDn)) {
159 return self :: $topDn;
162 return self :: getRootDn();
167 * Retourne le rootDn de la session
169 * @author Benjamin Renard <brenard@easter-eggs.com>
171 * @retval string le rootDn de la session
173 public static function getRootDn() {
174 return self :: $ldapServer['ldap_config']['basedn'];
178 * Initialisation de la gestion des erreurs
180 * Création de l'objet LSerror
182 * @author Benjamin Renard <brenard@easter-eggs.com
184 * @retval boolean true si l'initialisation a réussi, false sinon.
186 private static function startLSerror() {
187 if(!self :: loadLSclass('LSerror')) {
190 self :: defineLSerrors();
195 * Chargement d'une classe d'LdapSaisie
197 * @param[in] $class Nom de la classe à charger (Exemple : LSpeople)
198 * @param[in] $type (Optionnel) Type de classe à charger (Exemple : LSobjects)
200 * @author Benjamin Renard <brenard@easter-eggs.com
202 * @retval boolean true si le chargement a réussi, false sinon.
204 public static function loadLSclass($class,$type='') {
205 if (class_exists($class))
209 return self :: includeFile(LS_CLASS_DIR .'class.'.$type.$class.'.php');
213 * Chargement d'un object LdapSaisie
215 * @param[in] $object Nom de l'objet à charger
217 * @retval boolean true si le chargement a réussi, false sinon.
219 public static function loadLSobject($object) {
220 if(class_exists($object)) {
224 self :: loadLSclass('LSldapObject');
225 if (!self :: loadLSclass($object,'LSobjects')) {
228 if (!self :: includeFile( LS_OBJECTS_DIR . 'config.LSobjects.'.$object.'.php' )) {
232 if (!LSconfig :: set("LSobjects.$object",$GLOBALS['LSobjects'][$object])) {
235 else if (isset($GLOBALS['LSobjects'][$object]['LSaddons'])){
236 if (is_array($GLOBALS['LSobjects'][$object]['LSaddons'])) {
237 foreach ($GLOBALS['LSobjects'][$object]['LSaddons'] as $addon) {
238 if (!self :: loadLSaddon($addon)) {
244 if (!self :: loadLSaddon($GLOBALS['LSobjects'][$object]['LSaddons'])) {
251 LSerror :: addErrorCode('LSsession_04',$object);
258 * Chargement d'un addons d'LdapSaisie
260 * @param[in] $addon Nom de l'addon à charger (Exemple : samba)
262 * @author Benjamin Renard <brenard@easter-eggs.com
264 * @retval boolean true si le chargement a réussi, false sinon.
266 public static function loadLSaddon($addon) {
267 if(self :: includeFile(LS_ADDONS_DIR .'LSaddons.'.$addon.'.php')) {
268 self :: includeFile(LS_CONF_DIR."LSaddons/config.LSaddons.".$addon.".php");
269 if (!call_user_func('LSaddon_'. $addon .'_support')) {
270 LSerror :: addErrorCode('LSsession_02',$addon);
279 * Chargement d'une classe d'authentification d'LdapSaisie
281 * @author Benjamin Renard <brenard@easter-eggs.com
283 * @retval boolean true si le chargement a reussi, false sinon.
285 public static function loadLSauth() {
286 if (self :: loadLSclass('LSauth')) {
290 LSerror :: addErrorCode('LSsession_05','LSauth');
296 * Chargement des addons LdapSaisie
298 * Chargement des LSaddons contenue dans la variable
299 * $GLOBALS['LSaddons']['loads']
301 * @retval boolean true si le chargement a réussi, false sinon.
303 public static function loadLSaddons() {
304 $conf=LSconfig :: get('LSaddons.loads');
305 if(!is_array($conf)) {
306 LSerror :: addErrorCode('LSsession_01',"LSaddons['loads']");
310 foreach ($conf as $addon) {
311 self :: loadLSaddon($addon);
321 public static function setLocale() {
322 if (isset($_REQUEST['lang'])) {
323 $lang = $_REQUEST['lang'];
325 elseif (isset($_SESSION['LSlang'])) {
326 $lang = $_SESSION['LSlang'];
328 elseif (isset(self :: $ldapServer['lang'])) {
329 $lang = self :: $ldapServer['lang'];
332 $lang = LSconfig :: get('lang');
335 if (isset($_REQUEST['encoding'])) {
336 $encoding = $_REQUEST['encoding'];
338 elseif (isset($_SESSION['LSencoding'])) {
339 $encoding = $_SESSION['LSencoding'];
341 elseif (isset(self :: $ldapServer['encoding'])) {
342 $encoding = self :: $ldapServer['encoding'];
345 $encoding = LSconfig :: get('encoding');
348 $_SESSION['LSlang']=$lang;
350 $_SESSION['LSencoding']=$encoding;
351 self :: $encoding=$encoding;
354 if (self :: localeExist($lang,$encoding)) {
356 $lang.='.'.$encoding;
358 setlocale(LC_ALL, $lang);
359 bindtextdomain(LS_TEXT_DOMAIN, LS_I18N_DIR);
360 textdomain(LS_TEXT_DOMAIN);
362 self :: includeFile(LS_I18N_DIR.'/'.$lang.'/lang.php');
364 foreach (listFiles(LS_LOCAL_DIR.'/'.LS_I18N_DIR.'/'.$lang,'/^lang.+\.php$/') as $file) {
365 include(LS_LOCAL_DIR.'/'.LS_I18N_DIR."/$lang/$file");
369 if ($encoding && $lang) {
370 $lang.='.'.$encoding;
372 LSdebug('La locale "'.$lang.'" n\'existe pas, utilisation de la locale par défaut.');
377 * Retourne la liste des langues disponibles
379 * @retval array Tableau/Liste des langues disponibles
381 public static function getLangList() {
382 $list=array('en_US');
383 if (self :: $encoding) {
384 $regex = '^([a-zA-Z_]*)\.'.self :: $encoding.'$';
387 $regex = '^([a-zA-Z_]*)$';
389 if ($handle = opendir(LS_I18N_DIR)) {
390 while (false !== ($file = readdir($handle))) {
391 if(is_dir(LS_I18N_DIR.'/'.$file)) {
392 if (ereg($regex,$file,$regs)) {
393 if (!in_array($regs[1],$list)) {
404 * Retourne la langue courante de la session
406 * @param[in] boolean Si true, le code langue retourné sera court
408 * @retval string La langue de la session
410 public static function getLang($short=false) {
412 return strtolower(self :: $lang[0].self :: $lang[1]);
414 return self :: $lang;
418 * Vérifie si une locale est disponible
420 * @param[in] $lang string La langue (Ex : fr_FR)
421 * @param[in] $encoding string L'encodage de caractère (Ex : UTF8)
423 * @retval boolean True si la locale est disponible, False sinon
425 public static function localeExist($lang,$encoding) {
426 if ( !$lang && !$encoding ) {
429 $locale=$lang.(($encoding)?'.'.$encoding:'');
430 if ($locale=='en_US.UTF8') {
433 return (is_dir(LS_I18N_DIR.'/'.$locale));
437 * Initialisation LdapSaisie
439 * @retval boolean True si l'initialisation à réussi, false sinon.
441 public static function initialize() {
442 if (!self :: startLSconfig()) {
446 self :: startLSerror();
447 self :: startLStemplate();
453 self :: loadLSaddons();
454 self :: loadLSauth();
459 * Initialisation de la session LdapSaisie
461 * Initialisation d'une LSsession :
462 * - Authentification et activation du mécanisme de session de LdapSaisie
463 * - ou Chargement des paramètres de la session à partir de la variable
464 * $_SESSION['LSsession'].
465 * - ou Destruction de la session en cas de $_GET['LSsession_logout'].
467 * @retval boolean True si l'initialisation à réussi (utilisateur authentifié), false sinon.
469 public static function startLSsession() {
470 if (!self :: initialize()) {
474 if(isset($_SESSION['LSsession']['dn']) && !isset($_GET['LSsession_recoverPassword'])) {
475 LSdebug('LSsession : Session existente');
476 // --------------------- Session existante --------------------- //
477 self :: $topDn = $_SESSION['LSsession']['topDn'];
478 self :: $dn = $_SESSION['LSsession']['dn'];
479 self :: $rdn = $_SESSION['LSsession']['rdn'];
480 self :: $ldapServerId = $_SESSION['LSsession']['ldapServerId'];
481 self :: $tmp_file = $_SESSION['LSsession']['tmp_file'];
483 if ( self :: cacheLSprofiles() && !isset($_REQUEST['LSsession_refresh']) ) {
484 self :: setLdapServer(self :: $ldapServerId);
485 if (!LSauth :: start()) {
486 LSdebug("LSsession : can't start LSauth -> stop");
489 self :: $LSprofiles = $_SESSION['LSsession']['LSprofiles'];
490 self :: $LSaccess = $_SESSION['LSsession']['LSaccess'];
491 if (!self :: LSldapConnect())
495 self :: setLdapServer(self :: $ldapServerId);
496 if (!LSauth :: start()) {
497 LSdebug("LSsession : can't start LSauth -> stop");
500 if (!self :: LSldapConnect())
502 self :: loadLSprofiles();
505 if ( self :: cacheSudDn() && (!isset($_REQUEST['LSsession_refresh'])) ) {
506 self :: $_subDnLdapServer = ((isset($_SESSION['LSsession_subDnLdapServer']))?$_SESSION['LSsession_subDnLdapServer']:NULL);
509 if (!self :: loadLSobject(self :: $ldapServer['authObjectType'])) {
513 if (isset($_GET['LSsession_logout'])) {
517 if (is_array($_SESSION['LSsession']['tmp_file'])) {
518 self :: $tmp_file = $_SESSION['LSsession']['tmp_file'];
520 self :: deleteTmpFile();
521 unset($_SESSION['LSsession']);
523 self :: redirect('index.php');
527 if ( !self :: cacheLSprofiles() || isset($_REQUEST['LSsession_refresh']) ) {
528 self :: loadLSaccess();
531 LStemplate :: assign('LSsession_username',self :: getLSuserObject() -> getDisplayName());
533 if (isset ($_POST['LSsession_topDn']) && $_POST['LSsession_topDn']) {
534 if (self :: validSubDnLdapServer($_POST['LSsession_topDn'])) {
535 self :: $topDn = $_POST['LSsession_topDn'];
536 $_SESSION['LSsession']['topDn'] = $_POST['LSsession_topDn'];
544 // --------------------- Session inexistante --------------------- //
545 if (isset($_GET['LSsession_recoverPassword'])) {
548 // Session inexistante
549 if (isset($_POST['LSsession_ldapserver'])) {
550 self :: setLdapServer($_POST['LSsession_ldapserver']);
553 self :: setLdapServer(0);
556 // Connexion au serveur LDAP
557 if (self :: LSldapConnect()) {
560 if (isset($_POST['LSsession_topDn']) && $_POST['LSsession_topDn'] != '' ){
561 self :: $topDn = $_POST['LSsession_topDn'];
564 self :: $topDn = self :: $ldapServer['ldap_config']['basedn'];
566 $_SESSION['LSsession_topDn']=self :: $topDn;
568 if (!LSauth :: start()) {
569 LSdebug("LSsession : can't start LSauth -> stop");
573 if (isset($_GET['LSsession_recoverPassword'])) {
574 $recoveryPasswordInfos = self :: recoverPasswd(
575 $_REQUEST['LSsession_user'],
576 $_GET['recoveryHash']
580 $LSuserObject = LSauth :: forceAuthentication();
582 // Authentication successful
583 self :: $LSuserObject = $LSuserObject;
584 self :: $dn = $LSuserObject->getValue('dn');
585 self :: $rdn = $LSuserObject->getValue('rdn');
586 self :: loadLSprofiles();
587 self :: loadLSaccess();
588 LStemplate :: assign('LSsession_username',self :: getLSuserObject() -> getDisplayName());
589 $_SESSION['LSsession']=self :: getContextInfos();
595 LSerror :: addErrorCode('LSsession_09');
598 if (self :: $ldapServerId) {
599 LStemplate :: assign('ldapServerId',self :: $ldapServerId);
601 LStemplate :: assign('topDn',self :: $topDn);
602 if (isset($_GET['LSsession_recoverPassword'])) {
603 self :: displayRecoverPasswordForm($recoveryPasswordInfos);
605 elseif(LSauth :: displayLoginForm()) {
606 self :: displayLoginForm();
609 self :: setTemplate('blank.tpl');
610 LSerror :: addErrorCode('LSsession_10');
617 * Do recover password
619 * @param[in] $username string The submited username
620 * @param[in] $recoveryHash string The submited recoveryHash
622 * @retval array The recoveryPassword infos for template
624 private static function recoverPasswd($username,$recoveryHash) {
625 $recoveryPasswordInfos=array();
626 if ( self :: loadLSobject(self :: $ldapServer['authObjectType']) ) {
627 $authobject = new self :: $ldapServer['authObjectType']();
628 if (!empty($recoveryHash)) {
629 $filter=Net_LDAP2_Filter::create(
630 self :: $ldapServer['recoverPassword']['recoveryHashAttr'],
634 $result = $authobject -> listObjects($filter,self :: $topDn);
636 elseif (!empty($username)) {
637 $result = $authobject -> searchObject(
640 self :: $ldapServer['authObjectFilter']
644 return $recoveryPasswordInfos;
647 $nbresult=count($result);
650 LSdebug('hash/username incorrect');
651 LSerror :: addErrorCode('LSsession_06');
653 elseif ($nbresult>1) {
654 LSerror :: addErrorCode('LSsession_07');
657 $rdn = $result[0] -> getValue('rdn');
659 LSdebug('Recover : Id trouvé : '.$username);
660 if (self :: $ldapServer['recoverPassword']) {
661 if (self :: loadLSaddon('mail')) {
662 LSdebug('Récupération active');
664 $emailAddress = $user -> getValue(self :: $ldapServer['recoverPassword']['mailAttr']);
665 $emailAddress = $emailAddress[0];
667 if (checkEmail($emailAddress)) {
668 LSdebug('Email : '.$emailAddress);
669 self :: $dn = $user -> getDn();
671 // 1ère étape : envoie du recoveryHash
672 if (empty($recoveryHash)) {
673 $hash=self :: recoverPasswdFirstStep($user);
675 if (self :: recoverPasswdSendMail($emailAddress,1,$hash)) {
676 // Mail a bien été envoyé
677 $recoveryPasswordInfos['recoveryHashMail']=$emailAddress;
681 // 2nd étape : génération du mot de passe + envoie par mail
683 $pwd=self :: recoverPasswdSecondStep($user);
685 if (self :: recoverPasswdSendMail($emailAddress,2,$pwd)){
686 // Mail a bien été envoyé
687 $recoveryPasswordInfos['newPasswordMail']=$emailAddress;
693 LSerror :: addErrorCode('LSsession_19');
698 LSerror :: addErrorCode('LSsession_18');
702 return $recoveryPasswordInfos;
706 * Send recover password mail
708 * @param[in] $mail string The user's mail
709 * @param[in] $step integer The step
710 * @param[in] $info string The info for formatted message
712 * @retval boolean True on success or False
714 private static function recoverPasswdSendMail($mail,$step,$info) {
717 if (self :: $ldapServer['recoverPassword']['recoveryEmailSender']) {
718 $sendParams['From']=self :: $ldapServer['recoverPassword']['recoveryEmailSender'];
722 if ($_SERVER['HTTPS']=='on') {
723 $recovery_url='https://';
726 $recovery_url='http://';
728 $recovery_url .= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'&recoveryHash='.$info;
730 $subject = self :: $ldapServer['recoverPassword']['recoveryHashMail']['subject'];
732 self :: $ldapServer['recoverPassword']['recoveryHashMail']['msg'],
737 $subject = self :: $ldapServer['recoverPassword']['newPasswordMail']['subject'];
739 self :: $ldapServer['recoverPassword']['newPasswordMail']['msg'],
744 if (!sendMail($mail,$subject,$msg,$sendParams)) {
745 LSdebug("Problème durant l'envoie du mail");
746 LSerror :: addErrorCode('LSsession_20',4);
754 * Do first step of recovering password
756 * @param[in] $user LSldapObject The LSldapObject of the user
758 * @retval string|False The recory hash on success or False
760 private static function recoverPasswdFirstStep($user) {
762 $rdn=$user -> getValue('rdn');
764 $recovery_hash = md5($rdn . strval(time()) . strval(rand()));
766 $lostPasswdForm = $user -> getForm('lostPassword');
767 $lostPasswdForm -> setPostData(
769 self :: $ldapServer['recoverPassword']['recoveryHashAttr'] => $recovery_hash
774 if($lostPasswdForm -> validate()) {
775 if ($user -> updateData('lostPassword')) {
776 // recoveryHash de l'utilisateur mis à jour
777 return $recovery_hash;
780 // Erreur durant la mise à jour de l'objet
781 LSdebug("Erreur durant la mise à jour de l'objet");
782 LSerror :: addErrorCode('LSsession_20',6);
786 // Erreur durant la validation du formulaire de modification de perte de password
787 LSdebug("Erreur durant la validation du formulaire de modification de perte de password");
788 LSerror :: addErrorCode('LSsession_20',5);
794 * Do second step of recovering password
796 * @param[in] $user LSldapObject The LSldapObject of the user
798 * @retval string|False The new password on success or False
800 private static function recoverPasswdSecondStep($user) {
801 $attr=$user -> attrs[self :: $ldapServer['authObjectTypeAttrPwd']];
802 if ($attr instanceof LSattribute) {
803 $mdp = generatePassword(
804 $attr -> config['html_options']['chars'],
805 $attr -> config['html_options']['lenght']
807 LSdebug('Nvx mpd : '.$mdp);
808 $lostPasswdForm = $user -> getForm('lostPassword');
809 $lostPasswdForm -> setPostData(
811 self :: $ldapServer['recoverPassword']['recoveryHashAttr'] => array(''),
812 self :: $ldapServer['authObjectTypeAttrPwd'] => array($mdp)
816 if($lostPasswdForm -> validate()) {
817 if ($user -> updateData('lostPassword')) {
821 // Erreur durant la mise à jour de l'objet
822 LSdebug("Erreur durant la mise à jour de l'objet");
823 LSerror :: addErrorCode('LSsession_20',3);
827 // Erreur durant la validation du formulaire de modification de perte de password
828 LSdebug("Erreur durant la validation du formulaire de modification de perte de password");
829 LSerror :: addErrorCode('LSsession_20',2);
833 // l'attribut password n'existe pas
834 LSdebug("L'attribut password n'existe pas");
835 LSerror :: addErrorCode('LSsession_20',1);
841 * Retourne les informations du contexte
843 * @author Benjamin Renard <brenard@easter-eggs.com
845 * @retval array Tableau associatif des informations du contexte
847 private static function getContextInfos() {
849 'tmp_file' => self :: $tmp_file,
850 'topDn' => self :: $topDn,
852 'rdn' => self :: $rdn,
853 'ldapServerId' => self :: $ldapServerId,
854 'ldapServer' => self :: $ldapServer,
855 'LSprofiles' => self :: $LSprofiles,
856 'LSaccess' => self :: $LSaccess
861 * Retourne l'objet de l'utilisateur connecté
863 * @author Benjamin Renard <brenard@easter-eggs.com
865 * @retval mixed L'objet de l'utilisateur connecté ou false si il n'a pas put
868 public static function getLSuserObject($dn=null) {
872 if (!self :: $LSuserObject) {
873 if (self :: loadLSobject(self :: $ldapServer['authObjectType'])) {
874 self :: $LSuserObject = new self :: $ldapServer['authObjectType']();
875 self :: $LSuserObject -> loadData(self :: $dn);
881 return self :: $LSuserObject;
885 * Retourne le DN de l'utilisateur connecté
887 * @author Benjamin Renard <brenard@easter-eggs.com
889 * @retval string Le DN de l'utilisateur connecté
891 public static function getLSuserObjectDn() {
896 * Modifie l'utilisateur connecté à la volé
898 * @param[in] $object Mixed L'objet Ldap du nouvel utilisateur
899 * le type doit correspondre à
900 * self :: $ldapServer['authObjectType']
902 * @retval boolean True en cas de succès, false sinon
904 public static function changeAuthUser($object) {
905 if ($object instanceof self :: $ldapServer['authObjectType']) {
906 self :: $dn = $object -> getDn();
907 $rdn = $object -> getValue('rdn');
912 self :: $LSuserObject = $object;
914 if(self :: loadLSprofiles()) {
915 self :: loadLSaccess();
916 $_SESSION['LSsession']=self :: getContextInfos();
924 * Définition du serveur Ldap de la session
926 * Définition du serveur Ldap de la session à partir de son ID dans
927 * le tableau LSconfig :: get('ldap_servers').
929 * @param[in] integer Index du serveur Ldap
931 * @retval boolean True sinon false.
933 public static function setLdapServer($id) {
934 $conf = LSconfig :: get("ldap_servers.$id");
935 if ( is_array($conf) ) {
936 self :: $ldapServerId = $id;
937 self :: $ldapServer = $conf;
947 * Connexion au serveur Ldap
949 * @retval boolean True sinon false.
951 public static function LSldapConnect() {
952 if (self :: $ldapServer) {
953 self :: includeFile(LSconfig :: get('NetLDAP2'));
954 if (!self :: loadLSclass('LSldap')) {
957 LSldap :: connect(self :: $ldapServer['ldap_config']);
958 if (LSldap :: isConnected()) {
966 LSerror :: addErrorCode('LSsession_03');
972 * Use this function to know if subDn is enabled for the curent LdapServer
976 public static function subDnIsEnabled() {
977 if (!isset(self :: $ldapServer['subDn'])) {
980 if ( !is_array(self :: $ldapServer['subDn']) ) {
987 * Retourne les sous-dns du serveur Ldap courant
989 * @retval mixed Tableau des subDn, false si une erreur est survenue.
991 public static function getSubDnLdapServer($login=false) {
993 if (self :: cacheSudDn() && isset(self :: $_subDnLdapServer[self :: $ldapServerId][$login])) {
994 return self :: $_subDnLdapServer[self :: $ldapServerId][$login];
996 if (!self::subDnIsEnabled()) {
1000 foreach(self :: $ldapServer['subDn'] as $subDn_name => $subDn_config) {
1001 if ($login && isset($subDn_config['nologin']) && $subDn_config['nologin']) continue;
1002 if ($subDn_name == 'LSobject') {
1003 if (is_array($subDn_config)) {
1004 foreach($subDn_config as $LSobject_name => $LSoject_config) {
1005 if (isset($LSoject_config['basedn']) && !empty($LSoject_config['basedn'])) {
1006 $basedn = $LSoject_config['basedn'];
1009 $basedn = self::getRootDn();
1011 if (isset($LSoject_config['displayName']) && !empty($LSoject_config['displayName'])) {
1012 $displayName = $LSoject_config['displayName'];
1015 $displayName = NULL;
1017 if( self :: loadLSobject($LSobject_name) ) {
1018 if ($subdnobject = new $LSobject_name()) {
1019 $tbl_return = $subdnobject -> getSelectArray(NULL,$basedn,$displayName);
1020 if (is_array($tbl_return)) {
1021 $return=array_merge($return,$tbl_return);
1024 LSerror :: addErrorCode('LSsession_17',3);
1028 LSerror :: addErrorCode('LSsession_17',2);
1034 LSerror :: addErrorCode('LSsession_17',1);
1038 if ((isCompatibleDNs($subDn_config['dn'],self :: $ldapServer['ldap_config']['basedn']))&&($subDn_config['dn']!="")) {
1039 $return[$subDn_config['dn']] = __($subDn_name);
1043 if (self :: cacheSudDn()) {
1044 self :: $_subDnLdapServer[self :: $ldapServerId][$login]=$return;
1045 $_SESSION['LSsession_subDnLdapServer'] = self :: $_subDnLdapServer;
1051 * Retourne la liste de subDn du serveur Ldap utilise
1052 * trié par la profondeur dans l'arboressence (ordre décroissant)
1054 * @return array() Tableau des subDn trié
1056 public static function getSortSubDnLdapServer($login=false) {
1057 $subDnLdapServer = self :: getSubDnLdapServer($login);
1058 if (!$subDnLdapServer) {
1061 uksort($subDnLdapServer,"compareDn");
1062 return $subDnLdapServer;
1066 * Retourne les options d'une liste déroulante pour le choix du topDn
1067 * de connexion au serveur Ldap
1069 * Liste les subdn (self :: $ldapServer['subDn'])
1071 * @retval string Les options (<option>) pour la sélection du topDn.
1073 public static function getSubDnLdapServerOptions($selected=NULL,$login=false) {
1074 $list = self :: getSubDnLdapServer($login);
1078 foreach($list as $dn => $txt) {
1079 if ($selected && ($selected==$dn)) {
1080 $selected_txt = ' selected';
1085 $display.="<option value=\"".$dn."\"$selected_txt>".$txt."</option>\n";
1093 * Vérifie qu'un subDn est déclaré
1095 * @param[in] string Un subDn
1097 * @retval boolean True si le subDn existe, False sinon
1099 public static function validSubDnLdapServer($subDn) {
1100 $listTopDn = self :: getSubDnLdapServer();
1101 if(is_array($listTopDn)) {
1102 foreach($listTopDn as $dn => $txt) {
1112 * Test un couple LSobject/pwd
1114 * Test un bind sur le serveur avec le dn de l'objet et le mot de passe fourni.
1116 * @param[in] LSobject L'object "user" pour l'authentification
1117 * @param[in] string Le mot de passe à tester
1119 * @retval boolean True si l'authentification à réussi, false sinon.
1121 public static function checkUserPwd($object,$pwd) {
1122 return LSldap :: checkBind($object -> getValue('dn'),$pwd);
1126 * Affiche le formulaire de login
1128 * Défini les informations pour le template Smarty du formulaire de login.
1132 public static function displayLoginForm() {
1133 LStemplate :: assign('pagetitle',_('Connection'));
1134 if (isset($_GET['LSsession_logout'])) {
1135 LStemplate :: assign('loginform_action','index.php');
1138 LStemplate :: assign('loginform_action',$_SERVER['REQUEST_URI']);
1140 if (count(LSconfig :: get('ldap_servers'))==1) {
1141 LStemplate :: assign('loginform_ldapserver_style','style="display: none"');
1143 LStemplate :: assign('loginform_label_ldapserver',_('LDAP server'));
1144 $ldapservers_name=array();
1145 $ldapservers_index=array();
1146 foreach(LSconfig :: get('ldap_servers') as $id => $infos) {
1147 $ldapservers_index[]=$id;
1148 $ldapservers_name[]=__($infos['name']);
1150 LStemplate :: assign('loginform_ldapservers_name',$ldapservers_name);
1151 LStemplate :: assign('loginform_ldapservers_index',$ldapservers_index);
1153 LStemplate :: assign('loginform_label_level',_('Level'));
1154 LStemplate :: assign('loginform_label_user',_('Identifier'));
1155 LStemplate :: assign('loginform_label_pwd',_('Password'));
1156 LStemplate :: assign('loginform_label_submit',_('Connect'));
1157 LStemplate :: assign('loginform_label_recoverPassword',_('Forgot your password ?'));
1159 self :: setTemplate('login.tpl');
1160 self :: addJSscript('LSsession_login.js');
1164 * Affiche le formulaire de récupération de mot de passe
1166 * Défini les informations pour le template Smarty du formulaire de
1167 * récupération de mot de passe
1169 * @param[in] $infos array() Information sur le status du processus de
1170 * recouvrement de mot de passe
1174 public static function displayRecoverPasswordForm($recoveryPasswordInfos) {
1175 LStemplate :: assign('pagetitle',_('Recovery of your credentials'));
1176 LStemplate :: assign('recoverpasswordform_action','index.php?LSsession_recoverPassword');
1178 if (count(LSconfig :: get('ldap_servers'))==1) {
1179 LStemplate :: assign('recoverpasswordform_ldapserver_style','style="display: none"');
1182 LStemplate :: assign('recoverpasswordform_label_ldapserver',_('LDAP server'));
1183 $ldapservers_name=array();
1184 $ldapservers_index=array();
1185 foreach(LSconfig :: get('ldap_servers') as $id => $infos) {
1186 $ldapservers_index[]=$id;
1187 $ldapservers_name[]=$infos['name'];
1189 LStemplate :: assign('recoverpasswordform_ldapservers_name',$ldapservers_name);
1190 LStemplate :: assign('recoverpasswordform_ldapservers_index',$ldapservers_index);
1192 LStemplate :: assign('recoverpasswordform_label_user',_('Identifier'));
1193 LStemplate :: assign('recoverpasswordform_label_submit',_('Validate'));
1194 LStemplate :: assign('recoverpasswordform_label_back',_('Back'));
1196 $recoverpassword_msg = _('Please fill the identifier field to proceed recovery procedure');
1198 if (isset($recoveryPasswordInfos['recoveryHashMail'])) {
1199 $recoverpassword_msg = getFData(
1200 _("An email has been sent to %{mail}. " .
1201 "Please follow the instructions on it."),
1202 $recoveryPasswordInfos['recoveryHashMail']
1206 if (isset($recoveryPasswordInfos['newPasswordMail'])) {
1207 $recoverpassword_msg = getFData(
1208 _("Your new password has been sent to %{mail}. "),
1209 $recoveryPasswordInfos['newPasswordMail']
1213 LStemplate :: assign('recoverpassword_msg',$recoverpassword_msg);
1215 self :: setTemplate('recoverpassword.tpl');
1216 self :: addJSscript('LSsession_recoverPassword.js');
1220 * Défini le template Smarty à utiliser
1222 * Remarque : les fichiers de templates doivent se trouver dans le dossier
1225 * @param[in] string Le nom du fichier de template
1229 public static function setTemplate($template) {
1230 self :: $template = $template;
1234 * Ajoute un script JS au chargement de la page
1236 * Remarque : les scripts doivents être dans le dossier LS_JS_DIR.
1238 * @param[in] $script Le nom du fichier de script à charger.
1242 public static function addJSscript($file,$path=NULL) {
1247 self :: $JSscripts[$path.$file]=$script;
1251 * Ajouter un paramètre de configuration Javascript
1253 * @param[in] $name string Nom de la variable de configuration
1254 * @param[in] $val mixed Valeur de la variable de configuration
1258 public static function addJSconfigParam($name,$val) {
1259 self :: $_JSconfigParams[$name]=$val;
1263 * Ajoute une feuille de style au chargement de la page
1265 * Remarque : les scripts doivents être dans le dossier LS_CSS_DIR.
1267 * @param[in] $script Le nom du fichier css à charger.
1271 public static function addCssFile($file,$path=NULL) {
1276 self :: $CssFiles[$path.$file]=$cssFile;
1280 * Affiche le template Smarty
1282 * Charge les dépendances et affiche le template Smarty
1286 public static function displayTemplate() {
1289 foreach ($GLOBALS['defaultJSscipts'] as $script) {
1290 $JSscript_txt.="<script src='".LS_JS_DIR.$script."' type='text/javascript'></script>\n";
1293 foreach (self :: $JSscripts as $script) {
1294 if (!$script['path']) {
1295 $script['path']=LS_JS_DIR;
1298 $script['path'].='/';
1300 $JSscript_txt.="<script src='".$script['path'].$script['file']."' type='text/javascript'></script>\n";
1303 $KAconf = LSconfig :: get('keepLSsessionActive');
1306 (!isset(self :: $ldapServer['keepLSsessionActive']))
1308 (!($KAconf === false))
1311 (self :: $ldapServer['keepLSsessionActive'])
1313 self :: addJSconfigParam('keepLSsessionActive',ini_get('session.gc_maxlifetime'));
1316 LStemplate :: assign('LSjsConfig',json_encode(self :: $_JSconfigParams));
1319 $JSscript_txt.="<script type='text/javascript'>LSdebug_active = 1;</script>\n";
1322 $JSscript_txt.="<script type='text/javascript'>LSdebug_active = 0;</script>\n";
1325 LStemplate :: assign('LSsession_js',$JSscript_txt);
1328 self :: addCssFile("LSdefault.css");
1330 foreach (self :: $CssFiles as $file) {
1331 if (!$file['path']) {
1332 $file['path']=LS_CSS_DIR.'/';
1334 $Css_txt.="<link rel='stylesheet' type='text/css' href='".$file['path'].$file['file']."' />\n";
1336 LStemplate :: assign('LSsession_css',$Css_txt);
1338 if (isset(self :: $LSaccess[self :: $topDn])) {
1339 LStemplate :: assign('LSaccess',self :: $LSaccess[self :: $topDn]);
1343 $listTopDn = self :: getSubDnLdapServer();
1344 if (is_array($listTopDn)) {
1346 LStemplate :: assign('label_level',self :: getSubDnLabel());
1347 LStemplate :: assign('_refresh',_('Refresh'));
1348 $LSsession_topDn_index = array();
1349 $LSsession_topDn_name = array();
1350 foreach($listTopDn as $index => $name) {
1351 $LSsession_topDn_index[] = $index;
1352 $LSsession_topDn_name[] = $name;
1354 LStemplate :: assign('LSsession_subDn_indexes',$LSsession_topDn_index);
1355 LStemplate :: assign('LSsession_subDn_names',$LSsession_topDn_name);
1356 LStemplate :: assign('LSsession_subDn',self :: $topDn);
1357 LStemplate :: assign('LSsession_subDnName',self :: getSubDnName());
1360 LStemplate :: assign('LSlanguages',self :: getLangList());
1361 LStemplate :: assign('LSlang',self :: $lang);
1362 LStemplate :: assign('LSencoding',self :: $encoding);
1363 LStemplate :: assign('lang_label',_('Language'));
1365 LStemplate :: assign('displayLogoutBtn',LSauth :: displayLogoutBtn());
1366 LStemplate :: assign('displaySelfAccess',LSauth :: displaySelfAccess());
1369 if((!empty($_SESSION['LSsession_infos']))&&(is_array($_SESSION['LSsession_infos']))) {
1370 $txt_infos="<ul>\n";
1371 foreach($_SESSION['LSsession_infos'] as $info) {
1372 $txt_infos.="<li>$info</li>\n";
1374 $txt_infos.="</ul>\n";
1375 LStemplate :: assign('LSinfos',$txt_infos);
1376 $_SESSION['LSsession_infos']=array();
1379 if (self :: $ajaxDisplay) {
1380 LStemplate :: assign('LSerror_txt',LSerror :: getErrors());
1381 LStemplate :: assign('LSdebug_txt',LSdebug_print(true));
1384 LSerror :: display();
1387 if (!self :: $template)
1388 self :: setTemplate('empty.tpl');
1390 LStemplate :: assign('connected_as',_("Connected as"));
1392 LStemplate :: display(self :: $template);
1396 * Défini que l'affichage se fera ou non via un retour Ajax
1398 * @param[in] $val boolean True pour que l'affichage se fasse par un retour
1402 public static function setAjaxDisplay($val=true) {
1403 self :: $ajaxDisplay = (boolean)$val;
1407 * Affiche un retour Ajax
1411 public static function displayAjaxReturn($data=array()) {
1412 if (isset($data['LSredirect']) && (!LSdebugDefined()) ) {
1413 echo json_encode($data);
1417 $data['LSjsConfig'] = self :: $_JSconfigParams;
1420 if((!empty($_SESSION['LSsession_infos']))&&(is_array($_SESSION['LSsession_infos']))) {
1421 $txt_infos="<ul>\n";
1422 foreach($_SESSION['LSsession_infos'] as $info) {
1423 $txt_infos.="<li>$info</li>\n";
1425 $txt_infos.="</ul>\n";
1426 $data['LSinfos'] = $txt_infos;
1427 $_SESSION['LSsession_infos']=array();
1430 if (LSerror :: errorsDefined()) {
1431 $data['LSerror'] = LSerror :: getErrors();
1434 if (isset($_REQUEST['imgload'])) {
1435 $data['imgload'] = $_REQUEST['imgload'];
1438 if (LSdebugDefined()) {
1439 $data['LSdebug'] = LSdebug_print(true,false);
1442 echo json_encode($data);
1446 * Retournne un template Smarty compilé
1448 * @param[in] string $template Le template à retourner
1449 * @param[in] array $variables Variables Smarty à assigner avant l'affichage
1451 * @retval string Le HTML compilé du template
1453 public static function fetchTemplate($template,$variables=array()) {
1454 foreach($variables as $name => $val) {
1455 LStemplate :: assign($name,$val);
1457 return LStemplate :: fetch($template);
1461 * Charge les droits LS de l'utilisateur
1463 * @retval boolean True si le chargement à réussi, false sinon.
1465 private static function loadLSprofiles() {
1466 if (is_array(self :: $ldapServer['LSprofiles'])) {
1467 foreach (self :: $ldapServer['LSprofiles'] as $profile => $profileInfos) {
1468 if (is_array($profileInfos)) {
1469 foreach ($profileInfos as $topDn => $rightsInfos) {
1471 * If $topDn == 'LSobject', we search for each LSobject type to find
1472 * all items on witch the user will have powers.
1474 if ($topDn == 'LSobjects') {
1475 if (is_array($rightsInfos)) {
1476 foreach ($rightsInfos as $LSobject => $listInfos) {
1477 if (self :: loadLSclass('LSsearch')) {
1478 if (isset($listInfos['filter'])) {
1479 $filter = self :: getLSuserObject() -> getFData($listInfos['filter']);
1482 $filter = '('.$listInfos['attr'].'='.self :: getLSuserObject() -> getFData($listInfos['attr_value']).')';
1486 'basedn' => (isset($listInfos['basedn'])?$listInfos['basedn']:null),
1490 if (isset($listInfos['params']) && is_array($listInfos['params'])) {
1491 $params = array_merge($listInfos['params'],$params);
1494 $LSsearch = new LSsearch($LSobject,'LSsession :: loadLSprofiles',$params,true);
1495 $LSsearch -> run(false);
1497 self :: $LSprofiles[$profile] = $LSsearch -> listObjectsDn();
1502 LSdebug('LSobjects => [] doit etre un tableau');
1506 if (is_array($rightsInfos)) {
1507 foreach($rightsInfos as $dn => $conf) {
1508 if ((isset($conf['attr'])) && (isset($conf['LSobject']))) {
1509 if( self :: loadLSobject($conf['LSobject']) ) {
1510 if ($object = new $conf['LSobject']()) {
1511 if ($object -> loadData($dn)) {
1512 $listDns=$object -> getValue($conf['attr']);
1513 $valKey = (isset($conf['attr_value']))?$conf['attr_value']:'%{dn}';
1514 $val = self :: getLSuserObject() -> getFData($valKey);
1515 if (is_array($listDns)) {
1516 if (in_array($val,$listDns)) {
1517 self :: $LSprofiles[$profile][] = $topDn;
1522 LSdebug('Impossible de chargé le dn : '.$dn);
1526 LSdebug('Impossible de créer l\'objet de type : '.$conf['LSobject']);
1531 if (self :: $dn == $dn) {
1532 self :: $LSprofiles[$profile][] = $topDn;
1538 if ( self :: $dn == $rightsInfos ) {
1539 self :: $LSprofiles[$profile][] = $topDn;
1542 } // fin else ($topDn == 'LSobjects')
1543 } // fin foreach($profileInfos)
1544 } // fin is_array($profileInfos)
1545 } // fin foreach LSprofiles
1546 LSdebug(self :: $LSprofiles);
1555 * Charge les droits d'accès de l'utilisateur pour construire le menu de l'interface
1559 private static function loadLSaccess() {
1561 if (isset(self :: $ldapServer['subDn']) && is_array(self :: $ldapServer['subDn'])) {
1562 foreach(self :: $ldapServer['subDn'] as $name => $config) {
1563 if ($name=='LSobject') {
1564 if (is_array($config)) {
1566 // Définition des subDns
1567 foreach($config as $objectType => $objectConf) {
1568 if (self :: loadLSobject($objectType)) {
1569 if ($subdnobject = new $objectType()) {
1570 $tbl = $subdnobject -> getSelectArray(NULL,self::getRootDn(),NULL,NULL,false);
1571 if (is_array($tbl)) {
1572 // Définition des accès
1574 if (is_array($objectConf['LSobjects'])) {
1575 foreach($objectConf['LSobjects'] as $type) {
1576 if (self :: loadLSobject($type)) {
1577 if (self :: canAccess($type)) {
1578 $access[$type] = LSconfig :: get('LSobjects.'.$type.'.label');
1583 foreach($tbl as $dn => $dn_name) {
1584 $LSaccess[$dn]=$access;
1593 if ((isCompatibleDNs(self :: $ldapServer['ldap_config']['basedn'],$config['dn']))&&($config['dn']!='')) {
1595 if (is_array($config['LSobjects'])) {
1596 foreach($config['LSobjects'] as $objectType) {
1597 if (self :: loadLSobject($objectType)) {
1598 if (self :: canAccess($objectType)) {
1599 $access[$objectType] = LSconfig :: get('LSobjects.'.$objectType.'.label');
1604 $LSaccess[$config['dn']]=$access;
1610 if(is_array(self :: $ldapServer['LSaccess'])) {
1612 foreach(self :: $ldapServer['LSaccess'] as $objectType) {
1613 if (self :: loadLSobject($objectType)) {
1614 if (self :: canAccess($objectType)) {
1615 $access[$objectType] = LSconfig :: get('LSobjects.'.$objectType.'.label');
1619 $LSaccess[self :: $topDn] = $access;
1622 if (LSauth :: displaySelfAccess()) {
1623 foreach($LSaccess as $dn => $access) {
1624 $LSaccess[$dn] = array_merge(
1626 'SELF' => 'My account'
1632 self :: $LSaccess = $LSaccess;
1633 $_SESSION['LSsession']['LSaccess'] = $LSaccess;
1637 * Dit si l'utilisateur est du profil pour le DN spécifié
1639 * @param[in] string $profile de l'objet
1640 * @param[in] string $dn DN de l'objet
1642 * @retval boolean True si l'utilisateur est du profil sur l'objet, false sinon.
1644 public static function isLSprofile($dn,$profile) {
1645 if (is_array(self :: $LSprofiles[$profile])) {
1646 foreach(self :: $LSprofiles[$profile] as $topDn) {
1650 else if ( isCompatibleDNs($dn,$topDn) ) {
1659 * Retourne qui est l'utilisateur par rapport à l'object
1661 * @param[in] string Le DN de l'objet
1663 * @retval string 'admin'/'self'/'user' pour Admin , l'utilisateur lui même ou un simple utilisateur
1665 public static function whoami($dn) {
1666 $retval = array('user');
1668 foreach(self :: $LSprofiles as $profile => $infos) {
1669 if(self :: isLSprofile($dn,$profile)) {
1674 if (self :: $dn == $dn) {
1682 * Retourne le droit de l'utilisateur à accèder à un objet
1684 * @param[in] string $LSobject Le type de l'objet
1685 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1686 * @param[in] string $right Le type de droit d'accès à tester ('r'/'w')
1687 * @param[in] string $attr Le nom de l'attribut auquel on test l'accès
1689 * @retval boolean True si l'utilisateur a accès, false sinon
1691 public static function canAccess($LSobject,$dn=NULL,$right=NULL,$attr=NULL) {
1692 if (!self :: loadLSobject($LSobject)) {
1696 $whoami = self :: whoami($dn);
1697 if ($dn==self :: getLSuserObject() -> getValue('dn')) {
1698 if (!self :: in_menu('SELF')) {
1703 $obj = new $LSobject();
1705 if (!self :: in_menu($LSobject,$obj -> subDnValue)) {
1711 $objectdn=LSconfig :: get('LSobjects.'.$LSobject.'.container_dn').','.self :: $topDn;
1712 $whoami = self :: whoami($objectdn);
1715 // Pour un attribut particulier
1718 $attr=LSconfig :: get('LSobjects.'.$LSobject.'.rdn');
1720 if (!is_array(LSconfig :: get('LSobjects.'.$LSobject.'.attrs.'.$attr))) {
1725 foreach($whoami as $who) {
1726 $nr = LSconfig :: get('LSobjects.'.$LSobject.'.attrs.'.$attr.'.rights.'.$who);
1730 else if($nr == 'r') {
1737 if (($right=='r')||($right=='w')) {
1744 if ( ($r=='r') || ($r=='w') ) {
1751 // Pour un attribut quelconque
1752 $attrs_conf=LSconfig :: get('LSobjects.'.$LSobject.'.attrs');
1753 if (is_array($attrs_conf)) {
1754 if (($right=='r')||($right=='w')) {
1755 foreach($whoami as $who) {
1756 foreach ($attrs_conf as $attr_name => $attr_config) {
1757 if (isset($attr_config['rights'][$who]) && $attr_config['rights'][$who]==$right) {
1764 foreach($whoami as $who) {
1765 foreach ($attrs_conf as $attr_name => $attr_config) {
1766 if ( (isset($attr_config['rights'][$who])) && ( ($attr_config['rights'][$who]=='r') || ($attr_config['rights'][$who]=='w') ) ) {
1777 * Retourne le droit de l'utilisateur à editer à un objet
1779 * @param[in] string $LSobject Le type de l'objet
1780 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1781 * @param[in] string $attr Le nom de l'attribut auquel on test l'accès
1783 * @retval boolean True si l'utilisateur a accès, false sinon
1785 public static function canEdit($LSobject,$dn=NULL,$attr=NULL) {
1786 return self :: canAccess($LSobject,$dn,'w',$attr);
1790 * Retourne le droit de l'utilisateur à supprimer 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)
1795 * @retval boolean True si l'utilisateur a accès, false sinon
1797 public static function canRemove($LSobject,$dn) {
1798 return self :: canAccess($LSobject,$dn,'w','rdn');
1802 * Retourne le droit de l'utilisateur à créer un objet
1804 * @param[in] string $LSobject Le type de l'objet
1806 * @retval boolean True si l'utilisateur a accès, false sinon
1808 public static function canCreate($LSobject) {
1809 if (!self :: loadLSobject($LSobject)) {
1812 if (LSconfig :: get("LSobjects.$LSobject.disable_creation")) {
1815 return self :: canAccess($LSobject,NULL,'w','rdn');
1819 * Retourne le droit de l'utilisateur à gérer la relation d'objet
1821 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1822 * @param[in] string $LSobject Le type de l'objet
1823 * @param[in] string $relationName Le nom de la relation avec l'objet
1824 * @param[in] string $right Le type de droit a vérifier ('r' ou 'w')
1826 * @retval boolean True si l'utilisateur a accès, false sinon
1828 public static function relationCanAccess($dn,$LSobject,$relationName,$right=NULL) {
1829 $relConf=LSconfig :: get('LSobjects.'.$LSobject.'.LSrelation.'.$relationName);
1830 if (!is_array($relConf))
1832 $whoami = self :: whoami($dn);
1834 if (($right=='w') || ($right=='r')) {
1836 foreach($whoami as $who) {
1837 $nr = ((isset($relConf['rights'][$who]))?$relConf['rights'][$who]:'');
1841 else if($nr == 'r') {
1853 foreach($whoami as $who) {
1854 if ((isset($relConf['rights'][$who])) && ( ($relConf['rights'][$who] == 'w') || ($relConf['rights'][$who] == 'r') ) ) {
1863 * Retourne le droit de l'utilisateur à modifier la relation d'objet
1865 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1866 * @param[in] string $LSobject Le type de l'objet
1867 * @param[in] string $relationName Le nom de la relation avec l'objet
1869 * @retval boolean True si l'utilisateur a accès, false sinon
1871 public static function relationCanEdit($dn,$LSobject,$relationName) {
1872 return self :: relationCanAccess($dn,$LSobject,$relationName,'w');
1876 * Retourne le droit de l'utilisateur a executer une customAction
1878 * @param[in] string $dn Le DN de l'objet
1879 * @param[in] string $LSobject Le type de l'objet
1880 * @param[in] string $customActionName Le nom de la customAction
1882 * @retval boolean True si l'utilisateur peut executer cette customAction, false sinon
1884 public static function canExecuteCustomAction($dn,$LSobject,$customActionName) {
1885 $conf=LSconfig :: get('LSobjects.'.$LSobject.'.customActions.'.$customActionName);
1886 if (!is_array($conf))
1888 $whoami = self :: whoami($dn);
1890 if (isset($conf['rights']) && is_array($conf['rights'])) {
1891 foreach($whoami as $who) {
1892 if (in_array($who,$conf['rights'])) {
1902 * Ajoute un fichier temporaire
1904 * @author Benjamin Renard <brenard@easter-eggs.com>
1908 public static function addTmpFile($value,$filePath) {
1909 $hash = mhash(MHASH_MD5,$value);
1910 self :: $tmp_file[$filePath] = $hash;
1911 $_SESSION['LSsession']['tmp_file'][$filePath] = $hash;
1915 * Retourne le chemin du fichier temporaire si l'existe
1917 * @author Benjamin Renard <brenard@easter-eggs.com>
1919 * @param[in] $value La valeur du fichier
1923 public static function tmpFileExist($value) {
1924 $hash = mhash(MHASH_MD5,$value);
1925 foreach(self :: $tmp_file as $filePath => $contentHash) {
1926 if ($hash == $contentHash) {
1934 * Retourne le chemin du fichier temporaire
1936 * Retourne le chemin du fichier temporaire qu'il créera à partir de la valeur
1937 * s'il n'existe pas déjà .
1939 * @author Benjamin Renard <brenard@easter-eggs.com>
1941 * @param[in] $value La valeur du fichier
1945 public static function getTmpFile($value) {
1946 $exist = self :: tmpFileExist($value);
1948 $img_path = LS_TMP_DIR .rand().'.tmp';
1949 $fp = fopen($img_path, "w");
1950 fwrite($fp, $value);
1952 self :: addTmpFile($value,$img_path);
1961 * Supprime les fichiers temporaires
1963 * @author Benjamin Renard <brenard@easter-eggs.com>
1967 public static function deleteTmpFile($filePath=NULL) {
1970 unset(self :: $tmp_file[$filePath]);
1971 unset($_SESSION['LSsession']['tmp_file'][$filePath]);
1974 foreach(self :: $tmp_file as $file => $content) {
1977 self :: $tmp_file = array();
1978 $_SESSION['LSsession']['tmp_file'] = array();
1983 * Retourne true si le cache des droits est activé
1985 * @author Benjamin Renard <brenard@easter-eggs.com>
1987 * @retval boolean True si le cache des droits est activé, false sinon.
1989 public static function cacheLSprofiles() {
1990 return ( (LSconfig :: get('cacheLSprofiles')) || (self :: $ldapServer['cacheLSprofiles']) );
1994 * Retourne true si le cache des subDn est activé
1996 * @author Benjamin Renard <brenard@easter-eggs.com>
1998 * @retval boolean True si le cache des subDn est activé, false sinon.
2000 public static function cacheSudDn() {
2001 return ( (LSconfig :: get('cacheSubDn')) || (self :: $ldapServer['cacheSubDn']));
2005 * Retourne true si le cache des recherches est activé
2007 * @author Benjamin Renard <brenard@easter-eggs.com>
2009 * @retval boolean True si le cache des recherches est activé, false sinon.
2011 public static function cacheSearch() {
2012 return ( (LSconfig :: get('cacheSearch')) || (self :: $ldapServer['cacheSearch']));
2016 * Retourne le label des niveaux pour le serveur ldap courant
2018 * @author Benjamin Renard <brenard@easter-eggs.com>
2020 * @retval string Le label des niveaux pour le serveur ldap dourant
2022 public static function getSubDnLabel() {
2023 return (self :: $ldapServer['subDnLabel']!='')?__(self :: $ldapServer['subDnLabel']):_('Level');
2027 * Retourne le nom du subDn
2029 * @param[in] $subDn string subDn
2031 * @retval string Le nom du subDn ou '' sinon
2033 public static function getSubDnName($subDn=false) {
2035 $subDn = self :: $topDn;
2037 if (self :: getSubDnLdapServer(false)) {
2038 if (isset(self :: $_subDnLdapServer[self :: $ldapServerId][false][$subDn])) {
2039 return self :: $_subDnLdapServer[self :: $ldapServerId][false][$subDn];
2046 * L'objet est t-il utilisé pour listé les subDnS
2048 * @param[in] $type string Le type d'objet
2050 * @retval boolean true si le type d'objet est un subDnObject, false sinon
2052 public static function isSubDnLSobject($type) {
2054 if (isset(self :: $ldapServer['subDn']['LSobject']) && is_array(self :: $ldapServer['subDn']['LSobject'])) {
2055 foreach(self :: $ldapServer['subDn']['LSobject'] as $key => $value) {
2065 * Indique si un type d'objet est dans le menu courant
2067 * @retval boolean true si le type d'objet est dans le menu, false sinon
2069 public static function in_menu($LSobject,$topDn=NULL) {
2071 $topDn=self :: $topDn;
2073 return isset(self :: $LSaccess[$topDn][$LSobject]);
2077 * Indique si le serveur LDAP courant a des subDn
2079 * @retval boolean true si le serveur LDAP courant a des subDn, false sinon
2081 public static function haveSubDn() {
2082 return (isset(self :: $ldapServer['subDn']) && is_array(self :: $ldapServer['subDn']));
2086 * Ajoute une information à afficher
2088 * @param[in] $msg string Le message à afficher
2092 public static function addInfo($msg) {
2093 $_SESSION['LSsession_infos'][]=$msg;
2097 * Redirection de l'utilisateur vers une autre URL
2099 * @param[in] $url string L'URL
2100 * @param[in] $exit boolean Si true, l'execution script s'arrête après la redirection
2104 public static function redirect($url,$exit=true) {
2105 LStemplate :: assign('url',$url);
2106 LStemplate :: display('redirect.tpl');
2113 * Retourne l'adresse mail d'emission configurée pour le serveur courant
2115 * @retval string Adresse mail d'emission
2117 public static function getEmailSender() {
2118 return self :: $ldapServer['emailSender'];
2122 * Ajout d'une information d'aide
2124 * @param[in] $group string Le nom du groupe d'infos dans lequels ajouter
2126 * @param[in] $infos array Tableau array(name => value) des infos
2130 public static function addHelpInfos($group,$infos) {
2131 if (is_array($infos)) {
2132 if (isset(self :: $_JSconfigParams['helpInfos'][$group]) && is_array(self :: $_JSconfigParams['helpInfos'][$group])) {
2133 self :: $_JSconfigParams['helpInfos'][$group] = array_merge(self :: $_JSconfigParams['helpInfos'][$group],$infos);
2136 self :: $_JSconfigParams['helpInfos'][$group] = $infos;
2142 * Défini les codes erreur relative à la classe LSsession
2146 private static function defineLSerrors() {
2150 LSerror :: defineError('LSsession_01',
2151 _("LSsession : The constant %{const} is not defined.")
2153 LSerror :: defineError('LSsession_02',
2154 _("LSsession : The %{addon} support is uncertain. Verify system compatibility and the add-on configuration.")
2156 LSerror :: defineError('LSsession_03',
2157 _("LSsession : LDAP server's configuration data are invalid. Can't connect.")
2159 LSerror :: defineError('LSsession_04',
2160 _("LSsession : Failed to load LSobject type %{type} : unknon type.")
2162 LSerror :: defineError('LSsession_05',
2163 _("LSsession : Failed to load LSclass %{class}.")
2165 LSerror :: defineError('LSsession_06',
2166 _("LSsession : Login or password incorrect.")
2168 LSerror :: defineError('LSsession_07',
2169 _("LSsession : Impossible to identify you : Duplication of identities.")
2171 LSerror :: defineError('LSsession_08',
2172 _("LSsession : Can't load class of authentification (%{class}).")
2174 LSerror :: defineError('LSsession_09',
2175 _("LSsession : Can't connect to LDAP server.")
2177 LSerror :: defineError('LSsession_10',
2178 _("LSsession : Impossible to authenticate you.")
2180 LSerror :: defineError('LSsession_11',
2181 _("LSsession : Your are not authorized to do this action.")
2183 LSerror :: defineError('LSsession_12',
2184 _("LSsession : Some informations are missing to display this page.")
2186 LSerror :: defineError('LSsession_13',
2187 _("LSsession : The function of the custom action %{name} does not exists or is not configured.")
2189 // 14 -> 16 : not yet used
2190 LSerror :: defineError('LSsession_17',
2191 _("LSsession : Error during creation of list of levels. Contact administrators. (Code : %{code})")
2193 LSerror :: defineError('LSsession_18',
2194 _("LSsession : The password recovery is disabled for this LDAP server.")
2196 LSerror :: defineError('LSsession_19',
2197 _("LSsession : Some informations are missing to recover your password. Contact administrators.")
2199 LSerror :: defineError('LSsession_20',
2200 _("LSsession : Error during password recovery. Contact administrators.(Step : %{step})")
2202 // 21 : not yet used
2203 LSerror :: defineError('LSsession_22',
2204 _("LSsession : problem during initialisation.")
2209 * Ajax method when change ldapserver on login form
2211 * @param[in] $data array The return data address
2215 public static function ajax_onLdapServerChangedLogin(&$data) {
2216 if ( isset($_REQUEST['server']) ) {
2217 self :: setLdapServer($_REQUEST['server']);
2219 if ( self :: LSldapConnect() ) {
2220 if (session_id()=="") session_start();
2221 if (isset($_SESSION['LSsession_topDn'])) {
2222 $sel = $_SESSION['LSsession_topDn'];
2227 $list = self :: getSubDnLdapServerOptions($sel,true);
2228 if (is_string($list)) {
2229 $data['list_topDn'] = "<select name='LSsession_topDn' id='LSsession_topDn'>".$list."</select>";
2230 $data['subDnLabel'] = self :: getSubDnLabel();
2233 $data['recoverPassword'] = isset(self :: $ldapServer['recoverPassword']);
2238 * Ajax method when change ldapserver on recoverPassword form
2240 * @param[in] $data array The return data address
2244 public static function ajax_onLdapServerChangedRecoverPassword(&$data) {
2245 if ( isset($_REQUEST['server']) ) {
2246 self :: setLdapServer($_REQUEST['server']);
2247 $data=array('recoverPassword' => isset(self :: $ldapServer['recoverPassword']));