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 return LStemplate :: start(
138 'smarty_path' => LSconfig :: get('Smarty'),
139 'template_dir' => LS_TEMPLATES_DIR,
140 'image_dir' => LS_IMAGES_DIR,
141 'css_dir' => LS_CSS_DIR,
142 'compile_dir' => LS_TMP_DIR,
144 'debug_smarty' => (isset($_REQUEST['LStemplate_debug'])),
152 * Retourne le topDn de la session
154 * @author Benjamin Renard <brenard@easter-eggs.com>
156 * @retval string le topDn de la session
158 public static function getTopDn() {
159 if (!is_null(self :: $topDn)) {
160 return self :: $topDn;
163 return self :: getRootDn();
168 * Retourne le rootDn de la session
170 * @author Benjamin Renard <brenard@easter-eggs.com>
172 * @retval string le rootDn de la session
174 public static function getRootDn() {
175 return self :: $ldapServer['ldap_config']['basedn'];
179 * Initialisation de la gestion des erreurs
181 * Création de l'objet LSerror
183 * @author Benjamin Renard <brenard@easter-eggs.com
185 * @retval boolean true si l'initialisation a réussi, false sinon.
187 private static function startLSerror() {
188 if(!self :: loadLSclass('LSerror')) {
191 self :: defineLSerrors();
196 * Chargement d'une classe d'LdapSaisie
198 * @param[in] $class Nom de la classe à charger (Exemple : LSpeople)
199 * @param[in] $type (Optionnel) Type de classe à charger (Exemple : LSobjects)
201 * @author Benjamin Renard <brenard@easter-eggs.com
203 * @retval boolean true si le chargement a réussi, false sinon.
205 public static function loadLSclass($class,$type='') {
206 if (class_exists($class))
210 return self :: includeFile(LS_CLASS_DIR .'class.'.$type.$class.'.php');
214 * Chargement d'un object LdapSaisie
216 * @param[in] $object Nom de l'objet à charger
218 * @retval boolean true si le chargement a réussi, false sinon.
220 public static function loadLSobject($object) {
221 if(class_exists($object)) {
225 self :: loadLSclass('LSldapObject');
226 if (!self :: loadLSclass($object,'LSobjects')) {
229 if (!self :: includeFile( LS_OBJECTS_DIR . 'config.LSobjects.'.$object.'.php' )) {
233 if (!LSconfig :: set("LSobjects.$object",$GLOBALS['LSobjects'][$object])) {
236 else if (isset($GLOBALS['LSobjects'][$object]['LSaddons'])){
237 if (is_array($GLOBALS['LSobjects'][$object]['LSaddons'])) {
238 foreach ($GLOBALS['LSobjects'][$object]['LSaddons'] as $addon) {
239 if (!self :: loadLSaddon($addon)) {
245 if (!self :: loadLSaddon($GLOBALS['LSobjects'][$object]['LSaddons'])) {
252 LSerror :: addErrorCode('LSsession_04',$object);
259 * Chargement d'un addons d'LdapSaisie
261 * @param[in] $addon Nom de l'addon à charger (Exemple : samba)
263 * @author Benjamin Renard <brenard@easter-eggs.com
265 * @retval boolean true si le chargement a réussi, false sinon.
267 public static function loadLSaddon($addon) {
268 if(self :: includeFile(LS_ADDONS_DIR .'LSaddons.'.$addon.'.php')) {
269 self :: includeFile(LS_CONF_DIR."LSaddons/config.LSaddons.".$addon.".php");
270 if (!call_user_func('LSaddon_'. $addon .'_support')) {
271 LSerror :: addErrorCode('LSsession_02',$addon);
280 * Chargement d'une classe d'authentification d'LdapSaisie
282 * @author Benjamin Renard <brenard@easter-eggs.com
284 * @retval boolean true si le chargement a reussi, false sinon.
286 public static function loadLSauth() {
287 if (self :: loadLSclass('LSauth')) {
291 LSerror :: addErrorCode('LSsession_05','LSauth');
297 * Chargement des addons LdapSaisie
299 * Chargement des LSaddons contenue dans la variable
300 * $GLOBALS['LSaddons']['loads']
302 * @retval boolean true si le chargement a réussi, false sinon.
304 public static function loadLSaddons() {
305 $conf=LSconfig :: get('LSaddons.loads');
306 if(!is_array($conf)) {
307 LSerror :: addErrorCode('LSsession_01',"LSaddons['loads']");
311 foreach ($conf as $addon) {
312 self :: loadLSaddon($addon);
322 public static function setLocale() {
323 if (isset($_REQUEST['lang'])) {
324 $lang = $_REQUEST['lang'];
326 elseif (isset($_SESSION['LSlang'])) {
327 $lang = $_SESSION['LSlang'];
329 elseif (isset(self :: $ldapServer['lang'])) {
330 $lang = self :: $ldapServer['lang'];
333 $lang = LSconfig :: get('lang');
336 if (isset($_REQUEST['encoding'])) {
337 $encoding = $_REQUEST['encoding'];
339 elseif (isset($_SESSION['LSencoding'])) {
340 $encoding = $_SESSION['LSencoding'];
342 elseif (isset(self :: $ldapServer['encoding'])) {
343 $encoding = self :: $ldapServer['encoding'];
346 $encoding = LSconfig :: get('encoding');
349 $_SESSION['LSlang']=$lang;
351 $_SESSION['LSencoding']=$encoding;
352 self :: $encoding=$encoding;
355 if (self :: localeExist($lang,$encoding)) {
357 $lang.='.'.$encoding;
359 setlocale(LC_ALL, $lang);
360 bindtextdomain(LS_TEXT_DOMAIN, LS_I18N_DIR);
361 textdomain(LS_TEXT_DOMAIN);
363 self :: includeFile(LS_I18N_DIR.'/'.$lang.'/lang.php');
365 foreach (listFiles(LS_LOCAL_DIR.'/'.LS_I18N_DIR.'/'.$lang,'/^lang.+\.php$/') as $file) {
366 include(LS_LOCAL_DIR.'/'.LS_I18N_DIR."/$lang/$file");
370 if ($encoding && $lang) {
371 $lang.='.'.$encoding;
373 LSdebug('La locale "'.$lang.'" n\'existe pas, utilisation de la locale par défaut.');
378 * Retourne la liste des langues disponibles
380 * @retval array Tableau/Liste des langues disponibles
382 public static function getLangList() {
383 $list=array('en_US');
384 if (self :: $encoding) {
385 $regex = '^([a-zA-Z_]*)\.'.self :: $encoding.'$';
388 $regex = '^([a-zA-Z_]*)$';
390 if ($handle = opendir(LS_I18N_DIR)) {
391 while (false !== ($file = readdir($handle))) {
392 if(is_dir(LS_I18N_DIR.'/'.$file)) {
393 if (ereg($regex,$file,$regs)) {
394 if (!in_array($regs[1],$list)) {
405 * Retourne la langue courante de la session
407 * @param[in] boolean Si true, le code langue retourné sera court
409 * @retval string La langue de la session
411 public static function getLang($short=false) {
413 return strtolower(self :: $lang[0].self :: $lang[1]);
415 return self :: $lang;
419 * Vérifie si une locale est disponible
421 * @param[in] $lang string La langue (Ex : fr_FR)
422 * @param[in] $encoding string L'encodage de caractère (Ex : UTF8)
424 * @retval boolean True si la locale est disponible, False sinon
426 public static function localeExist($lang,$encoding) {
427 if ( !$lang && !$encoding ) {
430 $locale=$lang.(($encoding)?'.'.$encoding:'');
431 if ($locale=='en_US.UTF8') {
434 return (is_dir(LS_I18N_DIR.'/'.$locale));
438 * Initialisation LdapSaisie
440 * @retval boolean True si l'initialisation à réussi, false sinon.
442 public static function initialize() {
443 if (!self :: startLSconfig()) {
447 self :: startLSerror();
448 self :: startLStemplate();
454 self :: loadLSaddons();
455 self :: loadLSauth();
460 * Initialisation de la session LdapSaisie
462 * Initialisation d'une LSsession :
463 * - Authentification et activation du mécanisme de session de LdapSaisie
464 * - ou Chargement des paramètres de la session à partir de la variable
465 * $_SESSION['LSsession'].
466 * - ou Destruction de la session en cas de $_GET['LSsession_logout'].
468 * @retval boolean True si l'initialisation à réussi (utilisateur authentifié), false sinon.
470 public static function startLSsession() {
471 if (!self :: initialize()) {
475 if(isset($_SESSION['LSsession']['dn']) && !isset($_GET['LSsession_recoverPassword'])) {
476 LSdebug('LSsession : Session existente');
477 // --------------------- Session existante --------------------- //
478 self :: $topDn = $_SESSION['LSsession']['topDn'];
479 self :: $dn = $_SESSION['LSsession']['dn'];
480 self :: $rdn = $_SESSION['LSsession']['rdn'];
481 self :: $ldapServerId = $_SESSION['LSsession']['ldapServerId'];
482 self :: $tmp_file = $_SESSION['LSsession']['tmp_file'];
484 if ( self :: cacheLSprofiles() && !isset($_REQUEST['LSsession_refresh']) ) {
485 self :: setLdapServer(self :: $ldapServerId);
486 if (!LSauth :: start()) {
487 LSdebug("LSsession : can't start LSauth -> stop");
490 self :: $LSprofiles = $_SESSION['LSsession']['LSprofiles'];
491 self :: $LSaccess = $_SESSION['LSsession']['LSaccess'];
492 if (!self :: LSldapConnect())
496 self :: setLdapServer(self :: $ldapServerId);
497 if (!LSauth :: start()) {
498 LSdebug("LSsession : can't start LSauth -> stop");
501 if (!self :: LSldapConnect())
503 self :: loadLSprofiles();
506 if ( self :: cacheSudDn() && (!isset($_REQUEST['LSsession_refresh'])) ) {
507 self :: $_subDnLdapServer = ((isset($_SESSION['LSsession_subDnLdapServer']))?$_SESSION['LSsession_subDnLdapServer']:NULL);
510 if (!self :: loadLSobject(self :: $ldapServer['authObjectType'])) {
514 if (isset($_GET['LSsession_logout'])) {
518 if (is_array($_SESSION['LSsession']['tmp_file'])) {
519 self :: $tmp_file = $_SESSION['LSsession']['tmp_file'];
521 self :: deleteTmpFile();
522 unset($_SESSION['LSsession']);
524 self :: redirect('index.php');
528 if ( !self :: cacheLSprofiles() || isset($_REQUEST['LSsession_refresh']) ) {
529 self :: loadLSaccess();
532 LStemplate :: assign('LSsession_username',self :: getLSuserObject() -> getDisplayName());
534 if (isset ($_POST['LSsession_topDn']) && $_POST['LSsession_topDn']) {
535 if (self :: validSubDnLdapServer($_POST['LSsession_topDn'])) {
536 self :: $topDn = $_POST['LSsession_topDn'];
537 $_SESSION['LSsession']['topDn'] = $_POST['LSsession_topDn'];
545 // --------------------- Session inexistante --------------------- //
546 if (isset($_GET['LSsession_recoverPassword'])) {
549 // Session inexistante
550 if (isset($_POST['LSsession_ldapserver'])) {
551 self :: setLdapServer($_POST['LSsession_ldapserver']);
554 self :: setLdapServer(0);
557 // Connexion au serveur LDAP
558 if (self :: LSldapConnect()) {
561 if (isset($_POST['LSsession_topDn']) && $_POST['LSsession_topDn'] != '' ){
562 self :: $topDn = $_POST['LSsession_topDn'];
565 self :: $topDn = self :: $ldapServer['ldap_config']['basedn'];
567 $_SESSION['LSsession_topDn']=self :: $topDn;
569 if (!LSauth :: start()) {
570 LSdebug("LSsession : can't start LSauth -> stop");
574 if (isset($_GET['LSsession_recoverPassword'])) {
575 $recoveryPasswordInfos = self :: recoverPasswd(
576 $_REQUEST['LSsession_user'],
577 $_GET['recoveryHash']
581 $LSuserObject = LSauth :: forceAuthentication();
583 // Authentication successful
584 self :: $LSuserObject = $LSuserObject;
585 self :: $dn = $LSuserObject->getValue('dn');
586 self :: $rdn = $LSuserObject->getValue('rdn');
587 self :: loadLSprofiles();
588 self :: loadLSaccess();
589 LStemplate :: assign('LSsession_username',self :: getLSuserObject() -> getDisplayName());
590 $_SESSION['LSsession']=self :: getContextInfos();
596 LSerror :: addErrorCode('LSsession_09');
599 if (self :: $ldapServerId) {
600 LStemplate :: assign('ldapServerId',self :: $ldapServerId);
602 LStemplate :: assign('topDn',self :: $topDn);
603 if (isset($_GET['LSsession_recoverPassword'])) {
604 self :: displayRecoverPasswordForm($recoveryPasswordInfos);
606 elseif(LSauth :: displayLoginForm()) {
607 self :: displayLoginForm();
610 self :: setTemplate('blank.tpl');
611 LSerror :: addErrorCode('LSsession_10');
618 * Do recover password
620 * @param[in] $username string The submited username
621 * @param[in] $recoveryHash string The submited recoveryHash
623 * @retval array The recoveryPassword infos for template
625 private static function recoverPasswd($username,$recoveryHash) {
626 $recoveryPasswordInfos=array();
627 if ( self :: loadLSobject(self :: $ldapServer['authObjectType']) ) {
628 $authobject = new self :: $ldapServer['authObjectType']();
629 if (!empty($recoveryHash)) {
630 $filter=Net_LDAP2_Filter::create(
631 self :: $ldapServer['recoverPassword']['recoveryHashAttr'],
635 $result = $authobject -> listObjects($filter,self :: $topDn);
637 elseif (!empty($username)) {
638 $result = $authobject -> searchObject(
641 self :: $ldapServer['authObjectFilter']
645 return $recoveryPasswordInfos;
648 $nbresult=count($result);
651 LSdebug('hash/username incorrect');
652 LSerror :: addErrorCode('LSsession_06');
654 elseif ($nbresult>1) {
655 LSerror :: addErrorCode('LSsession_07');
658 $rdn = $result[0] -> getValue('rdn');
660 LSdebug('Recover : Id trouvé : '.$username);
661 if (self :: $ldapServer['recoverPassword']) {
662 if (self :: loadLSaddon('mail')) {
663 LSdebug('Récupération active');
665 $emailAddress = $user -> getValue(self :: $ldapServer['recoverPassword']['mailAttr']);
666 $emailAddress = $emailAddress[0];
668 if (checkEmail($emailAddress)) {
669 LSdebug('Email : '.$emailAddress);
670 self :: $dn = $user -> getDn();
672 // 1ère étape : envoie du recoveryHash
673 if (empty($recoveryHash)) {
674 $hash=self :: recoverPasswdFirstStep($user);
676 if (self :: recoverPasswdSendMail($emailAddress,1,$hash)) {
677 // Mail a bien été envoyé
678 $recoveryPasswordInfos['recoveryHashMail']=$emailAddress;
682 // 2nd étape : génération du mot de passe + envoie par mail
684 $pwd=self :: recoverPasswdSecondStep($user);
686 if (self :: recoverPasswdSendMail($emailAddress,2,$pwd)){
687 // Mail a bien été envoyé
688 $recoveryPasswordInfos['newPasswordMail']=$emailAddress;
694 LSerror :: addErrorCode('LSsession_19');
699 LSerror :: addErrorCode('LSsession_18');
703 return $recoveryPasswordInfos;
707 * Send recover password mail
709 * @param[in] $mail string The user's mail
710 * @param[in] $step integer The step
711 * @param[in] $info string The info for formatted message
713 * @retval boolean True on success or False
715 private static function recoverPasswdSendMail($mail,$step,$info) {
718 if (self :: $ldapServer['recoverPassword']['recoveryEmailSender']) {
719 $sendParams['From']=self :: $ldapServer['recoverPassword']['recoveryEmailSender'];
723 if ($_SERVER['HTTPS']=='on') {
724 $recovery_url='https://';
727 $recovery_url='http://';
729 $recovery_url .= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'&recoveryHash='.$info;
731 $subject = self :: $ldapServer['recoverPassword']['recoveryHashMail']['subject'];
733 self :: $ldapServer['recoverPassword']['recoveryHashMail']['msg'],
738 $subject = self :: $ldapServer['recoverPassword']['newPasswordMail']['subject'];
740 self :: $ldapServer['recoverPassword']['newPasswordMail']['msg'],
745 if (!sendMail($mail,$subject,$msg,$sendParams)) {
746 LSdebug("Problème durant l'envoie du mail");
747 LSerror :: addErrorCode('LSsession_20',4);
755 * Do first step of recovering password
757 * @param[in] $user LSldapObject The LSldapObject of the user
759 * @retval string|False The recory hash on success or False
761 private static function recoverPasswdFirstStep($user) {
763 $rdn=$user -> getValue('rdn');
765 $recovery_hash = md5($rdn . strval(time()) . strval(rand()));
767 $lostPasswdForm = $user -> getForm('lostPassword');
768 $lostPasswdForm -> setPostData(
770 self :: $ldapServer['recoverPassword']['recoveryHashAttr'] => $recovery_hash
775 if($lostPasswdForm -> validate()) {
776 if ($user -> updateData('lostPassword')) {
777 // recoveryHash de l'utilisateur mis à jour
778 return $recovery_hash;
781 // Erreur durant la mise à jour de l'objet
782 LSdebug("Erreur durant la mise à jour de l'objet");
783 LSerror :: addErrorCode('LSsession_20',6);
787 // Erreur durant la validation du formulaire de modification de perte de password
788 LSdebug("Erreur durant la validation du formulaire de modification de perte de password");
789 LSerror :: addErrorCode('LSsession_20',5);
795 * Do second step of recovering password
797 * @param[in] $user LSldapObject The LSldapObject of the user
799 * @retval string|False The new password on success or False
801 private static function recoverPasswdSecondStep($user) {
802 $attr=$user -> attrs[self :: $ldapServer['authObjectTypeAttrPwd']];
803 if ($attr instanceof LSattribute) {
804 $mdp = generatePassword(
805 $attr -> config['html_options']['chars'],
806 $attr -> config['html_options']['lenght']
808 LSdebug('Nvx mpd : '.$mdp);
809 $lostPasswdForm = $user -> getForm('lostPassword');
810 $lostPasswdForm -> setPostData(
812 self :: $ldapServer['recoverPassword']['recoveryHashAttr'] => array(''),
813 self :: $ldapServer['authObjectTypeAttrPwd'] => array($mdp)
817 if($lostPasswdForm -> validate()) {
818 if ($user -> updateData('lostPassword')) {
822 // Erreur durant la mise à jour de l'objet
823 LSdebug("Erreur durant la mise à jour de l'objet");
824 LSerror :: addErrorCode('LSsession_20',3);
828 // Erreur durant la validation du formulaire de modification de perte de password
829 LSdebug("Erreur durant la validation du formulaire de modification de perte de password");
830 LSerror :: addErrorCode('LSsession_20',2);
834 // l'attribut password n'existe pas
835 LSdebug("L'attribut password n'existe pas");
836 LSerror :: addErrorCode('LSsession_20',1);
842 * Retourne les informations du contexte
844 * @author Benjamin Renard <brenard@easter-eggs.com
846 * @retval array Tableau associatif des informations du contexte
848 private static function getContextInfos() {
850 'tmp_file' => self :: $tmp_file,
851 'topDn' => self :: $topDn,
853 'rdn' => self :: $rdn,
854 'ldapServerId' => self :: $ldapServerId,
855 'ldapServer' => self :: $ldapServer,
856 'LSprofiles' => self :: $LSprofiles,
857 'LSaccess' => self :: $LSaccess
862 * Retourne l'objet de l'utilisateur connecté
864 * @author Benjamin Renard <brenard@easter-eggs.com
866 * @retval mixed L'objet de l'utilisateur connecté ou false si il n'a pas put
869 public static function getLSuserObject($dn=null) {
873 if (!self :: $LSuserObject) {
874 if (self :: loadLSobject(self :: $ldapServer['authObjectType'])) {
875 self :: $LSuserObject = new self :: $ldapServer['authObjectType']();
876 self :: $LSuserObject -> loadData(self :: $dn);
882 return self :: $LSuserObject;
886 * Retourne le DN de l'utilisateur connecté
888 * @author Benjamin Renard <brenard@easter-eggs.com
890 * @retval string Le DN de l'utilisateur connecté
892 public static function getLSuserObjectDn() {
897 * Modifie l'utilisateur connecté à la volé
899 * @param[in] $object Mixed L'objet Ldap du nouvel utilisateur
900 * le type doit correspondre à
901 * self :: $ldapServer['authObjectType']
903 * @retval boolean True en cas de succès, false sinon
905 public static function changeAuthUser($object) {
906 if ($object instanceof self :: $ldapServer['authObjectType']) {
907 self :: $dn = $object -> getDn();
908 $rdn = $object -> getValue('rdn');
913 self :: $LSuserObject = $object;
915 if(self :: loadLSprofiles()) {
916 self :: loadLSaccess();
917 $_SESSION['LSsession']=self :: getContextInfos();
925 * Définition du serveur Ldap de la session
927 * Définition du serveur Ldap de la session à partir de son ID dans
928 * le tableau LSconfig :: get('ldap_servers').
930 * @param[in] integer Index du serveur Ldap
932 * @retval boolean True sinon false.
934 public static function setLdapServer($id) {
935 $conf = LSconfig :: get("ldap_servers.$id");
936 if ( is_array($conf) ) {
937 self :: $ldapServerId = $id;
938 self :: $ldapServer = $conf;
948 * Connexion au serveur Ldap
950 * @retval boolean True sinon false.
952 public static function LSldapConnect() {
953 if (self :: $ldapServer) {
954 self :: includeFile(LSconfig :: get('NetLDAP2'));
955 if (!self :: loadLSclass('LSldap')) {
958 LSldap :: connect(self :: $ldapServer['ldap_config']);
959 if (LSldap :: isConnected()) {
967 LSerror :: addErrorCode('LSsession_03');
973 * Use this function to know if subDn is enabled for the curent LdapServer
977 public static function subDnIsEnabled() {
978 if (!isset(self :: $ldapServer['subDn'])) {
981 if ( !is_array(self :: $ldapServer['subDn']) ) {
988 * Retourne les sous-dns du serveur Ldap courant
990 * @retval mixed Tableau des subDn, false si une erreur est survenue.
992 public static function getSubDnLdapServer($login=false) {
994 if (self :: cacheSudDn() && isset(self :: $_subDnLdapServer[self :: $ldapServerId][$login])) {
995 return self :: $_subDnLdapServer[self :: $ldapServerId][$login];
997 if (!self::subDnIsEnabled()) {
1001 foreach(self :: $ldapServer['subDn'] as $subDn_name => $subDn_config) {
1002 if ($login && isset($subDn_config['nologin']) && $subDn_config['nologin']) continue;
1003 if ($subDn_name == 'LSobject') {
1004 if (is_array($subDn_config)) {
1005 foreach($subDn_config as $LSobject_name => $LSoject_config) {
1006 if (isset($LSoject_config['basedn']) && !empty($LSoject_config['basedn'])) {
1007 $basedn = $LSoject_config['basedn'];
1010 $basedn = self::getRootDn();
1012 if (isset($LSoject_config['displayName']) && !empty($LSoject_config['displayName'])) {
1013 $displayName = $LSoject_config['displayName'];
1016 $displayName = NULL;
1018 if( self :: loadLSobject($LSobject_name) ) {
1019 if ($subdnobject = new $LSobject_name()) {
1020 $tbl_return = $subdnobject -> getSelectArray(NULL,$basedn,$displayName);
1021 if (is_array($tbl_return)) {
1022 $return=array_merge($return,$tbl_return);
1025 LSerror :: addErrorCode('LSsession_17',3);
1029 LSerror :: addErrorCode('LSsession_17',2);
1035 LSerror :: addErrorCode('LSsession_17',1);
1039 if ((isCompatibleDNs($subDn_config['dn'],self :: $ldapServer['ldap_config']['basedn']))&&($subDn_config['dn']!="")) {
1040 $return[$subDn_config['dn']] = __($subDn_name);
1044 if (self :: cacheSudDn()) {
1045 self :: $_subDnLdapServer[self :: $ldapServerId][$login]=$return;
1046 $_SESSION['LSsession_subDnLdapServer'] = self :: $_subDnLdapServer;
1052 * Retourne la liste de subDn du serveur Ldap utilise
1053 * trié par la profondeur dans l'arboressence (ordre décroissant)
1055 * @return array() Tableau des subDn trié
1057 public static function getSortSubDnLdapServer($login=false) {
1058 $subDnLdapServer = self :: getSubDnLdapServer($login);
1059 if (!$subDnLdapServer) {
1062 uksort($subDnLdapServer,"compareDn");
1063 return $subDnLdapServer;
1067 * Retourne les options d'une liste déroulante pour le choix du topDn
1068 * de connexion au serveur Ldap
1070 * Liste les subdn (self :: $ldapServer['subDn'])
1072 * @retval string Les options (<option>) pour la sélection du topDn.
1074 public static function getSubDnLdapServerOptions($selected=NULL,$login=false) {
1075 $list = self :: getSubDnLdapServer($login);
1079 foreach($list as $dn => $txt) {
1080 if ($selected && ($selected==$dn)) {
1081 $selected_txt = ' selected';
1086 $display.="<option value=\"".$dn."\"$selected_txt>".$txt."</option>\n";
1094 * Vérifie qu'un subDn est déclaré
1096 * @param[in] string Un subDn
1098 * @retval boolean True si le subDn existe, False sinon
1100 public static function validSubDnLdapServer($subDn) {
1101 $listTopDn = self :: getSubDnLdapServer();
1102 if(is_array($listTopDn)) {
1103 foreach($listTopDn as $dn => $txt) {
1113 * Test un couple LSobject/pwd
1115 * Test un bind sur le serveur avec le dn de l'objet et le mot de passe fourni.
1117 * @param[in] LSobject L'object "user" pour l'authentification
1118 * @param[in] string Le mot de passe à tester
1120 * @retval boolean True si l'authentification à réussi, false sinon.
1122 public static function checkUserPwd($object,$pwd) {
1123 return LSldap :: checkBind($object -> getValue('dn'),$pwd);
1127 * Affiche le formulaire de login
1129 * Défini les informations pour le template Smarty du formulaire de login.
1133 public static function displayLoginForm() {
1134 LStemplate :: assign('pagetitle',_('Connection'));
1135 if (isset($_GET['LSsession_logout'])) {
1136 LStemplate :: assign('loginform_action','index.php');
1139 LStemplate :: assign('loginform_action',$_SERVER['REQUEST_URI']);
1141 if (count(LSconfig :: get('ldap_servers'))==1) {
1142 LStemplate :: assign('loginform_ldapserver_style','style="display: none"');
1144 LStemplate :: assign('loginform_label_ldapserver',_('LDAP server'));
1145 $ldapservers_name=array();
1146 $ldapservers_index=array();
1147 foreach(LSconfig :: get('ldap_servers') as $id => $infos) {
1148 $ldapservers_index[]=$id;
1149 $ldapservers_name[]=__($infos['name']);
1151 LStemplate :: assign('loginform_ldapservers_name',$ldapservers_name);
1152 LStemplate :: assign('loginform_ldapservers_index',$ldapservers_index);
1154 LStemplate :: assign('loginform_label_level',_('Level'));
1155 LStemplate :: assign('loginform_label_user',_('Identifier'));
1156 LStemplate :: assign('loginform_label_pwd',_('Password'));
1157 LStemplate :: assign('loginform_label_submit',_('Connect'));
1158 LStemplate :: assign('loginform_label_recoverPassword',_('Forgot your password ?'));
1160 self :: setTemplate('login.tpl');
1161 self :: addJSscript('LSsession_login.js');
1165 * Affiche le formulaire de récupération de mot de passe
1167 * Défini les informations pour le template Smarty du formulaire de
1168 * récupération de mot de passe
1170 * @param[in] $infos array() Information sur le status du processus de
1171 * recouvrement de mot de passe
1175 public static function displayRecoverPasswordForm($recoveryPasswordInfos) {
1176 LStemplate :: assign('pagetitle',_('Recovery of your credentials'));
1177 LStemplate :: assign('recoverpasswordform_action','index.php?LSsession_recoverPassword');
1179 if (count(LSconfig :: get('ldap_servers'))==1) {
1180 LStemplate :: assign('recoverpasswordform_ldapserver_style','style="display: none"');
1183 LStemplate :: assign('recoverpasswordform_label_ldapserver',_('LDAP server'));
1184 $ldapservers_name=array();
1185 $ldapservers_index=array();
1186 foreach(LSconfig :: get('ldap_servers') as $id => $infos) {
1187 $ldapservers_index[]=$id;
1188 $ldapservers_name[]=$infos['name'];
1190 LStemplate :: assign('recoverpasswordform_ldapservers_name',$ldapservers_name);
1191 LStemplate :: assign('recoverpasswordform_ldapservers_index',$ldapservers_index);
1193 LStemplate :: assign('recoverpasswordform_label_user',_('Identifier'));
1194 LStemplate :: assign('recoverpasswordform_label_submit',_('Validate'));
1195 LStemplate :: assign('recoverpasswordform_label_back',_('Back'));
1197 $recoverpassword_msg = _('Please fill the identifier field to proceed recovery procedure');
1199 if (isset($recoveryPasswordInfos['recoveryHashMail'])) {
1200 $recoverpassword_msg = getFData(
1201 _("An email has been sent to %{mail}. " .
1202 "Please follow the instructions on it."),
1203 $recoveryPasswordInfos['recoveryHashMail']
1207 if (isset($recoveryPasswordInfos['newPasswordMail'])) {
1208 $recoverpassword_msg = getFData(
1209 _("Your new password has been sent to %{mail}. "),
1210 $recoveryPasswordInfos['newPasswordMail']
1214 LStemplate :: assign('recoverpassword_msg',$recoverpassword_msg);
1216 self :: setTemplate('recoverpassword.tpl');
1217 self :: addJSscript('LSsession_recoverPassword.js');
1221 * Défini le template Smarty à utiliser
1223 * Remarque : les fichiers de templates doivent se trouver dans le dossier
1226 * @param[in] string Le nom du fichier de template
1230 public static function setTemplate($template) {
1231 self :: $template = $template;
1235 * Ajoute un script JS au chargement de la page
1237 * Remarque : les scripts doivents être dans le dossier LS_JS_DIR.
1239 * @param[in] $script Le nom du fichier de script à charger.
1243 public static function addJSscript($file,$path=NULL) {
1248 self :: $JSscripts[$path.$file]=$script;
1252 * Ajouter un paramètre de configuration Javascript
1254 * @param[in] $name string Nom de la variable de configuration
1255 * @param[in] $val mixed Valeur de la variable de configuration
1259 public static function addJSconfigParam($name,$val) {
1260 self :: $_JSconfigParams[$name]=$val;
1264 * Ajoute une feuille de style au chargement de la page
1266 * @param[in] $script Le nom du fichier css à charger.
1270 public static function addCssFile($file,$path=NULL) {
1272 $file = $path.$file;
1275 $file = LStemplate :: getCSSPath($file);
1277 self :: $CssFiles[$file]=$file;
1281 * Affiche le template Smarty
1283 * Charge les dépendances et affiche le template Smarty
1287 public static function displayTemplate() {
1290 foreach ($GLOBALS['defaultJSscipts'] as $script) {
1291 $JSscript_txt.="<script src='".LS_JS_DIR.$script."' type='text/javascript'></script>\n";
1294 foreach (self :: $JSscripts as $script) {
1295 if (!$script['path']) {
1296 $script['path']=LS_JS_DIR;
1299 $script['path'].='/';
1301 $JSscript_txt.="<script src='".$script['path'].$script['file']."' type='text/javascript'></script>\n";
1304 $KAconf = LSconfig :: get('keepLSsessionActive');
1307 (!isset(self :: $ldapServer['keepLSsessionActive']))
1309 (!($KAconf === false))
1312 (self :: $ldapServer['keepLSsessionActive'])
1314 self :: addJSconfigParam('keepLSsessionActive',ini_get('session.gc_maxlifetime'));
1317 LStemplate :: assign('LSjsConfig',json_encode(self :: $_JSconfigParams));
1320 $JSscript_txt.="<script type='text/javascript'>LSdebug_active = 1;</script>\n";
1323 $JSscript_txt.="<script type='text/javascript'>LSdebug_active = 0;</script>\n";
1326 LStemplate :: assign('LSsession_js',$JSscript_txt);
1329 self :: addCssFile("LSdefault.css");
1331 foreach (self :: $CssFiles as $file) {
1332 $Css_txt.="<link rel='stylesheet' type='text/css' href='".$file."' />\n";
1334 LStemplate :: assign('LSsession_css',$Css_txt);
1336 if (isset(self :: $LSaccess[self :: $topDn])) {
1337 LStemplate :: assign('LSaccess',self :: $LSaccess[self :: $topDn]);
1341 $listTopDn = self :: getSubDnLdapServer();
1342 if (is_array($listTopDn)) {
1344 LStemplate :: assign('label_level',self :: getSubDnLabel());
1345 LStemplate :: assign('_refresh',_('Refresh'));
1346 $LSsession_topDn_index = array();
1347 $LSsession_topDn_name = array();
1348 foreach($listTopDn as $index => $name) {
1349 $LSsession_topDn_index[] = $index;
1350 $LSsession_topDn_name[] = $name;
1352 LStemplate :: assign('LSsession_subDn_indexes',$LSsession_topDn_index);
1353 LStemplate :: assign('LSsession_subDn_names',$LSsession_topDn_name);
1354 LStemplate :: assign('LSsession_subDn',self :: $topDn);
1355 LStemplate :: assign('LSsession_subDnName',self :: getSubDnName());
1358 LStemplate :: assign('LSlanguages',self :: getLangList());
1359 LStemplate :: assign('LSlang',self :: $lang);
1360 LStemplate :: assign('LSencoding',self :: $encoding);
1361 LStemplate :: assign('lang_label',_('Language'));
1363 LStemplate :: assign('displayLogoutBtn',LSauth :: displayLogoutBtn());
1364 LStemplate :: assign('displaySelfAccess',LSauth :: displaySelfAccess());
1367 if((!empty($_SESSION['LSsession_infos']))&&(is_array($_SESSION['LSsession_infos']))) {
1368 $txt_infos="<ul>\n";
1369 foreach($_SESSION['LSsession_infos'] as $info) {
1370 $txt_infos.="<li>$info</li>\n";
1372 $txt_infos.="</ul>\n";
1373 LStemplate :: assign('LSinfos',$txt_infos);
1374 $_SESSION['LSsession_infos']=array();
1377 if (self :: $ajaxDisplay) {
1378 LStemplate :: assign('LSerror_txt',LSerror :: getErrors());
1379 LStemplate :: assign('LSdebug_txt',LSdebug_print(true));
1382 LSerror :: display();
1385 if (!self :: $template)
1386 self :: setTemplate('empty.tpl');
1388 LStemplate :: assign('connected_as',_("Connected as"));
1390 LStemplate :: display(self :: $template);
1394 * Défini que l'affichage se fera ou non via un retour Ajax
1396 * @param[in] $val boolean True pour que l'affichage se fasse par un retour
1400 public static function setAjaxDisplay($val=true) {
1401 self :: $ajaxDisplay = (boolean)$val;
1405 * Affiche un retour Ajax
1409 public static function displayAjaxReturn($data=array()) {
1410 if (isset($data['LSredirect']) && (!LSdebugDefined()) ) {
1411 echo json_encode($data);
1415 $data['LSjsConfig'] = self :: $_JSconfigParams;
1418 if((!empty($_SESSION['LSsession_infos']))&&(is_array($_SESSION['LSsession_infos']))) {
1419 $txt_infos="<ul>\n";
1420 foreach($_SESSION['LSsession_infos'] as $info) {
1421 $txt_infos.="<li>$info</li>\n";
1423 $txt_infos.="</ul>\n";
1424 $data['LSinfos'] = $txt_infos;
1425 $_SESSION['LSsession_infos']=array();
1428 if (LSerror :: errorsDefined()) {
1429 $data['LSerror'] = LSerror :: getErrors();
1432 if (isset($_REQUEST['imgload'])) {
1433 $data['imgload'] = $_REQUEST['imgload'];
1436 if (LSdebugDefined()) {
1437 $data['LSdebug'] = LSdebug_print(true,false);
1440 echo json_encode($data);
1444 * Retournne un template Smarty compilé
1446 * @param[in] string $template Le template à retourner
1447 * @param[in] array $variables Variables Smarty à assigner avant l'affichage
1449 * @retval string Le HTML compilé du template
1451 public static function fetchTemplate($template,$variables=array()) {
1452 foreach($variables as $name => $val) {
1453 LStemplate :: assign($name,$val);
1455 return LStemplate :: fetch($template);
1459 * Charge les droits LS de l'utilisateur
1461 * @retval boolean True si le chargement à réussi, false sinon.
1463 private static function loadLSprofiles() {
1464 if (is_array(self :: $ldapServer['LSprofiles'])) {
1465 foreach (self :: $ldapServer['LSprofiles'] as $profile => $profileInfos) {
1466 if (is_array($profileInfos)) {
1467 foreach ($profileInfos as $topDn => $rightsInfos) {
1469 * If $topDn == 'LSobject', we search for each LSobject type to find
1470 * all items on witch the user will have powers.
1472 if ($topDn == 'LSobjects') {
1473 if (is_array($rightsInfos)) {
1474 foreach ($rightsInfos as $LSobject => $listInfos) {
1475 if (self :: loadLSclass('LSsearch')) {
1476 if (isset($listInfos['filter'])) {
1477 $filter = self :: getLSuserObject() -> getFData($listInfos['filter']);
1480 $filter = '('.$listInfos['attr'].'='.self :: getLSuserObject() -> getFData($listInfos['attr_value']).')';
1484 'basedn' => (isset($listInfos['basedn'])?$listInfos['basedn']:null),
1488 if (isset($listInfos['params']) && is_array($listInfos['params'])) {
1489 $params = array_merge($listInfos['params'],$params);
1492 $LSsearch = new LSsearch($LSobject,'LSsession :: loadLSprofiles',$params,true);
1493 $LSsearch -> run(false);
1495 self :: $LSprofiles[$profile] = $LSsearch -> listObjectsDn();
1500 LSdebug('LSobjects => [] doit etre un tableau');
1504 if (is_array($rightsInfos)) {
1505 foreach($rightsInfos as $dn => $conf) {
1506 if ((isset($conf['attr'])) && (isset($conf['LSobject']))) {
1507 if( self :: loadLSobject($conf['LSobject']) ) {
1508 if ($object = new $conf['LSobject']()) {
1509 if ($object -> loadData($dn)) {
1510 $listDns=$object -> getValue($conf['attr']);
1511 $valKey = (isset($conf['attr_value']))?$conf['attr_value']:'%{dn}';
1512 $val = self :: getLSuserObject() -> getFData($valKey);
1513 if (is_array($listDns)) {
1514 if (in_array($val,$listDns)) {
1515 self :: $LSprofiles[$profile][] = $topDn;
1520 LSdebug('Impossible de chargé le dn : '.$dn);
1524 LSdebug('Impossible de créer l\'objet de type : '.$conf['LSobject']);
1529 if (self :: $dn == $dn) {
1530 self :: $LSprofiles[$profile][] = $topDn;
1536 if ( self :: $dn == $rightsInfos ) {
1537 self :: $LSprofiles[$profile][] = $topDn;
1540 } // fin else ($topDn == 'LSobjects')
1541 } // fin foreach($profileInfos)
1542 } // fin is_array($profileInfos)
1543 } // fin foreach LSprofiles
1544 LSdebug(self :: $LSprofiles);
1553 * Charge les droits d'accès de l'utilisateur pour construire le menu de l'interface
1557 private static function loadLSaccess() {
1559 if (isset(self :: $ldapServer['subDn']) && is_array(self :: $ldapServer['subDn'])) {
1560 foreach(self :: $ldapServer['subDn'] as $name => $config) {
1561 if ($name=='LSobject') {
1562 if (is_array($config)) {
1564 // Définition des subDns
1565 foreach($config as $objectType => $objectConf) {
1566 if (self :: loadLSobject($objectType)) {
1567 if ($subdnobject = new $objectType()) {
1568 $tbl = $subdnobject -> getSelectArray(NULL,self::getRootDn(),NULL,NULL,false);
1569 if (is_array($tbl)) {
1570 // Définition des accès
1572 if (is_array($objectConf['LSobjects'])) {
1573 foreach($objectConf['LSobjects'] as $type) {
1574 if (self :: loadLSobject($type)) {
1575 if (self :: canAccess($type)) {
1576 $access[$type] = LSconfig :: get('LSobjects.'.$type.'.label');
1581 foreach($tbl as $dn => $dn_name) {
1582 $LSaccess[$dn]=$access;
1591 if ((isCompatibleDNs(self :: $ldapServer['ldap_config']['basedn'],$config['dn']))&&($config['dn']!='')) {
1593 if (is_array($config['LSobjects'])) {
1594 foreach($config['LSobjects'] as $objectType) {
1595 if (self :: loadLSobject($objectType)) {
1596 if (self :: canAccess($objectType)) {
1597 $access[$objectType] = LSconfig :: get('LSobjects.'.$objectType.'.label');
1602 $LSaccess[$config['dn']]=$access;
1608 if(is_array(self :: $ldapServer['LSaccess'])) {
1610 foreach(self :: $ldapServer['LSaccess'] as $objectType) {
1611 if (self :: loadLSobject($objectType)) {
1612 if (self :: canAccess($objectType)) {
1613 $access[$objectType] = LSconfig :: get('LSobjects.'.$objectType.'.label');
1617 $LSaccess[self :: $topDn] = $access;
1620 if (LSauth :: displaySelfAccess()) {
1621 foreach($LSaccess as $dn => $access) {
1622 $LSaccess[$dn] = array_merge(
1624 'SELF' => 'My account'
1630 self :: $LSaccess = $LSaccess;
1631 $_SESSION['LSsession']['LSaccess'] = $LSaccess;
1635 * Dit si l'utilisateur est du profil pour le DN spécifié
1637 * @param[in] string $profile de l'objet
1638 * @param[in] string $dn DN de l'objet
1640 * @retval boolean True si l'utilisateur est du profil sur l'objet, false sinon.
1642 public static function isLSprofile($dn,$profile) {
1643 if (is_array(self :: $LSprofiles[$profile])) {
1644 foreach(self :: $LSprofiles[$profile] as $topDn) {
1648 else if ( isCompatibleDNs($dn,$topDn) ) {
1657 * Retourne qui est l'utilisateur par rapport à l'object
1659 * @param[in] string Le DN de l'objet
1661 * @retval string 'admin'/'self'/'user' pour Admin , l'utilisateur lui même ou un simple utilisateur
1663 public static function whoami($dn) {
1664 $retval = array('user');
1666 foreach(self :: $LSprofiles as $profile => $infos) {
1667 if(self :: isLSprofile($dn,$profile)) {
1672 if (self :: $dn == $dn) {
1680 * Retourne le droit de l'utilisateur à accèder à un objet
1682 * @param[in] string $LSobject Le type de l'objet
1683 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1684 * @param[in] string $right Le type de droit d'accès à tester ('r'/'w')
1685 * @param[in] string $attr Le nom de l'attribut auquel on test l'accès
1687 * @retval boolean True si l'utilisateur a accès, false sinon
1689 public static function canAccess($LSobject,$dn=NULL,$right=NULL,$attr=NULL) {
1690 if (!self :: loadLSobject($LSobject)) {
1694 $whoami = self :: whoami($dn);
1695 if ($dn==self :: getLSuserObject() -> getValue('dn')) {
1696 if (!self :: in_menu('SELF')) {
1701 $obj = new $LSobject();
1703 if (!self :: in_menu($LSobject,$obj -> subDnValue)) {
1709 $objectdn=LSconfig :: get('LSobjects.'.$LSobject.'.container_dn').','.self :: $topDn;
1710 $whoami = self :: whoami($objectdn);
1713 // Pour un attribut particulier
1716 $attr=LSconfig :: get('LSobjects.'.$LSobject.'.rdn');
1718 if (!is_array(LSconfig :: get('LSobjects.'.$LSobject.'.attrs.'.$attr))) {
1723 foreach($whoami as $who) {
1724 $nr = LSconfig :: get('LSobjects.'.$LSobject.'.attrs.'.$attr.'.rights.'.$who);
1728 else if($nr == 'r') {
1735 if (($right=='r')||($right=='w')) {
1742 if ( ($r=='r') || ($r=='w') ) {
1749 // Pour un attribut quelconque
1750 $attrs_conf=LSconfig :: get('LSobjects.'.$LSobject.'.attrs');
1751 if (is_array($attrs_conf)) {
1752 if (($right=='r')||($right=='w')) {
1753 foreach($whoami as $who) {
1754 foreach ($attrs_conf as $attr_name => $attr_config) {
1755 if (isset($attr_config['rights'][$who]) && $attr_config['rights'][$who]==$right) {
1762 foreach($whoami as $who) {
1763 foreach ($attrs_conf as $attr_name => $attr_config) {
1764 if ( (isset($attr_config['rights'][$who])) && ( ($attr_config['rights'][$who]=='r') || ($attr_config['rights'][$who]=='w') ) ) {
1775 * Retourne le droit de l'utilisateur à editer à un objet
1777 * @param[in] string $LSobject Le type de l'objet
1778 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1779 * @param[in] string $attr Le nom de l'attribut auquel on test l'accès
1781 * @retval boolean True si l'utilisateur a accès, false sinon
1783 public static function canEdit($LSobject,$dn=NULL,$attr=NULL) {
1784 return self :: canAccess($LSobject,$dn,'w',$attr);
1788 * Retourne le droit de l'utilisateur à supprimer un objet
1790 * @param[in] string $LSobject Le type de l'objet
1791 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1793 * @retval boolean True si l'utilisateur a accès, false sinon
1795 public static function canRemove($LSobject,$dn) {
1796 return self :: canAccess($LSobject,$dn,'w','rdn');
1800 * Retourne le droit de l'utilisateur à créer un objet
1802 * @param[in] string $LSobject Le type de l'objet
1804 * @retval boolean True si l'utilisateur a accès, false sinon
1806 public static function canCreate($LSobject) {
1807 if (!self :: loadLSobject($LSobject)) {
1810 if (LSconfig :: get("LSobjects.$LSobject.disable_creation")) {
1813 return self :: canAccess($LSobject,NULL,'w','rdn');
1817 * Retourne le droit de l'utilisateur à gérer la relation d'objet
1819 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1820 * @param[in] string $LSobject Le type de l'objet
1821 * @param[in] string $relationName Le nom de la relation avec l'objet
1822 * @param[in] string $right Le type de droit a vérifier ('r' ou 'w')
1824 * @retval boolean True si l'utilisateur a accès, false sinon
1826 public static function relationCanAccess($dn,$LSobject,$relationName,$right=NULL) {
1827 $relConf=LSconfig :: get('LSobjects.'.$LSobject.'.LSrelation.'.$relationName);
1828 if (!is_array($relConf))
1830 $whoami = self :: whoami($dn);
1832 if (($right=='w') || ($right=='r')) {
1834 foreach($whoami as $who) {
1835 $nr = ((isset($relConf['rights'][$who]))?$relConf['rights'][$who]:'');
1839 else if($nr == 'r') {
1851 foreach($whoami as $who) {
1852 if ((isset($relConf['rights'][$who])) && ( ($relConf['rights'][$who] == 'w') || ($relConf['rights'][$who] == 'r') ) ) {
1861 * Retourne le droit de l'utilisateur à modifier la relation d'objet
1863 * @param[in] string $dn Le DN de l'objet (le container_dn du type de l'objet par défaut)
1864 * @param[in] string $LSobject Le type de l'objet
1865 * @param[in] string $relationName Le nom de la relation avec l'objet
1867 * @retval boolean True si l'utilisateur a accès, false sinon
1869 public static function relationCanEdit($dn,$LSobject,$relationName) {
1870 return self :: relationCanAccess($dn,$LSobject,$relationName,'w');
1874 * Retourne le droit de l'utilisateur a executer une customAction
1876 * @param[in] string $dn Le DN de l'objet
1877 * @param[in] string $LSobject Le type de l'objet
1878 * @param[in] string $customActionName Le nom de la customAction
1880 * @retval boolean True si l'utilisateur peut executer cette customAction, false sinon
1882 public static function canExecuteCustomAction($dn,$LSobject,$customActionName) {
1883 $conf=LSconfig :: get('LSobjects.'.$LSobject.'.customActions.'.$customActionName);
1884 if (!is_array($conf))
1886 $whoami = self :: whoami($dn);
1888 if (isset($conf['rights']) && is_array($conf['rights'])) {
1889 foreach($whoami as $who) {
1890 if (in_array($who,$conf['rights'])) {
1900 * Ajoute un fichier temporaire
1902 * @author Benjamin Renard <brenard@easter-eggs.com>
1906 public static function addTmpFile($value,$filePath) {
1907 $hash = mhash(MHASH_MD5,$value);
1908 self :: $tmp_file[$filePath] = $hash;
1909 $_SESSION['LSsession']['tmp_file'][$filePath] = $hash;
1913 * Retourne le chemin du fichier temporaire si l'existe
1915 * @author Benjamin Renard <brenard@easter-eggs.com>
1917 * @param[in] $value La valeur du fichier
1921 public static function tmpFileExist($value) {
1922 $hash = mhash(MHASH_MD5,$value);
1923 foreach(self :: $tmp_file as $filePath => $contentHash) {
1924 if ($hash == $contentHash) {
1932 * Retourne le chemin du fichier temporaire
1934 * Retourne le chemin du fichier temporaire qu'il créera à partir de la valeur
1935 * s'il n'existe pas déjà .
1937 * @author Benjamin Renard <brenard@easter-eggs.com>
1939 * @param[in] $value La valeur du fichier
1943 public static function getTmpFile($value) {
1944 $exist = self :: tmpFileExist($value);
1946 $img_path = LS_TMP_DIR .rand().'.tmp';
1947 $fp = fopen($img_path, "w");
1948 fwrite($fp, $value);
1950 self :: addTmpFile($value,$img_path);
1959 * Supprime les fichiers temporaires
1961 * @author Benjamin Renard <brenard@easter-eggs.com>
1965 public static function deleteTmpFile($filePath=NULL) {
1968 unset(self :: $tmp_file[$filePath]);
1969 unset($_SESSION['LSsession']['tmp_file'][$filePath]);
1972 foreach(self :: $tmp_file as $file => $content) {
1975 self :: $tmp_file = array();
1976 $_SESSION['LSsession']['tmp_file'] = array();
1981 * Retourne true si le cache des droits est activé
1983 * @author Benjamin Renard <brenard@easter-eggs.com>
1985 * @retval boolean True si le cache des droits est activé, false sinon.
1987 public static function cacheLSprofiles() {
1988 return ( (LSconfig :: get('cacheLSprofiles')) || (self :: $ldapServer['cacheLSprofiles']) );
1992 * Retourne true si le cache des subDn est activé
1994 * @author Benjamin Renard <brenard@easter-eggs.com>
1996 * @retval boolean True si le cache des subDn est activé, false sinon.
1998 public static function cacheSudDn() {
1999 return ( (LSconfig :: get('cacheSubDn')) || (self :: $ldapServer['cacheSubDn']));
2003 * Retourne true si le cache des recherches est activé
2005 * @author Benjamin Renard <brenard@easter-eggs.com>
2007 * @retval boolean True si le cache des recherches est activé, false sinon.
2009 public static function cacheSearch() {
2010 return ( (LSconfig :: get('cacheSearch')) || (self :: $ldapServer['cacheSearch']));
2014 * Retourne le label des niveaux pour le serveur ldap courant
2016 * @author Benjamin Renard <brenard@easter-eggs.com>
2018 * @retval string Le label des niveaux pour le serveur ldap dourant
2020 public static function getSubDnLabel() {
2021 return (self :: $ldapServer['subDnLabel']!='')?__(self :: $ldapServer['subDnLabel']):_('Level');
2025 * Retourne le nom du subDn
2027 * @param[in] $subDn string subDn
2029 * @retval string Le nom du subDn ou '' sinon
2031 public static function getSubDnName($subDn=false) {
2033 $subDn = self :: $topDn;
2035 if (self :: getSubDnLdapServer(false)) {
2036 if (isset(self :: $_subDnLdapServer[self :: $ldapServerId][false][$subDn])) {
2037 return self :: $_subDnLdapServer[self :: $ldapServerId][false][$subDn];
2044 * L'objet est t-il utilisé pour listé les subDnS
2046 * @param[in] $type string Le type d'objet
2048 * @retval boolean true si le type d'objet est un subDnObject, false sinon
2050 public static function isSubDnLSobject($type) {
2052 if (isset(self :: $ldapServer['subDn']['LSobject']) && is_array(self :: $ldapServer['subDn']['LSobject'])) {
2053 foreach(self :: $ldapServer['subDn']['LSobject'] as $key => $value) {
2063 * Indique si un type d'objet est dans le menu courant
2065 * @retval boolean true si le type d'objet est dans le menu, false sinon
2067 public static function in_menu($LSobject,$topDn=NULL) {
2069 $topDn=self :: $topDn;
2071 return isset(self :: $LSaccess[$topDn][$LSobject]);
2075 * Indique si le serveur LDAP courant a des subDn
2077 * @retval boolean true si le serveur LDAP courant a des subDn, false sinon
2079 public static function haveSubDn() {
2080 return (isset(self :: $ldapServer['subDn']) && is_array(self :: $ldapServer['subDn']));
2084 * Ajoute une information à afficher
2086 * @param[in] $msg string Le message à afficher
2090 public static function addInfo($msg) {
2091 $_SESSION['LSsession_infos'][]=$msg;
2095 * Redirection de l'utilisateur vers une autre URL
2097 * @param[in] $url string L'URL
2098 * @param[in] $exit boolean Si true, l'execution script s'arrête après la redirection
2102 public static function redirect($url,$exit=true) {
2103 LStemplate :: assign('url',$url);
2104 LStemplate :: display('redirect.tpl');
2111 * Retourne l'adresse mail d'emission configurée pour le serveur courant
2113 * @retval string Adresse mail d'emission
2115 public static function getEmailSender() {
2116 return self :: $ldapServer['emailSender'];
2120 * Ajout d'une information d'aide
2122 * @param[in] $group string Le nom du groupe d'infos dans lequels ajouter
2124 * @param[in] $infos array Tableau array(name => value) des infos
2128 public static function addHelpInfos($group,$infos) {
2129 if (is_array($infos)) {
2130 if (isset(self :: $_JSconfigParams['helpInfos'][$group]) && is_array(self :: $_JSconfigParams['helpInfos'][$group])) {
2131 self :: $_JSconfigParams['helpInfos'][$group] = array_merge(self :: $_JSconfigParams['helpInfos'][$group],$infos);
2134 self :: $_JSconfigParams['helpInfos'][$group] = $infos;
2140 * Défini les codes erreur relative à la classe LSsession
2144 private static function defineLSerrors() {
2148 LSerror :: defineError('LSsession_01',
2149 _("LSsession : The constant %{const} is not defined.")
2151 LSerror :: defineError('LSsession_02',
2152 _("LSsession : The %{addon} support is uncertain. Verify system compatibility and the add-on configuration.")
2154 LSerror :: defineError('LSsession_03',
2155 _("LSsession : LDAP server's configuration data are invalid. Can't connect.")
2157 LSerror :: defineError('LSsession_04',
2158 _("LSsession : Failed to load LSobject type %{type} : unknon type.")
2160 LSerror :: defineError('LSsession_05',
2161 _("LSsession : Failed to load LSclass %{class}.")
2163 LSerror :: defineError('LSsession_06',
2164 _("LSsession : Login or password incorrect.")
2166 LSerror :: defineError('LSsession_07',
2167 _("LSsession : Impossible to identify you : Duplication of identities.")
2169 LSerror :: defineError('LSsession_08',
2170 _("LSsession : Can't load class of authentification (%{class}).")
2172 LSerror :: defineError('LSsession_09',
2173 _("LSsession : Can't connect to LDAP server.")
2175 LSerror :: defineError('LSsession_10',
2176 _("LSsession : Impossible to authenticate you.")
2178 LSerror :: defineError('LSsession_11',
2179 _("LSsession : Your are not authorized to do this action.")
2181 LSerror :: defineError('LSsession_12',
2182 _("LSsession : Some informations are missing to display this page.")
2184 LSerror :: defineError('LSsession_13',
2185 _("LSsession : The function of the custom action %{name} does not exists or is not configured.")
2187 // 14 -> 16 : not yet used
2188 LSerror :: defineError('LSsession_17',
2189 _("LSsession : Error during creation of list of levels. Contact administrators. (Code : %{code})")
2191 LSerror :: defineError('LSsession_18',
2192 _("LSsession : The password recovery is disabled for this LDAP server.")
2194 LSerror :: defineError('LSsession_19',
2195 _("LSsession : Some informations are missing to recover your password. Contact administrators.")
2197 LSerror :: defineError('LSsession_20',
2198 _("LSsession : Error during password recovery. Contact administrators.(Step : %{step})")
2200 // 21 : not yet used
2201 LSerror :: defineError('LSsession_22',
2202 _("LSsession : problem during initialisation.")
2207 * Ajax method when change ldapserver on login form
2209 * @param[in] $data array The return data address
2213 public static function ajax_onLdapServerChangedLogin(&$data) {
2214 if ( isset($_REQUEST['server']) ) {
2215 self :: setLdapServer($_REQUEST['server']);
2217 if ( self :: LSldapConnect() ) {
2218 if (session_id()=="") session_start();
2219 if (isset($_SESSION['LSsession_topDn'])) {
2220 $sel = $_SESSION['LSsession_topDn'];
2225 $list = self :: getSubDnLdapServerOptions($sel,true);
2226 if (is_string($list)) {
2227 $data['list_topDn'] = "<select name='LSsession_topDn' id='LSsession_topDn'>".$list."</select>";
2228 $data['subDnLabel'] = self :: getSubDnLabel();
2231 $data['recoverPassword'] = isset(self :: $ldapServer['recoverPassword']);
2236 * Ajax method when change ldapserver on recoverPassword form
2238 * @param[in] $data array The return data address
2242 public static function ajax_onLdapServerChangedRecoverPassword(&$data) {
2243 if ( isset($_REQUEST['server']) ) {
2244 self :: setLdapServer($_REQUEST['server']);
2245 $data=array('recoverPassword' => isset(self :: $ldapServer['recoverPassword']));