2 /*******************************************************************************
3 * Copyright (C) 2007 Easter-eggs
4 * http://ldapsaisie.labs.libre-entreprise.org
6 * Author: See AUTHORS file in top-level directory.
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License version 2
10 * as published by the Free Software Foundation.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21 ******************************************************************************/
24 * Gestion des sessions
26 * Cette classe gère les sessions d'utilisateurs.
28 * @author Benjamin Renard <brenard@easter-eggs.com>
32 // La configuration du serveur Ldap utilisé
33 public static $ldapServer = NULL;
35 // L'id du serveur Ldap utilisé
36 private static $ldapServerId = NULL;
39 private static $topDn = NULL;
41 // Le DN de l'utilisateur connecté
42 private static $dn = NULL;
44 // Le RDN de l'utilisateur connecté (son identifiant)
45 private static $rdn = NULL;
47 // Les LSprofiles de l'utilisateur
48 private static $LSprofiles = array();
50 // Les droits d'accès de l'utilisateur
51 private static $LSaccess = array();
53 // Authentification parameters
54 private static $authParams = array();
56 // Les fichiers temporaires
57 private static $tmp_file = array();
59 // Langue et encodage actuel
60 private static $lang = NULL;
61 private static $encoding = NULL;
64 * Constante de classe non stockée en session
66 // Le template à afficher
67 private static $template = NULL;
69 // Les subDn des serveurs Ldap
70 private static $_subDnLdapServer = array();
73 private static $ajaxDisplay = false;
75 // Les fichiers JS à charger dans la page
76 private static $JSscripts = array();
78 // Les paramètres JS à communiquer dans la page
79 private static $_JSconfigParams = array();
81 // Les fichiers CSS à charger dans la page
82 private static $CssFiles = array();
84 // L'objet de l'utilisateur connecté
85 private static $LSuserObject = NULL;
88 * Include un fichier PHP
90 * @author Benjamin Renard <brenard@easter-eggs.com>
92 * @retval true si tout c'est bien passé, false sinon
94 public static function includeFile($file) {
95 if (!file_exists($file)) {
99 return include_once($file);
102 return @include_once($file);
108 * Lancement de LSconfig
110 * @author Benjamin Renard <brenard@easter-eggs.com>
112 * @retval true si tout c'est bien passé, false sinon
114 private static function startLSconfig() {
115 if (self :: loadLSclass('LSconfig')) {
116 if (LSconfig :: start()) {
120 die("ERROR : Can't load configuration files.");
125 * Lancement et initialisation de Smarty
127 * @author Benjamin Renard <brenard@easter-eggs.com>
129 * @retval true si tout c'est bien passé, false sinon
131 private static function startLStemplate() {
132 if ( self :: includeFile(LSconfig :: get('Smarty')) ) {
133 $GLOBALS['Smarty'] = new Smarty();
134 $GLOBALS['Smarty'] -> template_dir = LS_TEMPLATES_DIR;
135 $GLOBALS['Smarty'] -> compile_dir = LS_TMP_DIR;
138 $GLOBALS['Smarty'] -> caching = 0;
139 // cache files are always regenerated
140 $GLOBALS['Smarty'] -> force_compile = TRUE;
141 // recompile template if it is changed
142 $GLOBALS['Smarty'] -> compile_check = TRUE;
143 if (isset($_REQUEST['debug_smarty'])) {
145 $GLOBALS['Smarty'] -> debugging = true;
149 $GLOBALS['Smarty'] -> assign('LS_CSS_DIR',LS_CSS_DIR);
150 $GLOBALS['Smarty'] -> assign('LS_IMAGES_DIR',LS_IMAGES_DIR);
152 self :: addJSconfigParam('LS_IMAGES_DIR',LS_IMAGES_DIR);
155 die("ERROR : Can't load Smarty.");
160 * Retourne le topDn de la session
162 * @author Benjamin Renard <brenard@easter-eggs.com>
164 * @retval string le topDn de la session
166 public static function getTopDn() {
167 if (!is_null(self :: $topDn)) {
168 return self :: $topDn;
171 return self :: getRootDn();
176 * Retourne le rootDn de la session
178 * @author Benjamin Renard <brenard@easter-eggs.com>
180 * @retval string le rootDn de la session
182 public static function getRootDn() {
183 return self :: $ldapServer['ldap_config']['basedn'];
187 * Initialisation de la gestion des erreurs
189 * Création de l'objet LSerror
191 * @author Benjamin Renard <brenard@easter-eggs.com
193 * @retval boolean true si l'initialisation a réussi, false sinon.
195 private static function startLSerror() {
196 if(!self :: loadLSclass('LSerror')) {
199 self :: defineLSerrors();
204 * Chargement d'une classe d'LdapSaisie
206 * @param[in] $class Nom de la classe à charger (Exemple : LSpeople)
207 * @param[in] $type (Optionnel) Type de classe à charger (Exemple : LSobjects)
209 * @author Benjamin Renard <brenard@easter-eggs.com
211 * @retval boolean true si le chargement a réussi, false sinon.
213 public static function loadLSclass($class,$type='') {
214 if (class_exists($class))
218 return self :: includeFile(LS_CLASS_DIR .'class.'.$type.$class.'.php');
222 * Chargement d'un object LdapSaisie
224 * @param[in] $object Nom de l'objet à charger
226 * @retval boolean true si le chargement a réussi, false sinon.
228 public static function loadLSobject($object) {
229 if(class_exists($object)) {
233 self :: loadLSclass('LSldapObject');
234 if (!self :: loadLSclass($object,'LSobjects')) {
237 if (!self :: includeFile( LS_OBJECTS_DIR . 'config.LSobjects.'.$object.'.php' )) {
241 if (!LSconfig :: set("LSobjects.$object",$GLOBALS['LSobjects'][$object])) {
244 else if (isset($GLOBALS['LSobjects'][$object]['LSaddons'])){
245 if (is_array($GLOBALS['LSobjects'][$object]['LSaddons'])) {
246 foreach ($GLOBALS['LSobjects'][$object]['LSaddons'] as $addon) {
247 if (!self :: loadLSaddon($addon)) {
253 if (!self :: loadLSaddon($GLOBALS['LSobjects'][$object]['LSaddons'])) {
260 LSerror :: addErrorCode('LSsession_04',$object);
267 * Chargement d'un addons d'LdapSaisie
269 * @param[in] $addon Nom de l'addon à charger (Exemple : samba)
271 * @author Benjamin Renard <brenard@easter-eggs.com
273 * @retval boolean true si le chargement a réussi, false sinon.
275 public static function loadLSaddon($addon) {
276 if(self :: includeFile(LS_ADDONS_DIR .'LSaddons.'.$addon.'.php')) {
277 self :: includeFile(LS_CONF_DIR."LSaddons/config.LSaddons.".$addon.".php");
278 if (!call_user_func('LSaddon_'. $addon .'_support')) {
279 LSerror :: addErrorCode('LSsession_02',$addon);
288 * Chargement des addons LdapSaisie
290 * Chargement des LSaddons contenue dans la variable
291 * $GLOBALS['LSaddons']['loads']
293 * @retval boolean true si le chargement a réussi, false sinon.
295 public static function loadLSaddons() {
296 $conf=LSconfig :: get('LSaddons.loads');
297 if(!is_array($conf)) {
298 LSerror :: addErrorCode('LSsession_01',"LSaddons['loads']");
302 foreach ($conf as $addon) {
303 self :: loadLSaddon($addon);
313 public static function setLocale() {
314 if (isset($_REQUEST['lang'])) {
315 $lang = $_REQUEST['lang'];
317 elseif (isset($_SESSION['LSlang'])) {
318 $lang = $_SESSION['LSlang'];
320 elseif (isset(self :: $ldapServer['lang'])) {
321 $lang = self :: $ldapServer['lang'];
324 $lang = LSconfig :: get('lang');
327 if (isset($_REQUEST['encoding'])) {
328 $encoding = $_REQUEST['encoding'];
330 elseif (isset($_SESSION['LSencoding'])) {
331 $encoding = $_SESSION['LSencoding'];
333 elseif (isset(self :: $ldapServer['encoding'])) {
334 $encoding = self :: $ldapServer['encoding'];
337 $encoding = LSconfig :: get('encoding');
340 $_SESSION['LSlang']=$lang;
342 $_SESSION['LSencoding']=$encoding;
343 self :: $encoding=$encoding;
346 if (self :: localeExist($lang,$encoding)) {
348 $lang.='.'.$encoding;
350 setlocale(LC_ALL, $lang);
351 bindtextdomain(LS_TEXT_DOMAIN, LS_I18N_DIR);
352 textdomain(LS_TEXT_DOMAIN);
354 if (is_file(LS_I18N_DIR.'/'.$lang.'/lang.php')) {
355 include(LS_I18N_DIR.'/'.$lang.'/lang.php');
359 if ($encoding && $lang) {
360 $lang.='.'.$encoding;
362 LSdebug('La locale "'.$lang.'" n\'existe pas, utilisation de la locale par défaut.');
367 * Retourne la liste des langues disponibles
369 * @retval array Tableau/Liste des langues disponibles
371 public static function getLangList() {
372 $list=array('en_US');
373 if (self :: $encoding) {
374 $regex = '^([a-zA-Z_]*)\.'.self :: $encoding.'$';
377 $regex = '^([a-zA-Z_]*)$';
379 if ($handle = opendir(LS_I18N_DIR)) {
380 while (false !== ($file = readdir($handle))) {
381 if(is_dir(LS_I18N_DIR.'/'.$file)) {
382 if (ereg($regex,$file,$regs)) {
383 if (!in_array($regs[1],$list)) {
394 * Retourne la langue courante de la session
396 * @param[in] boolean Si true, le code langue retourné sera court
398 * @retval string La langue de la session
400 public static function getLang($short=false) {
402 return strtolower(self :: $lang[0].self :: $lang[1]);
404 return self :: $lang;
408 * Vérifie si une locale est disponible
410 * @param[in] $lang string La langue (Ex : fr_FR)
411 * @param[in] $encoding string L'encodage de caractère (Ex : UTF8)
413 * @retval boolean True si la locale est disponible, False sinon
415 public static function localeExist($lang,$encoding) {
416 if ( !$lang && !$encoding ) {
419 $locale=$lang.(($encoding)?'.'.$encoding:'');
420 if ($locale=='en_US.UTF8') {
423 return (is_dir(LS_I18N_DIR.'/'.$locale));
427 * Initialisation LdapSaisie
429 * @retval boolean True si l'initialisation à réussi, false sinon.
431 public static function initialize() {
432 if (!self :: startLSconfig()) {
436 self :: startLStemplate();
442 self :: startLSerror();
443 self :: loadLSaddons();
448 * Initialisation de la session LdapSaisie
450 * Initialisation d'une LSsession :
451 * - Authentification et activation du mécanisme de session de LdapSaisie
452 * - ou Chargement des paramètres de la session à partir de la variable
453 * $_SESSION['LSsession'].
454 * - ou Destruction de la session en cas de $_GET['LSsession_logout'].
456 * @retval boolean True si l'initialisation à réussi (utilisateur authentifié), false sinon.
458 public static function startLSsession() {
459 if (!self :: initialize()) {
464 if (isset($_GET['LSsession_logout'])||isset($_GET['LSsession_recoverPassword'])) {
467 if (is_array($_SESSION['LSsession']['tmp_file'])) {
468 self :: $tmp_file = $_SESSION['LSsession']['tmp_file'];
470 self :: deleteTmpFile();
471 unset($_SESSION['LSsession']);
474 // Récupération de mot de passe
475 if (isset($_GET['recoveryHash'])) {
476 $_POST['LSsession_user'] = 'a determiner plus tard';
479 if(isset($_SESSION['LSsession']['dn'])) {
481 self :: $topDn = $_SESSION['LSsession']['topDn'];
482 self :: $dn = $_SESSION['LSsession']['dn'];
483 self :: $rdn = $_SESSION['LSsession']['rdn'];
484 self :: $ldapServerId = $_SESSION['LSsession']['ldapServerId'];
485 self :: $tmp_file = $_SESSION['LSsession']['tmp_file'];
486 self :: $authParams = $_SESSION['LSsession']['authParams'];
488 if ( self :: cacheLSprofiles() && !isset($_REQUEST['LSsession_refresh']) ) {
489 self :: setLdapServer(self :: $ldapServerId);
490 self :: $LSprofiles = $_SESSION['LSsession']['LSprofiles'];
491 self :: $LSaccess = $_SESSION['LSsession']['LSaccess'];
492 if (!self :: LSldapConnect())
496 self :: setLdapServer(self :: $ldapServerId);
497 if (!self :: LSldapConnect())
499 self :: loadLSprofiles();
502 if ( self :: cacheSudDn() && (!isset($_REQUEST['LSsession_refresh'])) ) {
503 self :: $_subDnLdapServer = $_SESSION['LSsession_subDnLdapServer'];
506 if (!self :: loadLSobject(self :: $ldapServer['authObjectType'])) {
510 self :: getLSuserObject();
512 if ( !self :: cacheLSprofiles() || isset($_REQUEST['LSsession_refresh']) ) {
513 self :: loadLSaccess();
516 $GLOBALS['Smarty'] -> assign('LSsession_username',self :: getLSuserObject() -> getDisplayName());
518 if ($_POST['LSsession_topDn']) {
519 if (self :: validSubDnLdapServer($_POST['LSsession_topDn'])) {
520 self :: $topDn = $_POST['LSsession_topDn'];
521 $_SESSION['LSsession']['topDn'] = $_POST['LSsession_topDn'];
529 // Session inexistante
530 if (isset($_POST['LSsession_ldapserver'])) {
531 self :: setLdapServer($_POST['LSsession_ldapserver']);
534 self :: setLdapServer(0);
537 // Connexion au serveur LDAP
538 if (self :: LSldapConnect()) {
541 if ( $_POST['LSsession_topDn'] != '' ){
542 self :: $topDn = $_POST['LSsession_topDn'];
545 self :: $topDn = self :: $ldapServer['ldap_config']['basedn'];
547 $_SESSION['LSsession_topDn']=self :: $topDn;
549 if (isset($_GET['LSsession_recoverPassword'])) {
550 $recoveryPasswordInfos = self :: recoverPasswd(
551 $_REQUEST['LSsession_user'],
552 $_GET['recoveryHash']
556 if (self :: loadLSclass('LSauth')) {
557 if (isset(self :: $ldapServer['LSauth']['method'])) {
558 $LSauthClass = 'LSauth'.self :: $ldapServer['LSauth']['method'];
559 if (!self :: loadLSclass($LSauthClass)) {
560 LSerror :: addErrorCode('LSsession_08',$LSauthClass);
561 $LSauthClass = 'LSauth';
565 $LSauthClass = 'LSauth';
568 $authObj = new $LSauthClass();
569 self :: $authParams = $authObj->params;
570 if ($authObj -> getPostData()) {
571 $LSuserObject = $authObj -> authenticate();
573 // Authentification réussi
574 self :: $LSuserObject = $LSuserObject;
575 self :: $dn = $LSuserObject->getValue('dn');
576 self :: $rdn = $LSuserObject->getValue('rdn');
577 self :: loadLSprofiles();
578 self :: loadLSaccess();
579 $GLOBALS['Smarty'] -> assign('LSsession_username',self :: getLSuserObject() -> getDisplayName());
580 $_SESSION['LSsession']=self :: getContextInfos();
586 LSerror :: addErrorCode('LSsession_05','LSauth');
591 LSerror :: addErrorCode('LSsession_09');
593 if (self :: $ldapServerId) {
594 $GLOBALS['Smarty'] -> assign('ldapServerId',self :: $ldapServerId);
596 $GLOBALS['Smarty'] -> assign('topDn',self :: $topDn);
597 if (isset($_GET['LSsession_recoverPassword'])) {
598 self :: displayRecoverPasswordForm($recoveryPasswordInfos);
600 elseif(self :: $authParams['displayLoginForm']) {
601 self :: displayLoginForm();
604 self :: setTemplate('blank.tpl');
605 LSerror :: addErrorCode('LSsession_10');
612 * Do recover password
614 * @param[in] $username string The submited username
615 * @param[in] $recoveryHash string The submited recoveryHash
617 * @retval array The recoveryPassword infos for template
619 private static function recoverPasswd($username,$recoveryHash) {
620 $recoveryPasswordInfos=array();
621 if ( self :: loadLSobject(self :: $ldapServer['authObjectType']) ) {
622 $authobject = new self :: $ldapServer['authObjectType']();
623 if (!empty($recoveryHash)) {
624 $filter=Net_LDAP2_Filter::create(
625 self :: $ldapServer['recoverPassword']['recoveryHashAttr'],
629 $result = $authobject -> listObjects($filter,self :: $topDn);
632 $result = $authobject -> searchObject(
635 self :: $ldapServer['authObjectFilter']
639 $nbresult=count($result);
642 LSdebug('hash/username incorrect');
643 LSerror :: addErrorCode('LSsession_06');
645 elseif ($nbresult>1) {
646 LSerror :: addErrorCode('LSsession_07');
649 $rdn = $result[0] -> getValue('rdn');
651 LSdebug('Recover : Id trouvé : '.$username);
652 if (self :: $ldapServer['recoverPassword']) {
653 if (self :: loadLSaddon('mail')) {
654 LSdebug('Récupération active');
656 $emailAddress = $user -> getValue(self :: $ldapServer['recoverPassword']['mailAttr']);
657 $emailAddress = $emailAddress[0];
659 if (checkEmail($emailAddress)) {
660 LSdebug('Email : '.$emailAddress);
661 self :: $dn = $user -> getDn();
663 // 1ère étape : envoie du recoveryHash
664 if (empty($recoveryHash)) {
665 $hash=self :: recoverPasswdFirstStep($user);
667 if (self :: recoverPasswdSendMail($emailAddress,1,$hash)) {
668 // Mail a bien été envoyé
669 $recoveryPasswordInfos['recoveryHashMail']=$emailAddress;
673 // 2nd étape : génération du mot de passe + envoie par mail
675 $pwd=self :: recoverPasswdSecondStep($user);
677 if (self :: recoverPasswdSendMail($emailAddress,2,$pwd)){
678 // Mail a bien été envoyé
679 $recoveryPasswordInfos['newPasswordMail']=$emailAddress;
685 LSerror :: addErrorCode('LSsession_19');
690 LSerror :: addErrorCode('LSsession_18');
694 return $recoveryPasswordInfos;
698 * Send recover password mail
700 * @param[in] $mail string The user's mail
701 * @param[in] $step integer The step
702 * @param[in] $info string The info for formatted message
704 * @retval boolean True on success or False
706 private static function recoverPasswdSendMail($mail,$step,$info) {
709 if (self :: $ldapServer['recoverPassword']['recoveryEmailSender']) {
710 $sendParams['From']=self :: $ldapServer['recoverPassword']['recoveryEmailSender'];
714 if ($_SERVER['HTTPS']=='on') {
715 $recovery_url='https://';
718 $recovery_url='http://';
720 $recovery_url .= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'&recoveryHash='.$info;
722 $subject = self :: $ldapServer['recoverPassword']['recoveryHashMail']['subject'];
724 self :: $ldapServer['recoverPassword']['recoveryHashMail']['msg'],
729 $subject = self :: $ldapServer['recoverPassword']['newPasswordMail']['subject'];
731 self :: $ldapServer['recoverPassword']['newPasswordMail']['msg'],
736 if (!sendMail($mail,$subject,$msg,$sendParams)) {
737 LSdebug("Problème durant l'envoie du mail");
738 LSerror :: addErrorCode('LSsession_20',4);
746 * Do first step of recovering password
748 * @param[in] $user LSldapObject The LSldapObject of the user
750 * @retval string|False The recory hash on success or False
752 private static function recoverPasswdFirstStep($user) {
754 $rdn=$user -> getValue('rdn');
756 $recovery_hash = md5($rdn . strval(time()) . strval(rand()));
758 $lostPasswdForm = $user -> getForm('lostPassword');
759 $lostPasswdForm -> setPostData(
761 self :: $ldapServer['recoverPassword']['recoveryHashAttr'] => $recovery_hash
766 if($lostPasswdForm -> validate()) {
767 if ($user -> updateData('lostPassword')) {
768 // recoveryHash de l'utilisateur mis à jour
769 return $recovery_hash;
772 // Erreur durant la mise à jour de l'objet
773 LSdebug("Erreur durant la mise à jour de l'objet");
774 LSerror :: addErrorCode('LSsession_20',6);
778 // Erreur durant la validation du formulaire de modification de perte de password
779 LSdebug("Erreur durant la validation du formulaire de modification de perte de password");
780 LSerror :: addErrorCode('LSsession_20',5);
786 * Do second step of recovering password
788 * @param[in] $user LSldapObject The LSldapObject of the user
790 * @retval string|False The new password on success or False
792 private static function recoverPasswdSecondStep($user) {
793 $attr=$user -> attrs[self :: $ldapServer['authObjectTypeAttrPwd']];
794 if ($attr instanceof LSattribute) {
795 $mdp = generatePassword(
796 $attr -> config['html_options']['chars'],
797 $attr -> config['html_options']['lenght']
799 LSdebug('Nvx mpd : '.$mdp);
800 $lostPasswdForm = $user -> getForm('lostPassword');
801 $lostPasswdForm -> setPostData(
803 self :: $ldapServer['recoverPassword']['recoveryHashAttr'] => array(''),
804 self :: $ldapServer['authObjectTypeAttrPwd'] => array($mdp)
808 if($lostPasswdForm -> validate()) {
809 if ($user -> updateData('lostPassword')) {
813 // Erreur durant la mise à jour de l'objet
814 LSdebug("Erreur durant la mise à jour de l'objet");
815 LSerror :: addErrorCode('LSsession_20',3);
819 // Erreur durant la validation du formulaire de modification de perte de password
820 LSdebug("Erreur durant la validation du formulaire de modification de perte de password");
821 LSerror :: addErrorCode('LSsession_20',2);
825 // l'attribut password n'existe pas
826 LSdebug("L'attribut password n'existe pas");
827 LSerror :: addErrorCode('LSsession_20',1);
833 * Retourne les informations du contexte
835 * @author Benjamin Renard <brenard@easter-eggs.com
837 * @retval array Tableau associatif des informations du contexte
839 private static function getContextInfos() {
841 'tmp_file' => self :: $tmp_file,
842 'topDn' => self :: $topDn,
844 'rdn' => self :: $rdn,
845 'ldapServerId' => self :: $ldapServerId,
846 'ldapServer' => self :: $ldapServer,
847 'LSprofiles' => self :: $LSprofiles,
848 'LSaccess' => self :: $LSaccess,
849 'authParams' => self :: $authParams
854 * Retourne l'objet de l'utilisateur connecté
856 * @author Benjamin Renard <brenard@easter-eggs.com
858 * @retval mixed L'objet de l'utilisateur connecté ou false si il n'a pas put
861 public static function getLSuserObject($dn=null) {
865 if (!self :: $LSuserObject) {
866 if (self :: loadLSobject(self :: $ldapServer['authObjectType'])) {
867 self :: $LSuserObject = new self :: $ldapServer['authObjectType']();
868 self :: $LSuserObject -> loadData(self :: $dn);
874 return self :: $LSuserObject;
878 * Retourne le DN de l'utilisateur connecté
880 * @author Benjamin Renard <brenard@easter-eggs.com
882 * @retval string Le DN de l'utilisateur connecté
884 public static function getLSuserObjectDn() {
889 * Modifie l'utilisateur connecté à la volé
891 * @param[in] $object Mixed L'objet Ldap du nouvel utilisateur
892 * le type doit correspondre à
893 * self :: $ldapServer['authObjectType']
895 * @retval boolean True en cas de succès, false sinon
897 public static function changeAuthUser($object) {
898 if ($object instanceof self :: $ldapServer['authObjectType']) {
899 self :: $dn = $object -> getDn();
900 $rdn = $object -> getValue('rdn');
905 self :: $LSuserObject = $object;
907 if(self :: loadLSprofiles()) {
908 self :: loadLSaccess();
909 $_SESSION['LSsession']=self :: getContextInfos();
917 * Définition du serveur Ldap de la session
919 * Définition du serveur Ldap de la session à partir de son ID dans
920 * le tableau LSconfig :: get('ldap_servers').
922 * @param[in] integer Index du serveur Ldap
924 * @retval boolean True sinon false.
926 public static function setLdapServer($id) {
927 $conf = LSconfig :: get("ldap_servers.$id");
928 if ( is_array($conf) ) {
929 self :: $ldapServerId = $id;
930 self :: $ldapServer = $conf;
940 * Connexion au serveur Ldap
942 * @retval boolean True sinon false.
944 public static function LSldapConnect() {
945 if (self :: $ldapServer) {
946 self :: includeFile(LSconfig :: get('NetLDAP2'));
947 if (!self :: loadLSclass('LSldap')) {
950 LSldap :: connect(self :: $ldapServer['ldap_config']);
951 if (LSldap :: isConnected()) {
959 LSerror :: addErrorCode('LSsession_03');
965 * Use this function to know if subDn is enabled for the curent LdapServer
969 public static function subDnIsEnabled() {
970 if (!isset(self :: $ldapServer['subDn'])) {
973 if ( !is_array(self :: $ldapServer['subDn']) ) {
980 * Retourne les sous-dns du serveur Ldap courant
982 * @retval mixed Tableau des subDn, false si une erreur est survenue.
984 public static function getSubDnLdapServer() {
985 if (self :: cacheSudDn() && isset(self :: $_subDnLdapServer[self :: $ldapServerId])) {
986 return self :: $_subDnLdapServer[self :: $ldapServerId];
988 if (!self::subDnIsEnabled()) {
992 foreach(self :: $ldapServer['subDn'] as $subDn_name => $subDn_config) {
993 if ($subDn_name == 'LSobject') {
994 if (is_array($subDn_config)) {
995 foreach($subDn_config as $LSobject_name => $LSoject_config) {
996 if ($LSoject_config['basedn']) {
997 $basedn = $LSoject_config['basedn'];
1000 $basedn = self::getRootDn();
1002 if ($LSoject_config['displayName']) {
1003 $displayName = $LSoject_config['displayName'];
1006 $displayName = NULL;
1008 if( self :: loadLSobject($LSobject_name) ) {
1009 if ($subdnobject = new $LSobject_name()) {
1010 $tbl_return = $subdnobject -> getSelectArray(NULL,$basedn,$displayName);
1011 if (is_array($tbl_return)) {
1012 $return=array_merge($return,$tbl_return);
1015 LSerror :: addErrorCode('LSsession_17',3);
1019 LSerror :: addErrorCode('LSsession_17',2);
1025 LSerror :: addErrorCode('LSsession_17',1);
1029 if ((isCompatibleDNs($subDn_config['dn'],self :: $ldapServer['ldap_config']['basedn']))&&($subDn_config['dn']!="")) {
1030 $return[$subDn_config['dn']] = __($subDn_name);
1034 if (self :: cacheSudDn()) {
1035 self :: $_subDnLdapServer[self :: $ldapServerId]=$return;
1036 $_SESSION['LSsession_subDnLdapServer'] = self :: $_subDnLdapServer;
1042 * Retourne la liste de subDn du serveur Ldap utilise
1043 * trié par la profondeur dans l'arboressence (ordre décroissant)
1045 * @return array() Tableau des subDn trié
1047 public static function getSortSubDnLdapServer() {
1048 $subDnLdapServer = self :: getSubDnLdapServer();
1049 if (!$subDnLdapServer) {
1052 uksort($subDnLdapServer,"compareDn");
1053 return $subDnLdapServer;
1057 * Retourne les options d'une liste déroulante pour le choix du topDn
1058 * de connexion au serveur Ldap
1060 * Liste les subdn (self :: $ldapServer['subDn'])
1062 * @retval string Les options (<option>) pour la sélection du topDn.
1064 public static function getSubDnLdapServerOptions($selected=NULL) {
1065 $list = self :: getSubDnLdapServer();
1069 foreach($list as $dn => $txt) {
1070 if ($selected && ($selected==$dn)) {
1071 $selected_txt = ' selected';
1076 $display.="<option value=\"".$dn."\"$selected_txt>".$txt."</option>\n";
1084 * Vérifie qu'un subDn est déclaré
1086 * @param[in] string Un subDn
1088 * @retval boolean True si le subDn existe, False sinon
1090 public static function validSubDnLdapServer($subDn) {
1091 $listTopDn = self :: getSubDnLdapServer();
1092 if(is_array($listTopDn)) {
1093 foreach($listTopDn as $dn => $txt) {
1103 * Test un couple LSobject/pwd
1105 * Test un bind sur le serveur avec le dn de l'objet et le mot de passe fourni.
1107 * @param[in] LSobject L'object "user" pour l'authentification
1108 * @param[in] string Le mot de passe à tester
1110 * @retval boolean True si l'authentification à réussi, false sinon.
1112 public static function checkUserPwd($object,$pwd) {
1113 return LSldap :: checkBind($object -> getValue('dn'),$pwd);
1117 * Affiche le formulaire de login
1119 * Défini les informations pour le template Smarty du formulaire de login.
1123 public static function displayLoginForm() {
1124 $GLOBALS['Smarty'] -> assign('pagetitle',_('Connection'));
1125 if (isset($_GET['LSsession_logout'])) {
1126 $GLOBALS['Smarty'] -> assign('loginform_action','index.php');
1129 $GLOBALS['Smarty'] -> assign('loginform_action',$_SERVER['REQUEST_URI']);
1131 if (count(LSconfig :: get('ldap_servers'))==1) {
1132 $GLOBALS['Smarty'] -> assign('loginform_ldapserver_style','style="display: none"');
1134 $GLOBALS['Smarty'] -> assign('loginform_label_ldapserver',_('LDAP server'));
1135 $ldapservers_name=array();
1136 $ldapservers_index=array();
1137 foreach(LSconfig :: get('ldap_servers') as $id => $infos) {
1138 $ldapservers_index[]=$id;
1139 $ldapservers_name[]=__($infos['name']);
1141 $GLOBALS['Smarty'] -> assign('loginform_ldapservers_name',$ldapservers_name);
1142 $GLOBALS['Smarty'] -> assign('loginform_ldapservers_index',$ldapservers_index);
1144 $GLOBALS['Smarty'] -> assign('loginform_label_level',_('Level'));
1145 $GLOBALS['Smarty'] -> assign('loginform_label_user',_('Identifier'));
1146 $GLOBALS['Smarty'] -> assign('loginform_label_pwd',_('Password'));
1147 $GLOBALS['Smarty'] -> assign('loginform_label_submit',_('Connect'));
1148 $GLOBALS['Smarty'] -> assign('loginform_label_recoverPassword',_('Forgot your password ?'));
1150 self :: setTemplate('login.tpl');
1151 self :: addJSscript('LSsession_login.js');
1155 * Affiche le formulaire de récupération de mot de passe
1157 * Défini les informations pour le template Smarty du formulaire de
1158 * récupération de mot de passe
1160 * @param[in] $infos array() Information sur le status du processus de
1161 * recouvrement de mot de passe
1165 public static function displayRecoverPasswordForm($recoveryPasswordInfos) {
1166 $GLOBALS['Smarty'] -> assign('pagetitle',_('Recovery of your credentials'));
1167 $GLOBALS['Smarty'] -> assign('recoverpasswordform_action','index.php?LSsession_recoverPassword');
1169 if (count(LSconfig :: get('ldap_servers'))==1) {
1170 $GLOBALS['Smarty'] -> assign('recoverpasswordform_ldapserver_style','style="display: none"');
1173 $GLOBALS['Smarty'] -> assign('recoverpasswordform_label_ldapserver',_('LDAP server'));
1174 $ldapservers_name=array();
1175 $ldapservers_index=array();
1176 foreach(LSconfig :: get('ldap_servers') as $id => $infos) {
1177 $ldapservers_index[]=$id;
1178 $ldapservers_name[]=$infos['name'];
1180 $GLOBALS['Smarty'] -> assign('recoverpasswordform_ldapservers_name',$ldapservers_name);
1181 $GLOBALS['Smarty'] -> assign('recoverpasswordform_ldapservers_index',$ldapservers_index);
1183 $GLOBALS['Smarty'] -> assign('recoverpasswordform_label_user',_('Identifier'));
1184 $GLOBALS['Smarty'] -> assign('recoverpasswordform_label_submit',_('Validate'));
1185 $GLOBALS['Smarty'] -> assign('recoverpasswordform_label_back',_('Back'));
1187 $recoverpassword_msg = _('Please fill the identifier field to proceed recovery procedure');
1189 if (isset($recoveryPasswordInfos['recoveryHashMail'])) {
1190 $recoverpassword_msg = getFData(
1191 _("An email has been sent to %{mail}. " .
1192 "Please follow the instructions on it."),
1193 $recoveryPasswordInfos['recoveryHashMail']
1197 if (isset($recoveryPasswordInfos['newPasswordMail'])) {
1198 $recoverpassword_msg = getFData(
1199 _("Your new password has been sent to %{mail}. "),
1200 $recoveryPasswordInfos['newPasswordMail']
1204 $GLOBALS['Smarty'] -> assign('recoverpassword_msg',$recoverpassword_msg);
1206 self :: setTemplate('recoverpassword.tpl');
1207 self :: addJSscript('LSsession_recoverPassword.js');
1211 * Défini le template Smarty à utiliser
1213 * Remarque : les fichiers de templates doivent se trouver dans le dossier
1216 * @param[in] string Le nom du fichier de template
1220 public static function setTemplate($template) {
1221 self :: $template = $template;
1225 * Ajoute un script JS au chargement de la page
1227 * Remarque : les scripts doivents être dans le dossier LS_JS_DIR.
1229 * @param[in] $script Le nom du fichier de script à charger.
1233 public static function addJSscript($file,$path=NULL) {
1238 self :: $JSscripts[$path.$file]=$script;
1242 * Ajouter un paramètre de configuration Javascript
1244 * @param[in] $name string Nom de la variable de configuration
1245 * @param[in] $val mixed Valeur de la variable de configuration
1249 public static function addJSconfigParam($name,$val) {
1250 self :: $_JSconfigParams[$name]=$val;
1254 * Ajoute une feuille de style au chargement de la page
1256 * Remarque : les scripts doivents être dans le dossier LS_CSS_DIR.
1258 * @param[in] $script Le nom du fichier css à charger.
1262 public static function addCssFile($file,$path=NULL) {
1267 self :: $CssFiles[$path.$file]=$cssFile;
1271 * Affiche le template Smarty
1273 * Charge les dépendances et affiche le template Smarty
1277 public static function displayTemplate() {
1280 foreach ($GLOBALS['defaultJSscipts'] as $script) {
1281 $JSscript_txt.="<script src='".LS_JS_DIR.$script."' type='text/javascript'></script>\n";
1284 foreach (self :: $JSscripts as $script) {
1285 if (!$script['path']) {
1286 $script['path']=LS_JS_DIR;
1289 $script['path'].='/';
1291 $JSscript_txt.="<script src='".$script['path'].$script['file']."' type='text/javascript'></script>\n";
1294 $KAconf = LSconfig :: get('keepLSsessionActive');
1297 (!isset(self :: $ldapServer['keepLSsessionActive']))
1299 (!($KAconf === false))
1302 (self :: $ldapServer['keepLSsessionActive'])
1304 self :: addJSconfigParam('keepLSsessionActive',ini_get('session.gc_maxlifetime'));
1307 $GLOBALS['Smarty'] -> assign('LSjsConfig',json_encode(self :: $_JSconfigParams));
1310 $JSscript_txt.="<script type='text/javascript'>LSdebug_active = 1;</script>\n";
1313 $JSscript_txt.="<script type='text/javascript'>LSdebug_active = 0;</script>\n";
1316 $GLOBALS['Smarty'] -> assign('LSsession_js',$JSscript_txt);
1319 self :: addCssFile("LSdefault.css");
1321 foreach (self :: $CssFiles as $file) {
1322 if (!$file['path']) {
1323 $file['path']=LS_CSS_DIR.'/';
1325 $Css_txt.="<link rel='stylesheet' type='text/css' href='".$file['path'].$file['file']."' />\n";
1327 $GLOBALS['Smarty'] -> assign('LSsession_css',$Css_txt);
1329 if (isset(self :: $LSaccess[self :: $topDn])) {
1330 $GLOBALS['Smarty'] -> assign('LSaccess',self :: $LSaccess[self :: $topDn]);
1334 $listTopDn = self :: getSubDnLdapServer();
1335 if (is_array($listTopDn)) {
1337 $GLOBALS['Smarty'] -> assign('label_level',self :: getSubDnLabel());
1338 $GLOBALS['Smarty'] -> assign('_refresh',_('Refresh'));
1339 $LSsession_topDn_index = array();
1340 $LSsession_topDn_name = array();
1341 foreach($listTopDn as $index => $name) {
1342 $LSsession_topDn_index[] = $index;
1343 $LSsession_topDn_name[] = $name;
1345 $GLOBALS['Smarty'] -> assign('LSsession_subDn_indexes',$LSsession_topDn_index);
1346 $GLOBALS['Smarty'] -> assign('LSsession_subDn_names',$LSsession_topDn_name);
1347 $GLOBALS['Smarty'] -> assign('LSsession_subDn',self :: $topDn);
1348 $GLOBALS['Smarty'] -> assign('LSsession_subDnName',self :: getSubDnName());
1351 $GLOBALS['Smarty'] -> assign('LSlanguages',self :: getLangList());
1352 $GLOBALS['Smarty'] -> assign('LSlang',self :: $lang);
1353 $GLOBALS['Smarty'] -> assign('LSencoding',self :: $encoding);
1354 $GLOBALS['Smarty'] -> assign('lang_label',_('Language'));
1356 $GLOBALS['Smarty'] -> assign('displayLogoutBtn',self :: $authParams['displayLogoutBtn']);
1359 if((!empty($_SESSION['LSsession_infos']))&&(is_array($_SESSION['LSsession_infos']))) {
1360 $txt_infos="<ul>\n";
1361 foreach($_SESSION['LSsession_infos'] as $info) {
1362 $txt_infos.="<li>$info</li>\n";
1364 $txt_infos.="</ul>\n";
1365 $GLOBALS['Smarty'] -> assign('LSinfos',$txt_infos);
1366 $_SESSION['LSsession_infos']=array();
1369 if (self :: $ajaxDisplay) {
1370 $GLOBALS['Smarty'] -> assign('LSerror_txt',LSerror :: getErrors());
1371 $GLOBALS['Smarty'] -> assign('LSdebug_txt',LSdebug_print(true));
1374 LSerror :: display();
1377 if (!self :: $template)
1378 self :: setTemplate('empty.tpl');
1380 $GLOBALS['Smarty'] -> assign('connected_as',_("Connected as"));
1382 $GLOBALS['Smarty'] -> display(self :: $template);
1386 * Défini que l'affichage se fera ou non via un retour Ajax
1388 * @param[in] $val boolean True pour que l'affichage se fasse par un retour
1392 public static function setAjaxDisplay($val=true) {
1393 self :: $ajaxDisplay = (boolean)$val;
1397 * Affiche un retour Ajax
1401 public static function displayAjaxReturn($data=array()) {
1402 if (isset($data['LSredirect']) && (!LSdebugDefined()) ) {
1403 echo json_encode($data);
1407 $data['LSjsConfig'] = self :: $_JSconfigParams;
1410 if((!empty($_SESSION['LSsession_infos']))&&(is_array($_SESSION['LSsession_infos']))) {
1411 $txt_infos="<ul>\n";
1412 foreach($_SESSION['LSsession_infos'] as $info) {
1413 $txt_infos.="<li>$info</li>\n";
1415 $txt_infos.="</ul>\n";
1416 $data['LSinfos'] = $txt_infos;
1417 $_SESSION['LSsession_infos']=array();
1420 if (LSerror :: errorsDefined()) {
1421 $data['LSerror'] = LSerror :: getErrors();
1424 if (isset($_REQUEST['imgload'])) {
1425 $data['imgload'] = $_REQUEST['imgload'];
1428 if (LSdebugDefined()) {
1429 $data['LSdebug'] = LSdebug_print(true,false);
1432 echo json_encode($data);
1436 * Retournne un template Smarty compilé
1438 * @param[in] string $template Le template à retourner
1439 * @param[in] array $variables Variables Smarty à assigner avant l'affichage
1441 * @retval string Le HTML compilé du template
1443 public static function fetchTemplate($template,$variables=array()) {
1444 foreach($variables as $name => $val) {
1445 $GLOBALS['Smarty'] -> assign($name,$val);
1447 return $GLOBALS['Smarty'] -> fetch($template);
1451 * Charge les droits LS de l'utilisateur
1453 * @retval boolean True si le chargement à réussi, false sinon.
1455 private static function loadLSprofiles() {
1456 if (is_array(self :: $ldapServer['LSprofiles'])) {
1457 foreach (self :: $ldapServer['LSprofiles'] as $profile => $profileInfos) {
1458 if (is_array($profileInfos)) {
1459 foreach ($profileInfos as $topDn => $rightsInfos) {
1461 * If $topDn == 'LSobject', we search for each LSobject type to find
1462 * all items on witch the user will have powers.
1464 if ($topDn == 'LSobjects') {
1465 if (is_array($rightsInfos)) {
1466 foreach ($rightsInfos as $LSobject => $listInfos) {
1467 if (self :: loadLSclass('LSsearch')) {
1468 if ($listInfos['filter']) {
1469 $filter = self :: getLSuserObject() -> getFData($listInfos['filter']);
1472 $filter = '('.$listInfos['attr'].'='.self :: getLSuserObject() -> getFData($listInfos['attr_value']).')';
1476 'basedn' => $listInfos['basedn'],
1480 if (is_array($listInfos['params'])) {
1481 $params = array_merge($listInfos['params'],$params);
1484 $LSsearch = new LSsearch($LSobject,'LSsession :: loadLSprofiles',$params,true);
1485 $LSsearch -> run(false);
1487 $LSprofiles[$profile] = $LSsearch -> listObjectsDn();
1492 LSdebug('LSobjects => [] doit etre un tableau');
1496 if (is_array($rightsInfos)) {
1497 foreach($rightsInfos as $dn => $conf) {
1498 if ((isset($conf['attr'])) && (isset($conf['LSobject']))) {
1499 if( self :: loadLSobject($conf['LSobject']) ) {
1500 if ($object = new $conf['LSobject']()) {
1501 if ($object -> loadData($dn)) {
1502 $listDns=$object -> getValue($conf['attr']);
1503 $valKey = (isset($conf['attr_value']))?$conf['attr_value']:'%{dn}';
1504 $val = self :: getLSuserObject() -> getFData($valKey);
1505 if (is_array($listDns)) {
1506 if (in_array($val,$listDns)) {
1507 self :: $LSprofiles[$profile][] = $topDn;
1512 LSdebug('Impossible de chargé le dn : '.$dn);
1516 LSdebug('Impossible de créer l\'objet de type : '.$conf['LSobject']);
1521 if (self :: $dn == $dn) {
1522 self :: $LSprofiles[$profile][] = $topDn;
1528 if ( self :: $dn == $rightsInfos ) {
1529 self :: $LSprofiles[$profile][] = $topDn;
1532 } // fin else ($topDn == 'LSobjects')
1533 } // fin foreach($profileInfos)
1534 } // fin is_array($profileInfos)
1535 } // fin foreach LSprofiles
1536 LSdebug(self :: $LSprofiles);
1545 * Charge les droits d'accès de l'utilisateur pour construire le menu de l'interface
1549 private static function loadLSaccess() {
1551 if (is_array(self :: $ldapServer['subDn'])) {
1552 foreach(self :: $ldapServer['subDn'] as $name => $config) {
1553 if ($name=='LSobject') {
1554 if (is_array($config)) {
1556 // Définition des subDns
1557 foreach($config as $objectType => $objectConf) {
1558 if (self :: loadLSobject($objectType)) {
1559 if ($subdnobject = new $objectType()) {
1560 $tbl = $subdnobject -> getSelectArray(NULL,self::getRootDn(),NULL,NULL,false);
1561 if (is_array($tbl)) {
1562 // Définition des accès
1564 if (is_array($objectConf['LSobjects'])) {
1565 foreach($objectConf['LSobjects'] as $type) {
1566 if (self :: loadLSobject($type)) {
1567 if (self :: canAccess($type)) {
1568 $access[$type] = LSconfig :: get('LSobjects.'.$type.'.label');
1573 foreach($tbl as $dn => $dn_name) {
1574 $LSaccess[$dn]=$access;
1583 if ((isCompatibleDNs(self :: $ldapServer['ldap_config']['basedn'],$config['dn']))&&($config['dn']!='')) {
1585 if (is_array($config['LSobjects'])) {
1586 foreach($config['LSobjects'] as $objectType) {
1587 if (self :: loadLSobject($objectType)) {
1588 if (self :: canAccess($objectType)) {
1589 $access[$objectType] = LSconfig :: get('LSobjects.'.$objectType.'.label');
1594 $LSaccess[$config['dn']]=$access;
1600 if(is_array(self :: $ldapServer['LSaccess'])) {
1602 foreach(self :: $ldapServer['LSaccess'] as $objectType) {
1603 if (self :: loadLSobject($objectType)) {
1604 if (self :: canAccess($objectType)) {
1605 $access[$objectType] = LSconfig :: get('LSobjects.'.$objectType.'.label');
1609 $LSaccess[self :: $topDn] = $access;
1612 foreach($LSaccess as $dn => $access) {
1613 $LSaccess[$dn] = array_merge(
1615 'SELF' => 'My account'
1621 self :: $LSaccess = $LSaccess;
1622 $_SESSION['LSsession']['LSaccess'] = $LSaccess;
1626 * Dit si l'utilisateur est du profil pour le DN spécifié
1628 * @param[in] string $profile de l'objet
1629 * @param[in] string $dn DN de l'objet
1631 * @retval boolean True si l'utilisateur est du profil sur l'objet, false sinon.
1633 public static function isLSprofile($dn,$profile) {
1634 if (is_array(self :: $LSprofiles[$profile])) {
1635 foreach(self :: $LSprofiles[$profile] as $topDn) {
1639 else if ( isCompatibleDNs($dn,$topDn) ) {
1648 * Retourne qui est l'utilisateur par rapport à l'object
1650 * @param[in] string Le DN de l'objet
1652 * @retval string 'admin'/'self'/'user' pour Admin , l'utilisateur lui même ou un simple utilisateur
1654 public static function whoami($dn) {
1655 $retval = array('user');
1657 foreach(self :: $LSprofiles as $profile => $infos) {
1658 if(self :: isLSprofile($dn,$profile)) {
1663 if (self :: $dn == $dn) {
1671 * Retourne le droit de l'utilisateur à accèder à un objet
1673 * @param[in] string $LSobject Le type de l'objet
1674 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1675 * @param[in] string $right Le type de droit d'accès à tester ('r'/'w')
1676 * @param[in] string $attr Le nom de l'attribut auquel on test l'accès
1678 * @retval boolean True si l'utilisateur a accès, false sinon
1680 public static function canAccess($LSobject,$dn=NULL,$right=NULL,$attr=NULL) {
1681 if (!self :: loadLSobject($LSobject)) {
1685 $whoami = self :: whoami($dn);
1686 if ($dn==self :: getLSuserObject() -> getValue('dn')) {
1687 if (!self :: in_menu('SELF')) {
1692 $obj = new $LSobject();
1694 if (!self :: in_menu($LSobject,$obj -> subDnValue)) {
1700 $objectdn=LSconfig :: get('LSobjects.'.$LSobject.'.container_dn').','.self :: $topDn;
1701 $whoami = self :: whoami($objectdn);
1704 // Pour un attribut particulier
1707 $attr=LSconfig :: get('LSobjects.'.$LSobject.'.rdn');
1709 if (!is_array(LSconfig :: get('LSobjects.'.$LSobject.'.attrs.'.$attr))) {
1714 foreach($whoami as $who) {
1715 $nr = LSconfig :: get('LSobjects.'.$LSobject.'.attrs.'.$attr.'.rights.'.$who);
1719 else if($nr == 'r') {
1726 if (($right=='r')||($right=='w')) {
1733 if ( ($r=='r') || ($r=='w') ) {
1740 // Pour un attribut quelconque
1741 $attrs_conf=LSconfig :: get('LSobjects.'.$LSobject.'.attrs');
1742 if (is_array($attrs_conf)) {
1743 if (($right=='r')||($right=='w')) {
1744 foreach($whoami as $who) {
1745 foreach ($attrs_conf as $attr_name => $attr_config) {
1746 if ($attr_config['rights'][$who]==$right) {
1753 foreach($whoami as $who) {
1754 foreach ($attrs_conf as $attr_name => $attr_config) {
1755 if ( ($attr_config['rights'][$who]=='r') || ($attr_config['rights'][$who]=='w') ) {
1766 * Retourne le droit de l'utilisateur à editer à un objet
1768 * @param[in] string $LSobject Le type de l'objet
1769 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1770 * @param[in] string $attr Le nom de l'attribut auquel on test l'accès
1772 * @retval boolean True si l'utilisateur a accès, false sinon
1774 public static function canEdit($LSobject,$dn=NULL,$attr=NULL) {
1775 return self :: canAccess($LSobject,$dn,'w',$attr);
1779 * Retourne le droit de l'utilisateur à supprimer un objet
1781 * @param[in] string $LSobject Le type de l'objet
1782 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1784 * @retval boolean True si l'utilisateur a accès, false sinon
1786 public static function canRemove($LSobject,$dn) {
1787 return self :: canAccess($LSobject,$dn,'w','rdn');
1791 * Retourne le droit de l'utilisateur à créer un objet
1793 * @param[in] string $LSobject Le type de l'objet
1795 * @retval boolean True si l'utilisateur a accès, false sinon
1797 public static function canCreate($LSobject) {
1798 return self :: canAccess($LSobject,NULL,'w','rdn');
1802 * Retourne le droit de l'utilisateur à gérer la relation d'objet
1804 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1805 * @param[in] string $LSobject Le type de l'objet
1806 * @param[in] string $relationName Le nom de la relation avec l'objet
1807 * @param[in] string $right Le type de droit a vérifier ('r' ou 'w')
1809 * @retval boolean True si l'utilisateur a accès, false sinon
1811 public static function relationCanAccess($dn,$LSobject,$relationName,$right=NULL) {
1812 $relConf=LSconfig :: get('LSobjects.'.$LSobject.'.LSrelation.'.$relationName);
1813 if (!is_array($relConf))
1815 $whoami = self :: whoami($dn);
1817 if (($right=='w') || ($right=='r')) {
1819 foreach($whoami as $who) {
1820 $nr = $relConf['rights'][$who];
1824 else if($nr == 'r') {
1836 foreach($whoami as $who) {
1837 if (($relConf['rights'][$who] == 'w') || ($relConf['rights'][$who] == 'r')) {
1846 * Retourne le droit de l'utilisateur à modifier la relation d'objet
1848 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1849 * @param[in] string $LSobject Le type de l'objet
1850 * @param[in] string $relationName Le nom de la relation avec l'objet
1852 * @retval boolean True si l'utilisateur a accès, false sinon
1854 public static function relationCanEdit($dn,$LSobject,$relationName) {
1855 return self :: relationCanAccess($dn,$LSobject,$relationName,'w');
1859 * Ajoute un fichier temporaire
1861 * @author Benjamin Renard <brenard@easter-eggs.com>
1865 public static function addTmpFile($value,$filePath) {
1866 $hash = mhash(MHASH_MD5,$value);
1867 self :: $tmp_file[$filePath] = $hash;
1868 $_SESSION['LSsession']['tmp_file'][$filePath] = $hash;
1872 * Retourne le chemin du fichier temporaire si l'existe
1874 * @author Benjamin Renard <brenard@easter-eggs.com>
1876 * @param[in] $value La valeur du fichier
1880 public static function tmpFileExist($value) {
1881 $hash = mhash(MHASH_MD5,$value);
1882 foreach(self :: $tmp_file as $filePath => $contentHash) {
1883 if ($hash == $contentHash) {
1891 * Retourne le chemin du fichier temporaire
1893 * Retourne le chemin du fichier temporaire qu'il créera à partir de la valeur
1894 * s'il n'existe pas déjà .
1896 * @author Benjamin Renard <brenard@easter-eggs.com>
1898 * @param[in] $value La valeur du fichier
1902 public static function getTmpFile($value) {
1903 $exist = self :: tmpFileExist($value);
1905 $img_path = LS_TMP_DIR .rand().'.tmp';
1906 $fp = fopen($img_path, "w");
1907 fwrite($fp, $value);
1909 self :: addTmpFile($value,$img_path);
1918 * Supprime les fichiers temporaires
1920 * @author Benjamin Renard <brenard@easter-eggs.com>
1924 public static function deleteTmpFile($filePath=NULL) {
1927 unset(self :: $tmp_file[$filePath]);
1928 unset($_SESSION['LSsession']['tmp_file'][$filePath]);
1931 foreach(self :: $tmp_file as $file => $content) {
1934 self :: $tmp_file = array();
1935 $_SESSION['LSsession']['tmp_file'] = array();
1940 * Retourne true si le cache des droits est activé
1942 * @author Benjamin Renard <brenard@easter-eggs.com>
1944 * @retval boolean True si le cache des droits est activé, false sinon.
1946 public static function cacheLSprofiles() {
1947 return ( (LSconfig :: get('cacheLSprofiles')) || (self :: $ldapServer['cacheLSprofiles']) );
1951 * Retourne true si le cache des subDn est activé
1953 * @author Benjamin Renard <brenard@easter-eggs.com>
1955 * @retval boolean True si le cache des subDn est activé, false sinon.
1957 public static function cacheSudDn() {
1958 return ( (LSconfig :: get('cacheSubDn')) || (self :: $ldapServer['cacheSubDn']));
1962 * Retourne true si le cache des recherches est activé
1964 * @author Benjamin Renard <brenard@easter-eggs.com>
1966 * @retval boolean True si le cache des recherches est activé, false sinon.
1968 public static function cacheSearch() {
1969 return ( (LSconfig :: get('cacheSearch')) || (self :: $ldapServer['cacheSearch']));
1973 * Retourne le label des niveaux pour le serveur ldap courant
1975 * @author Benjamin Renard <brenard@easter-eggs.com>
1977 * @retval string Le label des niveaux pour le serveur ldap dourant
1979 public static function getSubDnLabel() {
1980 return (self :: $ldapServer['subDnLabel']!='')?__(self :: $ldapServer['subDnLabel']):_('Level');
1984 * Retourne le nom du subDn
1986 * @param[in] $subDn string subDn
1988 * @retval string Le nom du subDn ou '' sinon
1990 public static function getSubDnName($subDn=false) {
1992 $subDn = self :: $topDn;
1994 if (self :: getSubDnLdapServer()) {
1995 if (isset(self :: $_subDnLdapServer[self :: $ldapServerId][$subDn])) {
1996 return self :: $_subDnLdapServer[self :: $ldapServerId][$subDn];
2003 * L'objet est t-il utilisé pour listé les subDnS
2005 * @param[in] $type string Le type d'objet
2007 * @retval boolean true si le type d'objet est un subDnObject, false sinon
2009 public static function isSubDnLSobject($type) {
2011 if (is_array(self :: $ldapServer['subDn']['LSobject'])) {
2012 foreach(self :: $ldapServer['subDn']['LSobject'] as $key => $value) {
2022 * Indique si un type d'objet est dans le menu courant
2024 * @retval boolean true si le type d'objet est dans le menu, false sinon
2026 public static function in_menu($LSobject,$topDn=NULL) {
2028 $topDn=self :: $topDn;
2030 return isset(self :: $LSaccess[$topDn][$LSobject]);
2034 * Indique si le serveur LDAP courant a des subDn
2036 * @retval boolean true si le serveur LDAP courant a des subDn, false sinon
2038 public static function haveSubDn() {
2039 return (is_array(self :: $ldapServer['subDn']));
2043 * Ajoute une information à afficher
2045 * @param[in] $msg string Le message à afficher
2049 public static function addInfo($msg) {
2050 $_SESSION['LSsession_infos'][]=$msg;
2054 * Redirection de l'utilisateur vers une autre URL
2056 * @param[in] $url string L'URL
2057 * @param[in] $exit boolean Si true, l'execution script s'arrête après la redirection
2061 public static function redirect($url,$exit=true) {
2062 $GLOBALS['Smarty'] -> assign('url',$url);
2063 $GLOBALS['Smarty'] -> display('redirect.tpl');
2070 * Retourne l'adresse mail d'emission configurée pour le serveur courant
2072 * @retval string Adresse mail d'emission
2074 public static function getEmailSender() {
2075 return self :: $ldapServer['emailSender'];
2079 * Ajout d'une information d'aide
2081 * @param[in] $group string Le nom du groupe d'infos dans lequels ajouter
2083 * @param[in] $infos array Tableau array(name => value) des infos
2087 public static function addHelpInfos($group,$infos) {
2088 if (is_array($infos)) {
2089 if (is_array(self :: $_JSconfigParams['helpInfos'][$group])) {
2090 self :: $_JSconfigParams['helpInfos'][$group] = array_merge(self :: $_JSconfigParams['helpInfos'][$group],$infos);
2093 self :: $_JSconfigParams['helpInfos'][$group] = $infos;
2099 * Défini les codes erreur relative à la classe LSsession
2103 private static function defineLSerrors() {
2107 LSerror :: defineError('LSsession_01',
2108 _("LSsession : The constant %{const} is not defined.")
2110 LSerror :: defineError('LSsession_02',
2111 _("LSsession : The %{addon} support is uncertain. Verify system compatibility and the add-on configuration.")
2113 LSerror :: defineError('LSsession_03',
2114 _("LSsession : LDAP server's configuration data are invalid. Can't connect.")
2116 LSerror :: defineError('LSsession_04',
2117 _("LSsession : Failed to load LSobject type %{type} : unknon type.")
2119 LSerror :: defineError('LSsession_05',
2120 _("LSsession : Failed to load LSclass %{class}.")
2122 LSerror :: defineError('LSsession_06',
2123 _("LSsession : Login or password incorrect.")
2125 LSerror :: defineError('LSsession_07',
2126 _("LSsession : Impossible to identify you : Duplication of identities.")
2128 LSerror :: defineError('LSsession_08',
2129 _("LSsession : Can't load class of authentification (%{class}).")
2131 LSerror :: defineError('LSsession_09',
2132 _("LSsession : Can't connect to LDAP server.")
2134 LSerror :: defineError('LSsession_10',
2135 _("LSsession : Impossible to authenticate you.")
2137 LSerror :: defineError('LSsession_11',
2138 _("LSsession : Your are not authorized to do this action.")
2140 LSerror :: defineError('LSsession_12',
2141 _("LSsession : Some informations are missing to display this page.")
2143 // 13 -> 16 : not yet used
2144 LSerror :: defineError('LSsession_17',
2145 _("LSsession : Error during creation of list of levels. Contact administrators. (Code : %{code})")
2147 LSerror :: defineError('LSsession_18',
2148 _("LSsession : The password recovery is disabled for this LDAP server.")
2150 LSerror :: defineError('LSsession_19',
2151 _("LSsession : Some informations are missing to recover your password. Contact administrators.")
2153 LSerror :: defineError('LSsession_20',
2154 _("LSsession : Error during password recovery. Contact administrators.(Step : %{step})")
2156 // 21 : not yet used
2157 LSerror :: defineError('LSsession_22',
2158 _("LSsession : problem during initialisation.")
2163 * Ajax method when change ldapserver on login form
2165 * @param[in] $data array The return data address
2169 public static function ajax_onLdapServerChangedLogin(&$data) {
2170 if ( isset($_REQUEST['server']) ) {
2171 self :: setLdapServer($_REQUEST['server']);
2173 if ( self :: LSldapConnect() ) {
2175 if (isset($_SESSION['LSsession_topDn'])) {
2176 $sel = $_SESSION['LSsession_topDn'];
2181 $list = self :: getSubDnLdapServerOptions($sel);
2182 if (is_string($list)) {
2183 $data['list_topDn'] = "<select name='LSsession_topDn' id='LSsession_topDn'>".$list."</select>";
2184 $data['subDnLabel'] = self :: getSubDnLabel();
2187 $data['recoverPassword'] = isset(self :: $ldapServer['recoverPassword']);
2192 * Ajax method when change ldapserver on recoverPassword form
2194 * @param[in] $data array The return data address
2198 public static function ajax_onLdapServerChangedRecoverPassword(&$data) {
2199 if ( isset($_REQUEST['server']) ) {
2200 self :: setLdapServer($_REQUEST['server']);
2201 $data=array('recoverPassword' => isset(self :: $ldapServer['recoverPassword']));