Clean errors detected by PHPstan (level 3)

This commit is contained in:
Benjamin Renard 2023-01-02 01:17:46 +01:00
parent bbde10bbf0
commit 20432adb14
85 changed files with 645 additions and 650 deletions

View file

@ -1,5 +1,5 @@
parameters: parameters:
level: 2 level: 3
paths: paths:
- ../src - ../src
excludePaths: excludePaths:

View file

@ -480,12 +480,12 @@ les possibilités de contribution.</para>
/** /**
* Args autocompleter for CLI my_custom_cli_cmd command * Args autocompleter for CLI my_custom_cli_cmd command
* *
* @param array[string] $command_args List of already typed words of the command * @param array<string> $command_args List of already typed words of the command
* @param int $comp_word_num The command word number to autocomplete * @param int $comp_word_num The command word number to autocomplete
* @param string $comp_word The command word to autocomplete * @param string $comp_word The command word to autocomplete
* @param array[string] $opts List of global available options * @param array<string> $opts List of global available options
* *
* @return array[string] List of available options for the word to autocomplete * @return array<string> List of available options for the word to autocomplete
**/ **/
public static function cli_my_custom_cli_cmd_autocompleter($command_args, $comp_word_num, $comp_word, $opts) { public static function cli_my_custom_cli_cmd_autocompleter($command_args, $comp_word_num, $comp_word, $opts) {
$opts = array_merge($opts, array ('-f', '--force')); $opts = array_merge($opts, array ('-f', '--force'));

View file

@ -78,15 +78,15 @@ LSerror :: defineError('ASTERISK_04',
* @param LSldapObject $ldapObject The LSldapObject use to build the hashed password * @param LSldapObject $ldapObject The LSldapObject use to build the hashed password
* @param string $clearPassword The password in clear text * @param string $clearPassword The password in clear text
* *
* @return string The hashed password * @return string|false The hashed password, or false
*/ */
function hashAsteriskPassword($ldapObject,$clearPassword) { function hashAsteriskPassword($ldapObject,$clearPassword) {
if (!is_a($ldapObject,'LSldapObject')) { if (!is_a($ldapObject,'LSldapObject')) {
LSerror :: addErrorCode('ASTERISK_01',array('function' => 'hashAsteriskPassword', 'objectName' => 'LSldapObject')); LSerror :: addErrorCode('ASTERISK_01',array('function' => 'hashAsteriskPassword', 'objectName' => 'LSldapObject'));
return; return false;
} }
if (!is_string($clearPassword)) { if (!is_string($clearPassword)) {
return; return false;
} }
$ldapObject -> registerOtherValue('clearPassword',$clearPassword); $ldapObject -> registerOtherValue('clearPassword',$clearPassword);
return md5($ldapObject->getFData(LS_ASTERISK_HASH_PWD_FORMAT)); return md5($ldapObject->getFData(LS_ASTERISK_HASH_PWD_FORMAT));
@ -99,12 +99,12 @@ LSerror :: defineError('ASTERISK_04',
* *
* @param LSldapObject $ldapObject The LSldapObject * @param LSldapObject $ldapObject The LSldapObject
* *
* @return string asterisk MD5 hashed password or False * @return string|false asterisk MD5 hashed password or False
*/ */
function generate_asteriskMD5HashedPassword($ldapObject) { function generate_asteriskMD5HashedPassword($ldapObject) {
if ( get_class($ldapObject -> attrs[ LS_ASTERISK_USERPASSWORD_ATTR ]) != 'LSattribute' ) { if ( get_class($ldapObject -> attrs[ LS_ASTERISK_USERPASSWORD_ATTR ]) != 'LSattribute' ) {
LSerror :: addErrorCode('ASTERISK_02',array(LS_ASTERISK_USERPASSWORD_ATTR)); LSerror :: addErrorCode('ASTERISK_02',array(LS_ASTERISK_USERPASSWORD_ATTR));
return; return false;
} }
if ( if (
@ -114,13 +114,13 @@ LSerror :: defineError('ASTERISK_04',
) )
) { ) {
LSerror :: addErrorCode('ASTERISK_04', LS_ASTERISK_USERPASSWORD_ATTR); LSerror :: addErrorCode('ASTERISK_04', LS_ASTERISK_USERPASSWORD_ATTR);
return; return false;
} }
$password = $ldapObject -> attrs[ LS_ASTERISK_USERPASSWORD_ATTR ] -> ldap -> getClearPassword(); $password = $ldapObject -> attrs[ LS_ASTERISK_USERPASSWORD_ATTR ] -> ldap -> getClearPassword();
if (!$password) { if (!$password) {
LSerror :: addErrorCode('ASTERISK_03'); LSerror :: addErrorCode('ASTERISK_03');
return; return false;
} }
return hashAsteriskPassword($ldapObject,(string)$password); return hashAsteriskPassword($ldapObject,(string)$password);
} }

View file

@ -79,7 +79,7 @@ function LSaddon_dyngroup_support() {
return $retval; return $retval;
} }
/* /**
* Parse LDAP search URI * Parse LDAP search URI
* *
* @param string $uri The LDAP search URI to parse * @param string $uri The LDAP search URI to parse
@ -124,7 +124,7 @@ function extractAttributesFromLdapFilterString($filter) {
* *
* @param LSldapObject $ldapObject The LSldapObject * @param LSldapObject $ldapObject The LSldapObject
* *
* @return array|null array of memberUid URI attribute values or null in case of error * @return array|false array of memberUid URI attribute values or false in case of error
*/ */
function generateDyngroupMemberUidURI($ldapObject) { function generateDyngroupMemberUidURI($ldapObject) {
if (!isset($ldapObject -> attrs[ DYNGROUP_MEMBER_DN_URI_ATTRIBUTE ])) { if (!isset($ldapObject -> attrs[ DYNGROUP_MEMBER_DN_URI_ATTRIBUTE ])) {
@ -132,17 +132,17 @@ function generateDyngroupMemberUidURI($ldapObject) {
'DYNGROUP_01', 'DYNGROUP_01',
array('dependency' => DYNGROUP_MEMBER_DN_URI_ATTRIBUTE, 'attr' => DYNGROUP_MEMBER_UID_URI_ATTRIBUTE) array('dependency' => DYNGROUP_MEMBER_DN_URI_ATTRIBUTE, 'attr' => DYNGROUP_MEMBER_UID_URI_ATTRIBUTE)
); );
return; return false;
} }
$dn_uri = $ldapObject -> attrs[ DYNGROUP_MEMBER_DN_URI_ATTRIBUTE ] -> getValue(); $dn_uri = $ldapObject -> attrs[ DYNGROUP_MEMBER_DN_URI_ATTRIBUTE ] -> getValue();
if (empty($dn_uri)) if (empty($dn_uri))
return; return false;
$uri_parts = explode('?', $dn_uri[0]); $uri_parts = explode('?', $dn_uri[0]);
if (count($uri_parts) < 2) { if (count($uri_parts) < 2) {
LSerror :: addErrorCode('DYNGROUP_02', DYNGROUP_MEMBER_DN_URI_ATTRIBUTE); LSerror :: addErrorCode('DYNGROUP_02', DYNGROUP_MEMBER_DN_URI_ATTRIBUTE);
return; return false;
} }
$uri_parts[1] = 'uid'; $uri_parts[1] = 'uid';
return array( return array(
@ -354,6 +354,11 @@ function triggerUpdateDynGroupsMembersCacheOnUserChanges(&$user, &$changed_attrs
if (php_sapi_name() != 'cli') if (php_sapi_name() != 'cli')
return true; return true;
/**
* CLI command to update dynamic groups members cache
* @param array<string> $command_args Command arguments
* @return bool
*/
function cli_updateDynGroupsMembersCache($command_args) { function cli_updateDynGroupsMembersCache($command_args) {
return updateDynGroupsMembersCache(); return updateDynGroupsMembersCache();
} }

View file

@ -140,7 +140,7 @@ LSerror :: defineError('LS_EXPORTSEARCHRESULTASCSV_03',
* Write CSV row in file * Write CSV row in file
* *
* @param resource &$csv The CSV file description reference * @param resource &$csv The CSV file description reference
* @param array[string] $row An array of a CSV row fields to write * @param array<string> $row An array of a CSV row fields to write
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *

View file

@ -89,7 +89,7 @@ LSerror :: defineError('FTP_05',
* @param string $user Le nom d'utilidateur de connexion * @param string $user Le nom d'utilidateur de connexion
* @param string $pwd Le mot de passe de connexion * @param string $pwd Le mot de passe de connexion
* *
* @return mixed Net_FTP object en cas de succès, false sinon * @return Net_FTP|false Net_FTP object en cas de succès, false sinon
*/ */
function connectToFTP($host,$port,$user,$pwd) { function connectToFTP($host,$port,$user,$pwd) {
$cnx = new Net_FTP(); $cnx = new Net_FTP();
@ -102,13 +102,13 @@ LSerror :: defineError('FTP_05',
else { else {
LSerror :: addErrorCode('FTP_01',"2"); LSerror :: addErrorCode('FTP_01',"2");
LSerror :: addErrorCode('FTP_00',$do -> getMessage()); LSerror :: addErrorCode('FTP_00',$do -> getMessage());
return; return false;
} }
} }
else { else {
LSerror :: addErrorCode('FTP_01',"1"); LSerror :: addErrorCode('FTP_01',"1");
LSerror :: addErrorCode('FTP_00',$do -> getMessage()); LSerror :: addErrorCode('FTP_00',$do -> getMessage());
return; return false;
} }
} }
@ -123,13 +123,11 @@ LSerror :: defineError('FTP_05',
* @param string $pwd Le mot de passe de connexion * @param string $pwd Le mot de passe de connexion
* @param array $dirs ou string Le(s) dossier(s) à ajouter * @param array $dirs ou string Le(s) dossier(s) à ajouter
* *
* @return string True ou false si il y a un problème durant la création du/des dossier(s) * @return bool True ou false si il y a un problème durant la création du/des dossier(s)
*/ */
function createDirsByFTP($host,$port,$user,$pwd,$dirs,$chmod=NULL) { function createDirsByFTP($host,$port,$user,$pwd,$dirs,$chmod=NULL) {
$cnx = connectToFTP($host,$port,$user,$pwd); $cnx = connectToFTP($host,$port,$user,$pwd);
if (! $cnx){ if (!$cnx) return false;
return;
}
if (!is_array($dirs)) { if (!is_array($dirs)) {
$dirs = array($dirs); $dirs = array($dirs);
} }
@ -138,7 +136,7 @@ LSerror :: defineError('FTP_05',
if ($do instanceof PEAR_Error) { if ($do instanceof PEAR_Error) {
LSerror :: addErrorCode('FTP_02',$dir); LSerror :: addErrorCode('FTP_02',$dir);
LSerror :: addErrorCode('FTP_00',$do -> getMessage()); LSerror :: addErrorCode('FTP_00',$do -> getMessage());
return; return false;
} }
if ($chmod) { if ($chmod) {
$do = $cnx -> chmod($dir,$chmod); $do = $cnx -> chmod($dir,$chmod);
@ -170,13 +168,11 @@ LSerror :: defineError('FTP_05',
* @param string $pwd Le mot de passe de connexion * @param string $pwd Le mot de passe de connexion
* @param array $dirs ou string Le(s) dossier(s) à supprimer * @param array $dirs ou string Le(s) dossier(s) à supprimer
* *
* @return string True ou false si il y a un problème durant la suppression du/des dossier(s) * @return bool True ou false si il y a un problème durant la suppression du/des dossier(s)
*/ */
function removeDirsByFTP($host,$port,$user,$pwd,$dirs) { function removeDirsByFTP($host,$port,$user,$pwd,$dirs) {
$cnx = connectToFTP($host,$port,$user,$pwd); $cnx = connectToFTP($host,$port,$user,$pwd);
if (! $cnx){ if (!$cnx) return false;
return;
}
if (!is_array($dirs)) { if (!is_array($dirs)) {
$dirs = array($dirs); $dirs = array($dirs);
} }
@ -188,7 +184,7 @@ LSerror :: defineError('FTP_05',
if ($do instanceof PEAR_Error) { if ($do instanceof PEAR_Error) {
LSerror :: addErrorCode('FTP_03',$dir); LSerror :: addErrorCode('FTP_03',$dir);
LSerror :: addErrorCode('FTP_00',$do -> getMessage()); LSerror :: addErrorCode('FTP_00',$do -> getMessage());
return; return false;
} }
} }
return true; return true;
@ -206,18 +202,16 @@ LSerror :: defineError('FTP_05',
* @param string $old Le dossier à renomer * @param string $old Le dossier à renomer
* @param string $new Le nouveau nom du dossier à renomer * @param string $new Le nouveau nom du dossier à renomer
* *
* @return string True ou false si il y a un problème durant le renomage du/des dossier(s) * @return bool True ou false si il y a un problème durant le renomage du/des dossier(s)
*/ */
function renameDirByFTP($host,$port,$user,$pwd,$old,$new) { function renameDirByFTP($host,$port,$user,$pwd,$old,$new) {
$cnx = connectToFTP($host,$port,$user,$pwd); $cnx = connectToFTP($host,$port,$user,$pwd);
if (! $cnx){ if (!$cnx) return false;
return;
}
$do = $cnx -> rename($old,$new); $do = $cnx -> rename($old,$new);
if ($do instanceof PEAR_Error) { if ($do instanceof PEAR_Error) {
LSerror :: addErrorCode('FTP_05',array('old' => $old,'new' => $new)); LSerror :: addErrorCode('FTP_05',array('old' => $old,'new' => $new));
LSerror :: addErrorCode('FTP_00',$do -> getMessage()); LSerror :: addErrorCode('FTP_00',$do -> getMessage());
return; return false;
} }
return true; return true;
} }

View file

@ -154,7 +154,7 @@ LSerror :: defineError('MAIL_01',
if ($ret instanceof PEAR_Error) { if ($ret instanceof PEAR_Error) {
LSerror :: addErrorCode('MAIL_01'); LSerror :: addErrorCode('MAIL_01');
LSerror :: addErrorCode('MAIL_00', $ret -> getMessage()); LSerror :: addErrorCode('MAIL_00', $ret -> getMessage());
return; return false;
} }
return true; return true;
} }
@ -163,6 +163,11 @@ LSerror :: defineError('MAIL_01',
if (php_sapi_name() != 'cli') if (php_sapi_name() != 'cli')
return true; return true;
/**
* CLI command to send a test email
* @param array $command_args Command arguments
* @return bool
*/
function cli_test_send_mail($command_args) { function cli_test_send_mail($command_args) {
$recipient = null; $recipient = null;
$subject = "Test email"; $subject = "Test email";
@ -209,6 +214,16 @@ function cli_test_send_mail($command_args) {
return true; return true;
} }
/**
* Args autocompleter for CLI test_send_mail command
*
* @param array<string> $comp_words List of already typed words of the command
* @param int $comp_word_num The command word number to autocomplete
* @param string $comp_word The command word to autocomplete
* @param array<string> $opts List of global available options
*
* @return array<string> List of available options for the word to autocomplete
**/
function cli_test_send_mail_autocompleter($comp_words, $comp_word_num, $comp_word, $opts) { function cli_test_send_mail_autocompleter($comp_words, $comp_word_num, $comp_word, $opts) {
switch ($comp_words[$comp_word_num-1]) { switch ($comp_words[$comp_word_num-1]) {
case '-s': case '-s':

View file

@ -52,7 +52,7 @@ LSerror :: defineError('MAILDIR_04',
* @return boolean true si Maildir est pleinement supporté, false sinon * @return boolean true si Maildir est pleinement supporté, false sinon
*/ */
function LSaddon_maildir_support() { function LSaddon_maildir_support() {
$retval=true; $retval=true;
// Dependance de librairie // Dependance de librairie
if (!function_exists('createDirsByFTP')) { if (!function_exists('createDirsByFTP')) {
@ -87,13 +87,13 @@ $retval=true;
* @param string $dir Le chemin de la maildir. Si défini, la valeur ne sera pas * @param string $dir Le chemin de la maildir. Si défini, la valeur ne sera pas
* récupérée dans le ldapObject * récupérée dans le ldapObject
* *
* @return string True ou false si il y a un problème durant la création de la Maildir * @return bool True ou false si il y a un problème durant la création de la Maildir
*/ */
function createMaildirByFTP($ldapObject,$dir=null) { function createMaildirByFTP($ldapObject,$dir=null) {
if (!$dir) { if (!$dir) {
$dir = getMaildirPath($ldapObject); $dir = getMaildirPath($ldapObject);
if (!$dir) { if (!$dir) {
return; return false;
} }
} }
$dirs = array( $dirs = array(
@ -103,7 +103,7 @@ $retval=true;
); );
if (!createDirsByFTP(LS_MAILDIR_FTP_HOST,LS_MAILDIR_FTP_PORT,LS_MAILDIR_FTP_USER,LS_MAILDIR_FTP_PWD,$dirs,LS_MAILDIR_FTP_MAILDIR_CHMOD)) { if (!createDirsByFTP(LS_MAILDIR_FTP_HOST,LS_MAILDIR_FTP_PORT,LS_MAILDIR_FTP_USER,LS_MAILDIR_FTP_PWD,$dirs,LS_MAILDIR_FTP_MAILDIR_CHMOD)) {
LSerror :: addErrorCode('MAILDIR_01'); LSerror :: addErrorCode('MAILDIR_01');
return; return false;
} }
return true; return true;
} }
@ -117,18 +117,18 @@ $retval=true;
* @param string $dir Le chemin de la maildir. Si défini, la valeur ne sera pas * @param string $dir Le chemin de la maildir. Si défini, la valeur ne sera pas
* récupérée dans le ldapObject * récupérée dans le ldapObject
* *
* @return string True ou false si il y a un problème durant la suppression de la Maildir * @return bool True ou false si il y a un problème durant la suppression de la Maildir
*/ */
function removeMaildirByFTP($ldapObject,$dir=null) { function removeMaildirByFTP($ldapObject,$dir=null) {
if (!$dir) { if (!$dir) {
$dir = getMaildirPath($ldapObject); $dir = getMaildirPath($ldapObject);
if (!$dir) { if (!$dir) {
return; return false;
} }
} }
if (!removeDirsByFTP(LS_MAILDIR_FTP_HOST,LS_MAILDIR_FTP_PORT,LS_MAILDIR_FTP_USER,LS_MAILDIR_FTP_PWD,$dir)) { if (!removeDirsByFTP(LS_MAILDIR_FTP_HOST,LS_MAILDIR_FTP_PORT,LS_MAILDIR_FTP_USER,LS_MAILDIR_FTP_PWD,$dir)) {
LSerror :: addErrorCode('MAILDIR_02'); LSerror :: addErrorCode('MAILDIR_02');
return; return false;
} }
return true; return true;
} }
@ -140,7 +140,7 @@ $retval=true;
* *
* @param LSldapObject $ldapObject L'objet ldap * @param LSldapObject $ldapObject L'objet ldap
* *
* @return string Le chemin distant de la maildir ou false si il y a un problème * @return string|false Le chemin distant de la maildir ou false si il y a un problème
*/ */
function getMaildirPath($ldapObject) { function getMaildirPath($ldapObject) {
$dir = getFData(LS_MAILDIR_FTP_MAILDIR_PATH,$ldapObject,'getValue'); $dir = getFData(LS_MAILDIR_FTP_MAILDIR_PATH,$ldapObject,'getValue');
@ -156,7 +156,7 @@ $retval=true;
if ($dir=="") { if ($dir=="") {
LSerror :: addErrorCode('MAILDIR_04'); LSerror :: addErrorCode('MAILDIR_04');
return; return false;
} }
return $dir; return $dir;
@ -170,12 +170,12 @@ $retval=true;
* @param string $old L'ancien chemin de la maildir * @param string $old L'ancien chemin de la maildir
* @param string $new Le nouveau chemin de la maildir * @param string $new Le nouveau chemin de la maildir
* *
* @return string True ou false si il y a un problème durant le renomage de la Maildir * @return bool True ou false si il y a un problème durant le renomage de la Maildir
*/ */
function renameMaildirByFTP($old,$new) { function renameMaildirByFTP($old,$new) {
if (!renameDirByFTP(LS_MAILDIR_FTP_HOST,LS_MAILDIR_FTP_PORT,LS_MAILDIR_FTP_USER,LS_MAILDIR_FTP_PWD,$old,$new)) { if (!renameDirByFTP(LS_MAILDIR_FTP_HOST,LS_MAILDIR_FTP_PORT,LS_MAILDIR_FTP_USER,LS_MAILDIR_FTP_PWD,$old,$new)) {
LSerror :: addErrorCode('MAILDIR_03'); LSerror :: addErrorCode('MAILDIR_03');
return; return false;
} }
return true; return true;
} }

View file

@ -146,7 +146,7 @@ function mailquota_get_usage(&$LSldapObject) {
* *
* @param LSldapObject &$LSldapObject The LDAP object * @param LSldapObject &$LSldapObject The LDAP object
* *
* @return true in any case * @return bool true in any case
**/ **/
function mailquota_show_usage(&$LSldapObject) { function mailquota_show_usage(&$LSldapObject) {
$quota = mailquota_get_usage($LSldapObject); $quota = mailquota_get_usage($LSldapObject);

View file

@ -87,7 +87,7 @@ LSerror :: defineError('POSIX_01',
* *
* @param LSldapObject $ldapObject L'objet ldap * @param LSldapObject $ldapObject L'objet ldap
* *
* @return integer uidNumber ou false si il y a un problème durant la génération * @return integer|false uidNumber ou false si il y a un problème durant la génération
*/ */
function generate_uidNumber($ldapObject) { function generate_uidNumber($ldapObject) {
@ -103,7 +103,7 @@ LSerror :: defineError('POSIX_01',
$uidNumber = LS_POSIX_UIDNUMBER_MIN_VAL; $uidNumber = LS_POSIX_UIDNUMBER_MIN_VAL;
if (!is_array($objects)) if (!is_array($objects))
return; return false;
foreach($objects as $object) { foreach($objects as $object) {
if($object['attrs'][LS_POSIX_UIDNUMBER_ATTR] > $uidNumber) if($object['attrs'][LS_POSIX_UIDNUMBER_ATTR] > $uidNumber)
@ -122,7 +122,7 @@ LSerror :: defineError('POSIX_01',
* *
* @param LSldapObject $ldapObject L'objet ldap * @param LSldapObject $ldapObject L'objet ldap
* *
* @return integer gidNumber ou false si il y a un problème durant la génération * @return integer|false gidNumber ou false si il y a un problème durant la génération
*/ */
function generate_gidNumber($ldapObject) { function generate_gidNumber($ldapObject) {
@ -138,7 +138,7 @@ LSerror :: defineError('POSIX_01',
$gidNumber = LS_POSIX_GIDNUMBER_MIN_VAL; $gidNumber = LS_POSIX_GIDNUMBER_MIN_VAL;
if (!is_array($objects)) if (!is_array($objects))
return; return false;
foreach($objects as $object) { foreach($objects as $object) {
if($object['attrs'][LS_POSIX_GIDNUMBER_ATTR] > $gidNumber) if($object['attrs'][LS_POSIX_GIDNUMBER_ATTR] > $gidNumber)
@ -157,12 +157,12 @@ LSerror :: defineError('POSIX_01',
* *
* @param LSldapObject $ldapObject L'objet ldap * @param LSldapObject $ldapObject L'objet ldap
* *
* @return string homeDirectory ou false si il y a un problème durant la génération * @return string|false homeDirectory ou false si il y a un problème durant la génération
*/ */
function generate_homeDirectory($ldapObject) { function generate_homeDirectory($ldapObject) {
if ( get_class($ldapObject -> attrs[ LS_POSIX_UID_ATTR ]) != 'LSattribute' ) { if ( get_class($ldapObject -> attrs[ LS_POSIX_UID_ATTR ]) != 'LSattribute' ) {
LSerror :: addErrorCode('POSIX_01',array('dependency' => 'uid', 'attr' => 'homeDirectory')); LSerror :: addErrorCode('POSIX_01',array('dependency' => 'uid', 'attr' => 'homeDirectory'));
return; return false;
} }
$uid = $ldapObject -> attrs[ LS_POSIX_UID_ATTR ] -> getValue(); $uid = $ldapObject -> attrs[ LS_POSIX_UID_ATTR ] -> getValue();
@ -172,19 +172,19 @@ LSerror :: defineError('POSIX_01',
} }
/** /**
* Generation de homeDirectory * Create home directory by FTP
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @param LSldapObject $ldapObject L'objet ldap * @param LSldapObject $ldapObject L'objet ldap
* *
* @return string homeDirectory ou false si il y a un problème durant la génération * @return bool True on success, false otherwise
*/ */
function createHomeDirectoryByFTP($ldapObject) { function createHomeDirectoryByFTP($ldapObject) {
$dir = getFData(LS_POSIX_HOMEDIRECTORY_FTP_PATH,$ldapObject,'getValue'); $dir = getFData(LS_POSIX_HOMEDIRECTORY_FTP_PATH,$ldapObject,'getValue');
if (!createDirsByFTP(LS_POSIX_HOMEDIRECTORY_FTP_HOST,LS_POSIX_HOMEDIRECTORY_FTP_PORT,LS_POSIX_HOMEDIRECTORY_FTP_USER,LS_POSIX_HOMEDIRECTORY_FTP_PWD,$dir)) { if (!createDirsByFTP(LS_POSIX_HOMEDIRECTORY_FTP_HOST,LS_POSIX_HOMEDIRECTORY_FTP_PORT,LS_POSIX_HOMEDIRECTORY_FTP_USER,LS_POSIX_HOMEDIRECTORY_FTP_PWD,$dir)) {
LSerror :: addErrorCode('POSIX_02'); LSerror :: addErrorCode('POSIX_02');
return; return false;
} }
return true; return true;
} }
@ -199,22 +199,22 @@ LSerror :: defineError('POSIX_01',
* *
* @param LSldapObject $ldapObject The LSldapObject * @param LSldapObject $ldapObject The LSldapObject
* *
* @return array|null array of member attribute values or null in case of error * @return array|false array of member attribute values or false in case of error
*/ */
function generateMemberFromMemberUid($ldapObject) { function generateMemberFromMemberUid($ldapObject) {
if ( get_class($ldapObject -> attrs[ 'memberUid' ]) != 'LSattribute' ) { if ( get_class($ldapObject -> attrs[ 'memberUid' ]) != 'LSattribute' ) {
LSerror :: addErrorCode('POSIX_01',array('dependency' => 'memberUid', 'attr' => 'member')); LSerror :: addErrorCode('POSIX_01',array('dependency' => 'memberUid', 'attr' => 'member'));
return; return false;
} }
if ( get_class($ldapObject -> attrs[ 'member' ]) != 'LSattribute' ) { if ( get_class($ldapObject -> attrs[ 'member' ]) != 'LSattribute' ) {
LSerror :: addErrorCode('POSIX_01',array('dependency' => 'member', 'attr' => 'member')); LSerror :: addErrorCode('POSIX_01',array('dependency' => 'member', 'attr' => 'member'));
return; return false;
} }
$obj_type=LSconfig::get('LSobjects.'.get_class($ldapObject).'.attrs.memberUid.html_options.selectable_object.object_type'); $obj_type=LSconfig::get('LSobjects.'.get_class($ldapObject).'.attrs.memberUid.html_options.selectable_object.object_type');
if (empty($obj_type)) if (empty($obj_type))
return; return false;
$uids = $ldapObject -> attrs[ 'memberUid' ] -> getValue(); $uids = $ldapObject -> attrs[ 'memberUid' ] -> getValue();
$member = array(); $member = array();
@ -237,17 +237,17 @@ LSerror :: defineError('POSIX_01',
* *
* @param LSldapObject $ldapObject The LSldapObject * @param LSldapObject $ldapObject The LSldapObject
* *
* @return array|null array of memberUid values or null in case of error * @return array|false array of memberUid values or false in case of error
*/ */
function generate_memberUidFromUniqueMember($ldapObject) { function generate_memberUidFromUniqueMember($ldapObject) {
if ( get_class($ldapObject -> attrs[ 'memberUid' ]) != 'LSattribute' ) { if ( get_class($ldapObject -> attrs[ 'memberUid' ]) != 'LSattribute' ) {
LSerror :: addErrorCode('POSIX_01',array('dependency' => 'memberUid', 'attr' => 'memberUid')); LSerror :: addErrorCode('POSIX_01',array('dependency' => 'memberUid', 'attr' => 'memberUid'));
return; return false;
} }
if ( get_class($ldapObject -> attrs[ 'uniqueMember' ]) != 'LSattribute' ) { if ( get_class($ldapObject -> attrs[ 'uniqueMember' ]) != 'LSattribute' ) {
LSerror :: addErrorCode('POSIX_01',array('dependency' => 'uniqueMember', 'attr' => 'memberUid')); LSerror :: addErrorCode('POSIX_01',array('dependency' => 'uniqueMember', 'attr' => 'memberUid'));
return; return false;
} }
$dns = $ldapObject -> attrs[ 'uniqueMember' ] -> getValue(); $dns = $ldapObject -> attrs[ 'uniqueMember' ] -> getValue();

View file

@ -200,7 +200,8 @@ function ppolicy_extraDisplayColumn_password_expiration($entry) {
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return boolean Void if CSV file is successfully generated and upload, false in other case * @return boolean|array Data to export as array if $return is enabled, otherwise, true on
* success and false on error.
*/ */
function ppolicy_export_search_info($LSsearch, $as_csv=true, $return=false) { function ppolicy_export_search_info($LSsearch, $as_csv=true, $return=false) {
$csv = null; $csv = null;
@ -304,7 +305,7 @@ function ppolicy_export_search_info($LSsearch, $as_csv=true, $return=false) {
* Write CSV row in file * Write CSV row in file
* *
* @param resource $csv The CSV file description reference * @param resource $csv The CSV file description reference
* @param array[string] $row An array of a CSV row fields to write * @param array<string> $row An array of a CSV row fields to write
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
@ -345,13 +346,13 @@ function handle_api_LSobject_exportPpolicyInfo($request) {
if (!array_intersect($GLOBALS['LS_PPOLICY_API_GRANTED_PROFILES'], $whoami)) { if (!array_intersect($GLOBALS['LS_PPOLICY_API_GRANTED_PROFILES'], $whoami)) {
LSerror :: addErrorCode('LSsession_11'); LSerror :: addErrorCode('LSsession_11');
LSsession :: displayAjaxReturn(); LSsession :: displayAjaxReturn();
return false; return;
} }
if (!LSsession :: loadLSclass('LSsearch')) { if (!LSsession :: loadLSclass('LSsearch')) {
LSerror :: addErrorCode('LSsession_05', 'LSsearch'); LSerror :: addErrorCode('LSsession_05', 'LSsearch');
LSsession :: displayAjaxReturn(); LSsession :: displayAjaxReturn();
return false; return;
} }
$search = new LSsearch( $search = new LSsearch(
@ -367,6 +368,12 @@ function handle_api_LSobject_exportPpolicyInfo($request) {
if (php_sapi_name() != 'cli') if (php_sapi_name() != 'cli')
return true; return true;
/**
* CLI command to export password policy info of a all objects of a specified object type
* @param array<string> $command_args Command arguments
* @return bool
*/
function cli_export_ppolicy_info($command_args) { function cli_export_ppolicy_info($command_args) {
$objType = null; $objType = null;
$output = false; $output = false;
@ -427,19 +434,20 @@ function cli_export_ppolicy_info($command_args) {
exit(); exit();
} }
$fd = fopen($output, 'w') or LStemplate::fatal_error("Fail to open output file '$output'"); $fd = fopen($output, 'w') or LStemplate::fatal_error("Fail to open output file '$output'");
fwrite($fd, $data) or LStemplate::fatal_error("Fail to write result in output file '$output'"); $result = fwrite($fd, $data) or LStemplate::fatal_error("Fail to write result in output file '$output'");
@fclose($fd); @fclose($fd);
return $result;
} }
/** /**
* Args autocompleter for CLI export_ppolicy_info command * Args autocompleter for CLI export_ppolicy_info command
* *
* @param array[string] $command_args List of already typed words of the command * @param array<string> $command_args List of already typed words of the command
* @param int $comp_word_num The command word number to autocomplete * @param int $comp_word_num The command word number to autocomplete
* @param string $comp_word The command word to autocomplete * @param string $comp_word The command word to autocomplete
* @param array[string] $opts List of global available options * @param array<string> $opts List of global available options
* *
* @return array[string] List of available options for the word to autocomplete * @return array<string> List of available options for the word to autocomplete
**/ **/
function cli_export_ppolicy_info_args_autocompleter($command_args, $comp_word_num, $comp_word, $opts) { function cli_export_ppolicy_info_args_autocompleter($command_args, $comp_word_num, $comp_word, $opts) {
$opts = array_merge($opts, array ('-o', '--output', '-j', '--json', '-p', '--pretty')); $opts = array_merge($opts, array ('-o', '--output', '-j', '--json', '-p', '--pretty'));

View file

@ -117,7 +117,7 @@ function LSaddon_samba_support() {
* @param string $unix_attr The UNIX attribute name * @param string $unix_attr The UNIX attribute name
* @param integer $base_number The base number value * @param integer $base_number The base number value
* *
* @return string SambaSID ou false si il y a un problème durant la génération * @return string|false SambaSID ou false si il y a un problème durant la génération
*/ */
function generate_sambaSID($ldapObject, $unix_attr, $base_number) { function generate_sambaSID($ldapObject, $unix_attr, $base_number) {
if ( get_class($ldapObject -> attrs[ $unix_attr ]) != 'LSattribute' ) { if ( get_class($ldapObject -> attrs[ $unix_attr ]) != 'LSattribute' ) {
@ -128,7 +128,7 @@ function generate_sambaSID($ldapObject, $unix_attr, $base_number) {
'attr' => 'sambaSID' 'attr' => 'sambaSID'
) )
); );
return; return false;
} }
$unix_id_attr_val = $ldapObject -> getValue($unix_attr, true, null); $unix_id_attr_val = $ldapObject -> getValue($unix_attr, true, null);
@ -145,7 +145,7 @@ function generate_sambaSID($ldapObject, $unix_attr, $base_number) {
* @param LSldapObject $ldapObject The user LSldapObject object * @param LSldapObject $ldapObject The user LSldapObject object
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return string User SambaSID value on success, false otherwise * @return string|false User SambaSID value on success, false otherwise
*/ */
function generate_user_sambaSID($ldapObject) { function generate_user_sambaSID($ldapObject) {
return generate_sambaSID($ldapObject, LS_SAMBA_UIDNUMBER_ATTR, LS_SAMBA_SID_BASE_USER); return generate_sambaSID($ldapObject, LS_SAMBA_UIDNUMBER_ATTR, LS_SAMBA_SID_BASE_USER);
@ -162,7 +162,7 @@ function generate_user_sambaSID($ldapObject) {
* @param LSldapObject $ldapObject The user LSldapObject object * @param LSldapObject $ldapObject The user LSldapObject object
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return string User SambaSID value on success, false otherwise * @return string|false User SambaSID value on success, false otherwise
*/ */
function generate_sambaUserSID($ldapObject) { function generate_sambaUserSID($ldapObject) {
LSerror :: addErrorCode( LSerror :: addErrorCode(
@ -185,7 +185,7 @@ function generate_sambaUserSID($ldapObject) {
* @param LSldapObject $ldapObject The group LSldapObject object * @param LSldapObject $ldapObject The group LSldapObject object
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return string Group SambaSID value on success, false otherwise * @return string|false Group SambaSID value on success, false otherwise
*/ */
function generate_group_sambaSID($ldapObject) { function generate_group_sambaSID($ldapObject) {
return generate_sambaSID($ldapObject, LS_SAMBA_GIDNUMBER_ATTR, LS_SAMBA_SID_BASE_GROUP); return generate_sambaSID($ldapObject, LS_SAMBA_GIDNUMBER_ATTR, LS_SAMBA_SID_BASE_GROUP);
@ -200,7 +200,7 @@ function generate_group_sambaSID($ldapObject) {
* @param LSldapObject $ldapObject The group LSldapObject object * @param LSldapObject $ldapObject The group LSldapObject object
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return string Group SambaSID value on success, false otherwise * @return string|false Group SambaSID value on success, false otherwise
*/ */
function generate_sambaGroupSID($ldapObject) { function generate_sambaGroupSID($ldapObject) {
LSerror :: addErrorCode( LSerror :: addErrorCode(
@ -223,7 +223,7 @@ function generate_sambaGroupSID($ldapObject) {
* @param LSldapObject $ldapObject The LSldapObject object * @param LSldapObject $ldapObject The LSldapObject object
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return string The sambaPrimaryGroupSID value on success, false otherwise * @return string|false The sambaPrimaryGroupSID value on success, false otherwise
*/ */
function generate_sambaPrimaryGroupSID($ldapObject) { function generate_sambaPrimaryGroupSID($ldapObject) {
return generate_sambaSID($ldapObject, LS_SAMBA_GIDNUMBER_ATTR, LS_SAMBA_SID_BASE_GROUP); return generate_sambaSID($ldapObject, LS_SAMBA_GIDNUMBER_ATTR, LS_SAMBA_SID_BASE_GROUP);
@ -242,7 +242,7 @@ function generate_sambaPrimaryGroupSID($ldapObject) {
function generate_sambaNTPassword($ldapObject) { function generate_sambaNTPassword($ldapObject) {
if ( get_class($ldapObject -> attrs[ LS_SAMBA_USERPASSWORD_ATTR ]) != 'LSattribute' ) { if ( get_class($ldapObject -> attrs[ LS_SAMBA_USERPASSWORD_ATTR ]) != 'LSattribute' ) {
LSerror :: addErrorCode('SAMBA_01',array('dependency' => LS_SAMBA_USERPASSWORD_ATTR, 'attr' => 'sambaNTPassword')); LSerror :: addErrorCode('SAMBA_01',array('dependency' => LS_SAMBA_USERPASSWORD_ATTR, 'attr' => 'sambaNTPassword'));
return; return false;
} }
if ( if (
@ -252,14 +252,14 @@ function generate_sambaPrimaryGroupSID($ldapObject) {
) )
) { ) {
LSerror :: addErrorCode('SAMBA_05', LS_SAMBA_USERPASSWORD_ATTR); LSerror :: addErrorCode('SAMBA_05', LS_SAMBA_USERPASSWORD_ATTR);
return; return false;
} }
$password = $ldapObject -> attrs[ LS_SAMBA_USERPASSWORD_ATTR ] -> ldap -> getClearPassword(); $password = $ldapObject -> attrs[ LS_SAMBA_USERPASSWORD_ATTR ] -> ldap -> getClearPassword();
$sambapassword = new smbHash; $sambapassword = new smbHash;
$sambaNTPassword = $sambapassword -> nthash($password); $sambaNTPassword = $sambapassword -> nthash($password);
if($sambaNTPassword == '') { if($sambaNTPassword == '') {
return; return false;
} }
return $sambaNTPassword; return $sambaNTPassword;
} }
@ -275,8 +275,11 @@ function generate_sambaPrimaryGroupSID($ldapObject) {
*/ */
function generate_sambaLMPassword($ldapObject) { function generate_sambaLMPassword($ldapObject) {
if ( get_class($ldapObject -> attrs[ LS_SAMBA_USERPASSWORD_ATTR ]) != 'LSattribute' ) { if ( get_class($ldapObject -> attrs[ LS_SAMBA_USERPASSWORD_ATTR ]) != 'LSattribute' ) {
LSerror :: addErrorCode('SAMBA_01',array('dependency' => LS_SAMBA_USERPASSWORD_ATTR, 'attr' => 'sambaLMPassword')); LSerror :: addErrorCode(
return; 'SAMBA_01',
array('dependency' => LS_SAMBA_USERPASSWORD_ATTR, 'attr' => 'sambaLMPassword')
);
return false;
} }
if ( if (
@ -286,7 +289,7 @@ function generate_sambaPrimaryGroupSID($ldapObject) {
) )
) { ) {
LSerror :: addErrorCode('SAMBA_05', LS_SAMBA_USERPASSWORD_ATTR); LSerror :: addErrorCode('SAMBA_05', LS_SAMBA_USERPASSWORD_ATTR);
return; return false;
} }
$password = $ldapObject -> attrs[ LS_SAMBA_USERPASSWORD_ATTR ] -> ldap -> getClearPassword(); $password = $ldapObject -> attrs[ LS_SAMBA_USERPASSWORD_ATTR ] -> ldap -> getClearPassword();
@ -294,7 +297,7 @@ function generate_sambaPrimaryGroupSID($ldapObject) {
$sambaLMPassword = $sambapassword -> lmhash($password); $sambaLMPassword = $sambapassword -> lmhash($password);
if($sambaLMPassword == '') { if($sambaLMPassword == '') {
return; return false;
} }
return $sambaLMPassword; return $sambaLMPassword;
} }
@ -306,20 +309,20 @@ function generate_sambaPrimaryGroupSID($ldapObject) {
* *
* @param string $attr The sambaUnixIdPool attribute name that contain next ID value * @param string $attr The sambaUnixIdPool attribute name that contain next ID value
* *
* @return integer UNIX ID value on success, false otherwise * @return string|false UNIX ID value on success, false otherwise
*/ */
function get_samba_unix_pool_next_id($attr) { function get_samba_unix_pool_next_id($attr) {
$unix_id_pool_dn = (defined('LS_SAMBA_UNIX_ID_POOL_DN')?constant('LS_SAMBA_UNIX_ID_POOL_DN'):LS_SAMBA_DOMAIN_OBJECT_DN); $unix_id_pool_dn = (defined('LS_SAMBA_UNIX_ID_POOL_DN')?constant('LS_SAMBA_UNIX_ID_POOL_DN'):LS_SAMBA_DOMAIN_OBJECT_DN);
$unix_id_pool = LSldap :: getLdapEntry ($unix_id_pool_dn); $unix_id_pool = LSldap :: getLdapEntry ($unix_id_pool_dn);
if ($unix_id_pool === false) { if ($unix_id_pool === false) {
LSerror :: addErrorCode('SAMBA_02'); LSerror :: addErrorCode('SAMBA_02');
return; return false;
} }
$next_id = $unix_id_pool->getValue($attr, 'single'); $next_id = $unix_id_pool->getValue($attr, 'single');
if (Net_LDAP2::isError($next_id) || $next_id == '0') { if (Net_LDAP2::isError($next_id) || !is_string($next_id) || $next_id == '0') {
LSerror :: addErrorCode('SAMBA_04', $attr); LSerror :: addErrorCode('SAMBA_04', $attr);
return; return false;
} }
$unix_id_pool->replace(array($attr => (intval($next_id) + 1))); $unix_id_pool->replace(array($attr => (intval($next_id) + 1)));
@ -327,10 +330,8 @@ function get_samba_unix_pool_next_id($attr) {
if(!Net_LDAP2::isError($res)) { if(!Net_LDAP2::isError($res)) {
return $next_id; return $next_id;
} }
else {
LSerror :: addErrorCode('SAMBA_03'); LSerror :: addErrorCode('SAMBA_03');
return; return false;
}
} }
/** /**

View file

@ -111,7 +111,7 @@ LSerror :: defineError('SSH_07',
* ) * )
* @param boolean $sftp Enable SFTP mode (default : false) * @param boolean $sftp Enable SFTP mode (default : false)
* *
* @return mixed SSH2/SFTP object or false * @return SSH2|SFTP|false SSH2/SFTP object or false
*/ */
function connectToSSH($params, $sftp=false) { function connectToSSH($params, $sftp=false) {
$logger = LSlog :: get_logger('LSaddon_ssh'); $logger = LSlog :: get_logger('LSaddon_ssh');
@ -150,7 +150,7 @@ LSerror :: defineError('SSH_07',
$key_content = file_get_contents($key_file_path); $key_content = file_get_contents($key_file_path);
if (!$password -> loadKey($key_content)) { if (!$password -> loadKey($key_content)) {
LSerror :: addErrorCode('SSH_03', $key_file_path); LSerror :: addErrorCode('SSH_03', $key_file_path);
return; return false;
} }
$logger -> debug("Connect on $user@$host:$port (timeout: $timeout sec) with key authentication using file '$key_file_path'."); $logger -> debug("Connect on $user@$host:$port (timeout: $timeout sec) with key authentication using file '$key_file_path'.");
} }
@ -193,9 +193,7 @@ LSerror :: defineError('SSH_07',
*/ */
function createDirsBySFTP($connection_params, $dirs, $chmod=-1, $recursive=false, $continue=false) { function createDirsBySFTP($connection_params, $dirs, $chmod=-1, $recursive=false, $continue=false) {
$cnx = connectToSSH($connection_params, true); $cnx = connectToSSH($connection_params, true);
if (! $cnx){ if (!$cnx instanceof SFTP) return false;
return;
}
if (!is_array($dirs)) { if (!is_array($dirs)) {
$dirs = array($dirs); $dirs = array($dirs);
} }
@ -225,9 +223,7 @@ LSerror :: defineError('SSH_07',
*/ */
function removeDirsBySFTP($connection_params, $dirs, $recursive=false, $continue=false) { function removeDirsBySFTP($connection_params, $dirs, $recursive=false, $continue=false) {
$cnx = connectToSSH($connection_params, true); $cnx = connectToSSH($connection_params, true);
if (! $cnx){ if (!$cnx instanceof SFTP) return false;
return;
}
if (!is_array($dirs)) { if (!is_array($dirs)) {
$dirs = array($dirs); $dirs = array($dirs);
} }
@ -256,13 +252,11 @@ LSerror :: defineError('SSH_07',
*/ */
function renameDirBySFTP($connection_params, $old, $new) { function renameDirBySFTP($connection_params, $old, $new) {
$cnx = connectToSSH($connection_params, true); $cnx = connectToSSH($connection_params, true);
if (! $cnx){ if (!$cnx instanceof SFTP) return false;
return;
}
LSlog :: get_logger('LSaddon_ssh') -> debug("rename($old, $new)"); LSlog :: get_logger('LSaddon_ssh') -> debug("rename($old, $new)");
if (!$cnx -> rename($old, $new)) { if (!$cnx -> rename($old, $new)) {
LSerror :: addErrorCode('SSH_07',array('old' => $old,'new' => $new)); LSerror :: addErrorCode('SSH_07',array('old' => $old,'new' => $new));
return; return false;
} }
return true; return true;
} }
@ -275,15 +269,13 @@ LSerror :: defineError('SSH_07',
* @param array $connection_params Connection parameters * @param array $connection_params Connection parameters
* @param string $cmd The command to run on remote server * @param string $cmd The command to run on remote server
* *
* @return mixed False if connection fail and an array otherwise, with * @return array|false False if connection fail and an array otherwise, with
* exit code as first value and the command outup as second * exit code as first value and the command outup as second
* one (stdout + stderr). * one (stdout + stderr).
*/ */
function execBySSH($connection_params, $cmd) { function execBySSH($connection_params, $cmd) {
$cnx = connectToSSH($connection_params); $cnx = connectToSSH($connection_params);
if (! $cnx){ if (!$cnx instanceof SSH2) return false;
return;
}
LSlog :: get_logger('LSaddon_ssh') -> debug("exec($cmd)"); LSlog :: get_logger('LSaddon_ssh') -> debug("exec($cmd)");
$result = $cnx -> exec($cmd); $result = $cnx -> exec($cmd);
$exit_status = $cnx->getExitStatus(); $exit_status = $cnx->getExitStatus();

View file

@ -112,7 +112,7 @@ function LSaddon_supann_support() {
* *
* @param LSldapObject $ldapObject L'objet ldap * @param LSldapObject $ldapObject L'objet ldap
* *
* @return string Le displayName ou false si il y a un problème durant la génération * @return string|false Le displayName ou false si il y a un problème durant la génération
*/ */
function generate_displayName($ldapObject) { function generate_displayName($ldapObject) {
if ( get_class($ldapObject -> attrs[ $GLOBALS['LS_SUPANN_LASTNAME_ATTR'] ]) != 'LSattribute' ) { if ( get_class($ldapObject -> attrs[ $GLOBALS['LS_SUPANN_LASTNAME_ATTR'] ]) != 'LSattribute' ) {
@ -120,14 +120,14 @@ function generate_displayName($ldapObject) {
'SUPANN_01', 'SUPANN_01',
array('dependency' => $GLOBALS['LS_SUPANN_LASTNAME_ATTR'], 'attr' => 'cn') array('dependency' => $GLOBALS['LS_SUPANN_LASTNAME_ATTR'], 'attr' => 'cn')
); );
return; return false;
} }
if ( get_class($ldapObject -> attrs[ $GLOBALS['LS_SUPANN_FIRSTNAME_ATTR'] ]) != 'LSattribute' ) { if ( get_class($ldapObject -> attrs[ $GLOBALS['LS_SUPANN_FIRSTNAME_ATTR'] ]) != 'LSattribute' ) {
LSerror :: addErrorCode( LSerror :: addErrorCode(
'SUPANN_01', 'SUPANN_01',
array('dependency' => $GLOBALS['LS_SUPANN_FIRSTNAME_ATTR'], 'attr' => 'cn') array('dependency' => $GLOBALS['LS_SUPANN_FIRSTNAME_ATTR'], 'attr' => 'cn')
); );
return; return false;
} }
$noms = $ldapObject -> attrs[ $GLOBALS['LS_SUPANN_LASTNAME_ATTR'] ] -> getValue(); $noms = $ldapObject -> attrs[ $GLOBALS['LS_SUPANN_LASTNAME_ATTR'] ] -> getValue();
@ -143,7 +143,7 @@ function generate_displayName($ldapObject) {
* *
* @param LSldapObject $ldapObject L'objet ldap * @param LSldapObject $ldapObject L'objet ldap
* *
* @return string Le CN ou false si il y a un problème durant la génération * @return string|false Le CN ou false si il y a un problème durant la génération
*/ */
function generate_cn($ldapObject) { function generate_cn($ldapObject) {
if ( get_class($ldapObject -> attrs[ $GLOBALS['LS_SUPANN_LASTNAME_ATTR'] ]) != 'LSattribute' ) { if ( get_class($ldapObject -> attrs[ $GLOBALS['LS_SUPANN_LASTNAME_ATTR'] ]) != 'LSattribute' ) {
@ -151,14 +151,14 @@ function generate_cn($ldapObject) {
'SUPANN_01', 'SUPANN_01',
array('dependency' => $GLOBALS['LS_SUPANN_LASTNAME_ATTR'], 'attr' => 'cn') array('dependency' => $GLOBALS['LS_SUPANN_LASTNAME_ATTR'], 'attr' => 'cn')
); );
return; return false;
} }
if ( get_class($ldapObject -> attrs[ $GLOBALS['LS_SUPANN_FIRSTNAME_ATTR'] ]) != 'LSattribute' ) { if ( get_class($ldapObject -> attrs[ $GLOBALS['LS_SUPANN_FIRSTNAME_ATTR'] ]) != 'LSattribute' ) {
LSerror :: addErrorCode( LSerror :: addErrorCode(
'SUPANN_01', 'SUPANN_01',
array('dependency' => $GLOBALS['LS_SUPANN_FIRSTNAME_ATTR'], 'attr' => 'cn') array('dependency' => $GLOBALS['LS_SUPANN_FIRSTNAME_ATTR'], 'attr' => 'cn')
); );
return; return false;
} }
$noms = $ldapObject -> attrs[ $GLOBALS['LS_SUPANN_LASTNAME_ATTR'] ] -> getValue(); $noms = $ldapObject -> attrs[ $GLOBALS['LS_SUPANN_LASTNAME_ATTR'] ] -> getValue();
@ -175,7 +175,7 @@ function generate_cn($ldapObject) {
* *
* @param LSldapObject $ldapObject L'objet ldap * @param LSldapObject $ldapObject L'objet ldap
* *
* @return array Les valeurs de l'attribut eduPersonOrgUnitDN ou false * @return array|false Les valeurs de l'attribut eduPersonOrgUnitDN ou false
* si il y a un problème durant la génération * si il y a un problème durant la génération
*/ */
function generate_eduPersonOrgUnitDN($ldapObject) { function generate_eduPersonOrgUnitDN($ldapObject) {
@ -184,7 +184,7 @@ function generate_eduPersonOrgUnitDN($ldapObject) {
'SUPANN_01', 'SUPANN_01',
array('dependency' => 'supannEntiteAffectation', 'attr' => 'eduPersonOrgUnitDN') array('dependency' => 'supannEntiteAffectation', 'attr' => 'eduPersonOrgUnitDN')
); );
return; return false;
} }
$affectations = $ldapObject -> attrs[ 'supannEntiteAffectation' ] -> getUpdateData(); $affectations = $ldapObject -> attrs[ 'supannEntiteAffectation' ] -> getUpdateData();
@ -192,7 +192,7 @@ function generate_eduPersonOrgUnitDN($ldapObject) {
$basedn = LSconfig :: get('LSobjects.'.$GLOBALS['LS_SUPANN_LSOBJECT_ENTITE_TYPE'].'.container_dn').','.LSsession::getTopDn(); $basedn = LSconfig :: get('LSobjects.'.$GLOBALS['LS_SUPANN_LSOBJECT_ENTITE_TYPE'].'.container_dn').','.LSsession::getTopDn();
if ($basedn == "") { if ($basedn == "") {
LSerror :: addErrorCode('SUPANN_02','eduPersonOrgUnitDN'); LSerror :: addErrorCode('SUPANN_02','eduPersonOrgUnitDN');
return; return false;
} }
$retval = array(); $retval = array();
@ -211,13 +211,13 @@ function generate_eduPersonOrgUnitDN($ldapObject) {
* *
* @param LSldapObject $ldapObject L'objet ldap * @param LSldapObject $ldapObject L'objet ldap
* *
* @return array La valeur de l'attribut eduPersonPrimaryOrgUnitDN * @return array|false La valeur de l'attribut eduPersonPrimaryOrgUnitDN
* ou false si il y a un problème durant la génération * ou false si il y a un problème durant la génération
*/ */
function generate_eduPersonPrimaryOrgUnitDN($ldapObject) { function generate_eduPersonPrimaryOrgUnitDN($ldapObject) {
if ( get_class($ldapObject -> attrs[ 'supannEntiteAffectationPrincipale' ]) != 'LSattribute' ) { if ( get_class($ldapObject -> attrs[ 'supannEntiteAffectationPrincipale' ]) != 'LSattribute' ) {
LSerror :: addErrorCode('SUPANN_01',array('dependency' => 'supannEntiteAffectationPrincipale', 'attr' => 'eduPersonPrimaryOrgUnitDN')); LSerror :: addErrorCode('SUPANN_01',array('dependency' => 'supannEntiteAffectationPrincipale', 'attr' => 'eduPersonPrimaryOrgUnitDN'));
return; return false;
} }
$affectations = $ldapObject -> attrs[ 'supannEntiteAffectationPrincipale' ] -> getUpdateData(); $affectations = $ldapObject -> attrs[ 'supannEntiteAffectationPrincipale' ] -> getUpdateData();
@ -225,7 +225,7 @@ function generate_eduPersonPrimaryOrgUnitDN($ldapObject) {
$basedn = LSconfig :: get('LSobjects.'.$GLOBALS['LS_SUPANN_LSOBJECT_ENTITE_TYPE'].'.container_dn').','.LSsession::getTopDn(); $basedn = LSconfig :: get('LSobjects.'.$GLOBALS['LS_SUPANN_LSOBJECT_ENTITE_TYPE'].'.container_dn').','.LSsession::getTopDn();
if ($basedn == "") { if ($basedn == "") {
LSerror :: addErrorCode('SUPANN_02','eduPersonPrimaryOrgUnitDN'); LSerror :: addErrorCode('SUPANN_02','eduPersonPrimaryOrgUnitDN');
return; return false;
} }
$retval = array(); $retval = array();
@ -247,13 +247,13 @@ function generate_eduPersonPrimaryOrgUnitDN($ldapObject) {
* *
* @param LSldapObject $ldapObject L'objet ldap * @param LSldapObject $ldapObject L'objet ldap
* *
* @return array La valeur de l'attribut eduPersonOrgDN ou false * @return array|false La valeur de l'attribut eduPersonOrgDN ou false
* si il y a un problème durant la génération * si il y a un problème durant la génération
*/ */
function generate_eduPersonOrgDN($ldapObject) { function generate_eduPersonOrgDN($ldapObject) {
if ( get_class($ldapObject -> attrs[ 'supannEtablissement' ]) != 'LSattribute' ) { if ( get_class($ldapObject -> attrs[ 'supannEtablissement' ]) != 'LSattribute' ) {
LSerror :: addErrorCode('SUPANN_01',array('dependency' => 'supannEtablissement', 'attr' => 'eduPersonOrgDN')); LSerror :: addErrorCode('SUPANN_01',array('dependency' => 'supannEtablissement', 'attr' => 'eduPersonOrgDN'));
return; return false;
} }
$eta = $ldapObject -> attrs[ 'supannEtablissement' ] -> getUpdateData(); $eta = $ldapObject -> attrs[ 'supannEtablissement' ] -> getUpdateData();
@ -279,7 +279,7 @@ function generate_eduPersonOrgDN($ldapObject) {
* *
* @param string $value La valeur * @param string $value La valeur
* *
* @return array Un tableau cle->valeur contenant label et value ou False * @return array|false Un tableau cle->valeur contenant label et value ou False
**/ **/
function supannParseLabeledValue($value) { function supannParseLabeledValue($value) {
if (preg_match('/^\{([^\}]*)\}(.*)$/', $value, $m)) { if (preg_match('/^\{([^\}]*)\}(.*)$/', $value, $m)) {
@ -288,7 +288,7 @@ function supannParseLabeledValue($value) {
'value' => $m[2] 'value' => $m[2]
); );
} }
return; return false;
} }
/** /**
@ -302,13 +302,13 @@ function supannParseLabeledValue($value) {
* *
* @param string $val La valeur composite * @param string $val La valeur composite
* *
* @return array Un tableau contenant key->value ou false en cas d'erreur * @return array|false Un tableau contenant key->value ou false en cas d'erreur
**/ **/
function supannParseCompositeValue($val) { function supannParseCompositeValue($val) {
// Check value is valid // Check value is valid
if (!preg_match('/^(\[[^=]+=[^\]\]]*\])+$/', $val)) { if (!preg_match('/^(\[[^=]+=[^\]\]]*\])+$/', $val)) {
LSlog :: get_logger('LSaddon_supann') -> warning("supannParseCompositeValue($val): invalid value"); LSlog :: get_logger('LSaddon_supann') -> warning("supannParseCompositeValue($val): invalid value");
return; return false;
} }
// Search for components value // Search for components value
@ -319,7 +319,7 @@ function supannParseCompositeValue($val) {
} }
return $parseValue; return $parseValue;
} }
return; return false;
} }
/** /**
@ -344,7 +344,7 @@ function supannParseCompositeValue($val) {
* *
* @param array $val Tableau associatif des valeurs * @param array $val Tableau associatif des valeurs
* *
* @return array Un tableau contenant key->value ou false en cas d'erreur * @return string La valeur composite formatée
**/ **/
function supannFormatCompositeValue($val) { function supannFormatCompositeValue($val) {
$retval = ""; $retval = "";
@ -522,7 +522,7 @@ function supannSearchParrainByPattern($pattern, $max_matches=10) {
* @param string $label L'étiquette de la valeur (optionnel) * @param string $label L'étiquette de la valeur (optionnel)
* @param string $value La valeur * @param string $value La valeur
* *
* @return bool True si valide, False sinon * @return array|false Tableau des informations de la valeur si elle est valide, false sinon
**/ **/
function supannValidateNomenclatureValue($table, $label, $value) { function supannValidateNomenclatureValue($table, $label, $value) {
if (!supannLoadNomenclature($table)) if (!supannLoadNomenclature($table))
@ -565,7 +565,7 @@ function supannValidateNomenclatureValue($table, $label, $value) {
* @param string $label L'étiquette de la valeur (optionnel) * @param string $label L'étiquette de la valeur (optionnel)
* @param string $value La valeur * @param string $value La valeur
* *
* @return array Le label de la valeur. En cas de valeur nor-reconnue, retourne * @return string Le label de la valeur. En cas de valeur nor-reconnue, retourne
* la valeur en spécifiant qu'elle n'est pas reconnue. * la valeur en spécifiant qu'elle n'est pas reconnue.
**/ **/
function supannGetNomenclatureLabel($table, $label, $value) { function supannGetNomenclatureLabel($table, $label, $value) {
@ -834,7 +834,7 @@ function supannDetectCodesPopulations($populations, $prefix="") {
} }
} }
/* /**
* Charge une nomenclature SUPANN * Charge une nomenclature SUPANN
* *
* @param string $pattern La nomenclature à charger * @param string $pattern La nomenclature à charger
@ -1009,7 +1009,7 @@ function supannLoadNomenclature($table) {
* *
* @param LSldapObject $ldapObject L'objet ldap * @param LSldapObject $ldapObject L'objet ldap
* *
* @return array La valeur de l'attribut eduPersonOrgDN ou false * @return string|false La valeur de l'attribut eduPersonOrgDN ou false
* si il y a un problème durant la génération * si il y a un problème durant la génération
*/ */
function generate_eduPersonPrincipalName($ldapObject) { function generate_eduPersonPrincipalName($ldapObject) {
@ -1024,7 +1024,7 @@ function generate_eduPersonPrincipalName($ldapObject) {
* *
* @param LSldapObject $ldapObject L'objet ldap * @param LSldapObject $ldapObject L'objet ldap
* *
* @return array La valeur de l'attribut eduPersonOrgDN ou false * @return string|false La valeur de l'attribut eduPersonOrgDN ou false
* si il y a un problème durant la génération * si il y a un problème durant la génération
*/ */
function generate_eduPersonUniqueId($ldapObject) { function generate_eduPersonUniqueId($ldapObject) {
@ -1222,7 +1222,7 @@ function generate_supannEtuEtape($ldapObject) {
* *
* @param LSldapObject $ldapObject L'objet ldap * @param LSldapObject $ldapObject L'objet ldap
* *
* @return array Les valeurs de l'attribut supannEtuDateFin * @return string|null Les valeurs de l'attribut supannEtuDateFin
*/ */
function generate_supannEtuDateFin($ldapObject) { function generate_supannEtuDateFin($ldapObject) {
$values = generate_from_supannEtuInscription($ldapObject, 'datefin'); $values = generate_from_supannEtuInscription($ldapObject, 'datefin');
@ -1242,17 +1242,25 @@ function generate_supannEtuDateFin($ldapObject) {
LSlog :: get_logger('LSaddon_supann') -> debug( LSlog :: get_logger('LSaddon_supann') -> debug(
"generate_supannEtuDateFin($ldapObject): result = ".varDump($max_time) "generate_supannEtuDateFin($ldapObject): result = ".varDump($max_time)
); );
return $max_time; return $max_time?strval($max_time):null;
} }
if (php_sapi_name() != 'cli') if (php_sapi_name() != 'cli')
return true; return true;
/**
* CLI command to generate Supann codeEtablissement UAI nomenclature
* @param array<string> $command_args Command arguments
* @return bool
*/
function cli_generate_supann_codeEtablissement_uai_nomenclature($command_args) { function cli_generate_supann_codeEtablissement_uai_nomenclature($command_args) {
$data = file_get_contents('https://data.enseignementsup-recherche.gouv.fr/explore/dataset/fr-esr-principaux-etablissements-enseignement-superieur/download?format=json'); $data = file_get_contents('https://data.enseignementsup-recherche.gouv.fr/explore/dataset/fr-esr-principaux-etablissements-enseignement-superieur/download?format=json');
$items = json_decode($data, true); $items = json_decode($data, true);
if (!is_array($items)) if (!is_array($items)) {
LSlog :: get_logger('LSaddon_supann') -> fatal('Fail to retrieve UAI dataset from data.enseignementsup-recherche.gouv.fr'); LSlog :: get_logger('LSaddon_supann') -> fatal(
'Fail to retrieve UAI dataset from data.enseignementsup-recherche.gouv.fr');
return false;
}
$codes = array(); $codes = array();
foreach($items as $item) { foreach($items as $item) {
if (!isset($item['fields']) || !isset($item['fields']['uai']) || !$item['fields']['uai']) if (!isset($item['fields']) || !isset($item['fields']['uai']) || !$item['fields']['uai'])
@ -1260,6 +1268,7 @@ function cli_generate_supann_codeEtablissement_uai_nomenclature($command_args) {
$codes[$item['fields']['uai']] = $item['fields']['uo_lib']; $codes[$item['fields']['uai']] = $item['fields']['uo_lib'];
} }
var_export($codes); var_export($codes);
return true;
} }
LScli :: add_command( LScli :: add_command(

View file

@ -80,7 +80,6 @@ class LSattr_html extends LSlog_staticLoggerClass {
$this -> name = $name; $this -> name = $name;
$this -> config = $config; $this -> config = $config;
$this -> attribute =& $attribute; $this -> attribute =& $attribute;
return true;
} }
/** /**
@ -111,17 +110,17 @@ class LSattr_html extends LSlog_staticLoggerClass {
* @param string $idForm L'identifiant du formulaire * @param string $idForm L'identifiant du formulaire
* @param array|string|null $data Valeur du champs du formulaire * @param array|string|null $data Valeur du champs du formulaire
* *
* @return LSformElement L'element du formulaire ajouté * @return LSformElement|false L'element du formulaire ajouté, ou false
*/ */
public function addToForm (&$form,$idForm,$data=NULL) { public function addToForm (&$form,$idForm,$data=NULL) {
if (!$this -> LSformElement_type) { if (!$this -> LSformElement_type) {
LSerror :: addErrorCode('LSattr_html_01',$this -> name); LSerror :: addErrorCode('LSattr_html_01',$this -> name);
return; return false;
} }
$element=$form -> addElement($this -> LSformElement_type, $this -> name, $this -> getLabel(), $this -> config, $this); $element=$form -> addElement($this -> LSformElement_type, $this -> name, $this -> getLabel(), $this -> config, $this);
if(!$element) { if(!$element) {
LSerror :: addErrorCode('LSform_06',$this -> name); LSerror :: addErrorCode('LSform_06',$this -> name);
return; return false;
} }
if (!is_null($data)) { if (!is_null($data)) {
$data = ensureIsArray($data); $data = ensureIsArray($data);

View file

@ -36,7 +36,7 @@ class LSattr_html_date extends LSattr_html {
* @param string $idForm L'identifiant du formulaire * @param string $idForm L'identifiant du formulaire
* @param array|string|null $data Valeur du champs du formulaire * @param array|string|null $data Valeur du champs du formulaire
* *
* @return LSformElement_date L'element du formulaire ajouté * @return LSformElement_date|false L'element du formulaire ajouté
*/ */
function addToForm (&$form,$idForm,$data=NULL) { function addToForm (&$form,$idForm,$data=NULL) {
$element = parent::addToForm($form,$idForm,$data); $element = parent::addToForm($form,$idForm,$data);
@ -51,7 +51,7 @@ class LSattr_html_date extends LSattr_html {
) )
) )
); );
return $element; return (is_a($element, 'LSformElement_date')?$element:false);
} }
} }

View file

@ -235,18 +235,19 @@ class LSattr_html_select_list extends LSattr_html{
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return array Tableau associatif des valeurs possible de la liste avec en clé * @return array|false Tableau associatif des valeurs possible de la liste avec en clé
* la valeur des balises option et en valeur ce qui sera affiché. * la valeur des balises option et en valeur ce qui sera affiché.
* False en cas d'erreur.
*/ */
protected static function getLSobjectPossibleValues($conf, $options, $name) { protected static function getLSobjectPossibleValues($conf, $options, $name) {
$retInfos = array(); $retInfos = array();
if ((!isset($conf['object_type'])) || ((!isset($conf['value_attribute'])) && (!isset($conf['values_attribute'])))) { if ((!isset($conf['object_type'])) || ((!isset($conf['value_attribute'])) && (!isset($conf['values_attribute'])))) {
LSerror :: addErrorCode('LSattr_html_select_list_01',$name); LSerror :: addErrorCode('LSattr_html_select_list_01',$name);
return; return false;
} }
if (!LSsession :: loadLSclass('LSsearch')) { if (!LSsession :: loadLSclass('LSsearch')) {
return; return false;
} }
$param=array( $param=array(

View file

@ -43,14 +43,14 @@ class LSattr_html_select_object extends LSattr_html{
* @param string $idForm L'identifiant du formulaire * @param string $idForm L'identifiant du formulaire
* @param array|string|null $data Valeur du champs du formulaire * @param array|string|null $data Valeur du champs du formulaire
* *
* @return LSformElement L'element du formulaire ajouté * @return LSformElement|false L'element du formulaire ajouté, ou false
*/ */
public function addToForm (&$form,$idForm,$data=NULL) { public function addToForm (&$form,$idForm,$data=NULL) {
$this -> config['attrObject'] = $this; $this -> config['attrObject'] = $this;
$element=$form -> addElement($this -> LSformElement_type, $this -> name, $this -> getLabel(), $this -> config, $this); $element=$form -> addElement($this -> LSformElement_type, $this -> name, $this -> getLabel(), $this -> config, $this);
if(!$element) { if(!$element) {
LSerror :: addErrorCode('LSform_06',$this -> name); LSerror :: addErrorCode('LSform_06',$this -> name);
return; return false;
} }
if ($data) { if ($data) {
$values = $this -> getFormValues(ensureIsArray($data)); $values = $this -> getFormValues(ensureIsArray($data));
@ -69,7 +69,7 @@ class LSattr_html_select_object extends LSattr_html{
* *
* @param mixed $data The attribute value (liste de DNs) * @param mixed $data The attribute value (liste de DNs)
* *
* @return mixed La valeur formatée de l'attribut (array('DNs' => 'displayName')) * @return array La valeur formatée de l'attribut (array('DNs' => 'displayName'))
**/ **/
public function refreshForm($data,$fromDNs=false) { public function refreshForm($data,$fromDNs=false) {
return $this -> getFormValues($data,$fromDNs); return $this -> getFormValues($data,$fromDNs);
@ -368,8 +368,8 @@ class LSattr_html_select_object extends LSattr_html{
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return array Tableau associatif des objects selectionnés avec en clé * @return array|false Tableau associatif des objects selectionnés avec en clé
* le DN et en valeur ce qui sera affiché. * le DN et en valeur ce qui sera affiché. False en cas d'erreur.
*/ */
public function getValuesFromLSselect() { public function getValuesFromLSselect() {
$LSselect_id = $this -> getLSselectId(); $LSselect_id = $this -> getLSselectId();

View file

@ -57,14 +57,11 @@ class LSattr_ldap extends LSlog_staticLoggerClass {
* @param string $name Nom de l'attribut ldap * @param string $name Nom de l'attribut ldap
* @param array $config Configuration de l'objet * @param array $config Configuration de l'objet
* @param LSattribute &$attribute L'objet LSattribut parent * @param LSattribute &$attribute L'objet LSattribut parent
*
* @return boolean Retourne true.
*/ */
public function __construct($name, $config, &$attribute) { public function __construct($name, $config, &$attribute) {
$this -> name = $name; $this -> name = $name;
$this -> config = $config; $this -> config = $config;
$this -> attribute =& $attribute; $this -> attribute =& $attribute;
return true;
} }
/** /**
@ -111,7 +108,7 @@ class LSattr_ldap extends LSlog_staticLoggerClass {
if ($this -> attribute -> data != $data) { if ($this -> attribute -> data != $data) {
return true; return true;
} }
return; return false;
} }
/** /**

View file

@ -30,14 +30,14 @@ class LSattr_ldap_boolean extends LSattr_ldap {
* *
* @param mixed $data Attribute data * @param mixed $data Attribute data
* *
* @return mixed Attribute display value * @return string|null Attribute display value
**/ **/
public function getDisplayValue($data) { public function getDisplayValue($data) {
if ($this -> isTrue($data)) if ($this -> isTrue($data))
return 'yes'; return 'yes';
if ($this -> isFalse($data)) if ($this -> isFalse($data))
return 'no'; return 'no';
return; return null;
} }
/** /**
@ -45,7 +45,7 @@ class LSattr_ldap_boolean extends LSattr_ldap {
* *
* @param mixed $data Attribute data * @param mixed $data Attribute data
* *
* @return mixed Attribute data * @return array Attribute data
**/ **/
public function getUpdateData($data) { public function getUpdateData($data) {
$data = ensureIsArray($data); $data = ensureIsArray($data);

View file

@ -34,7 +34,7 @@ class LSattr_ldap_compositeValueToJSON extends LSattr_ldap {
* *
* @param mixed $data The attribute value * @param mixed $data The attribute value
* *
* @return mixed The display value of the attribute * @return array The display value of the attribute
*/ */
public function getDisplayValue($data) { public function getDisplayValue($data) {
$ret = array(); $ret = array();
@ -48,7 +48,7 @@ class LSattr_ldap_compositeValueToJSON extends LSattr_ldap {
* *
* @param mixed $data The attribute value * @param mixed $data The attribute value
* *
* @return mixed The processed attribute value * @return array The processed attribute value
*/ */
public function getUpdateData($data) { public function getUpdateData($data) {
$ret = array(); $ret = array();
@ -70,7 +70,7 @@ class LSattr_ldap_compositeValueToJSON extends LSattr_ldap {
} }
return $parseValue; return $parseValue;
} }
return; return null;
} }
/** /**

View file

@ -31,7 +31,7 @@ class LSattr_ldap_date extends LSattr_ldap {
* *
* @param mixed $data The attribute value * @param mixed $data The attribute value
* *
* @return mixed The display value of the attribute * @return array The display value of the attribute
*/ */
public function getDisplayValue($data) { public function getDisplayValue($data) {
$data = ensureIsArray($data); $data = ensureIsArray($data);
@ -53,7 +53,7 @@ class LSattr_ldap_date extends LSattr_ldap {
* *
* @param mixed $data The attribute value * @param mixed $data The attribute value
* *
* @return mixed The processed attribute value * @return array The processed attribute value
*/ */
public function getUpdateData($data) { public function getUpdateData($data) {
$data = ensureIsArray($data); $data = ensureIsArray($data);

View file

@ -33,7 +33,7 @@ class LSattr_ldap_naiveDate extends LSattr_ldap {
* *
* @param mixed $data The LDAP attribute value * @param mixed $data The LDAP attribute value
* *
* @return mixed The display value ot the attribute * @return array The display value ot the attribute
*/ */
public function getDisplayValue($data) { public function getDisplayValue($data) {
$retval = array(); $retval = array();
@ -58,7 +58,7 @@ class LSattr_ldap_naiveDate extends LSattr_ldap {
* *
* @param mixed $data The value of the attribute * @param mixed $data The value of the attribute
* *
* @return mixed The LDAP value of the attribute * @return array The LDAP value of the attribute
*/ */
public function getUpdateData($data) { public function getUpdateData($data) {
$retval = array(); $retval = array();
@ -75,7 +75,7 @@ class LSattr_ldap_naiveDate extends LSattr_ldap {
* @return string the storage format of the date * @return string the storage format of the date
**/ **/
public function getFormat() { public function getFormat() {
return $this -> getConfig('ldap_options.format', "%Y%m%d%H%M%SZ"); return $this -> getConfig('ldap_options.format', "%Y%m%d%H%M%SZ", 'string');
} }
} }

View file

@ -61,11 +61,18 @@ class LSattr_ldap_pwdHistory extends LSattr_ldap {
return $ret; return $ret;
} }
/**
* Parse value
*
* @param array|string|null $value The value to parse
*
* @return array|false Array of parsed value info as array, or false
**/
public function parseValue($value) { public function parseValue($value) {
$parts = explode('#', $value); $parts = explode('#', $value);
if (!is_array($parts) || count($parts) != 4) { if (!is_array($parts) || count($parts) != 4) {
self :: log_warning($this."->parseValue($value): Invalid value (parts count != 4)."); self :: log_warning($this."->parseValue($value): Invalid value (parts count != 4).");
return; return false;
} }
$datetime = date_create_from_format('YmdHisO', $parts[0]); $datetime = date_create_from_format('YmdHisO', $parts[0]);
if ($datetime instanceof DateTime) { if ($datetime instanceof DateTime) {
@ -87,17 +94,17 @@ class LSattr_ldap_pwdHistory extends LSattr_ldap {
/** /**
* Encode a value * Encode a value
* @param array $value The value to encode * @param array $value The value to encode
* @return string The encoded value * @return string|false The encoded value, or false
*/ */
public function encodeValue($value) { public function encodeValue($value) {
if (!is_array($value)) { if (!is_array($value)) {
self :: log_warning($this."->encodeValue($value): Provided value is not an array."); self :: log_warning($this."->encodeValue($value): Provided value is not an array.");
return; return false;
} }
$datetime = date_create_from_format('YmdHisO', $value['time']); $datetime = date_create_from_format('YmdHisO', $value['time']);
if (!is_a($datetime, 'DateTime')) { if (!is_a($datetime, 'DateTime')) {
self :: log_warning($this."->encodeValue(".varDump($value)."): Fail to create DateTime object from timestamp '".varDump($value['time'])."'."); self :: log_warning($this."->encodeValue(".varDump($value)."): Fail to create DateTime object from timestamp '".varDump($value['time'])."'.");
return; return false;
} }
$datetime -> setTimezone('UTC'); $datetime -> setTimezone('UTC');
$datetime_string = $datetime -> format('YmdHisO'); $datetime_string = $datetime -> format('YmdHisO');

View file

@ -58,7 +58,7 @@ class LSattr_ldap_sambaAcctFlags extends LSattr_ldap {
* *
* @param array|string|null $data Attribute data * @param array|string|null $data Attribute data
* *
* @return array Array of enabled flags * @return array|false Array of enabled flags, or false
**/ **/
public static function parse_flags($data) { public static function parse_flags($data) {
if (!$data) if (!$data)
@ -66,7 +66,7 @@ class LSattr_ldap_sambaAcctFlags extends LSattr_ldap {
$data = ensureIsArray($data); $data = ensureIsArray($data);
if (count($data) > 1) { if (count($data) > 1) {
LSerror :: addErrorCode('LSattr_ldap_sambaAcctFlags_01'); LSerror :: addErrorCode('LSattr_ldap_sambaAcctFlags_01');
return; return false;
} }
$value = $data[0]; $value = $data[0];
$preg_pattern = "/^\[([ "; $preg_pattern = "/^\[([ ";
@ -78,7 +78,7 @@ class LSattr_ldap_sambaAcctFlags extends LSattr_ldap {
if (!preg_match($preg_pattern, $value, $m)) { if (!preg_match($preg_pattern, $value, $m)) {
self :: log_error("parse($value): fail to parse value."); self :: log_error("parse($value): fail to parse value.");
LSerror :: addErrorCode('LSattr_ldap_sambaAcctFlags_02'); LSerror :: addErrorCode('LSattr_ldap_sambaAcctFlags_02');
return; return false;
} }
$flags = array(); $flags = array();
foreach(str_split($m[1]) as $flag) { foreach(str_split($m[1]) as $flag) {
@ -96,14 +96,14 @@ class LSattr_ldap_sambaAcctFlags extends LSattr_ldap {
* *
* @param array $flags of string Flags * @param array $flags of string Flags
* *
* @return array Array of LDAP attribute value * @return array|false Array of LDAP attribute value, or false
**/ **/
public static function format_flags($flags) { public static function format_flags($flags) {
$flags = ensureIsArray($flags); $flags = ensureIsArray($flags);
foreach($flags as $flag) { foreach($flags as $flag) {
if (!self :: check_flag($flag)) { if (!self :: check_flag($flag)) {
LSerror :: addErrorCode('LSattr_ldap_sambaAcctFlags_03', $flag); LSerror :: addErrorCode('LSattr_ldap_sambaAcctFlags_03', $flag);
return; return false;
} }
} }
// Add some space if need // Add some space if need

View file

@ -69,7 +69,7 @@ class LSattribute extends LSlog_staticLoggerClass {
* Attribute data * Attribute data
* @var array * @var array
*/ */
var array $data; var array $data = array();
/** /**
* Attribute updated data * Attribute updated data
@ -157,7 +157,6 @@ class LSattribute extends LSlog_staticLoggerClass {
); );
return; return;
} }
return true;
} }
/** /**
@ -174,7 +173,7 @@ class LSattribute extends LSlog_staticLoggerClass {
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return string Le label de l'attribut * @return string|false Le label de l'attribut, ou false
* *
* @see LSattr_html::getLabel() * @see LSattr_html::getLabel()
*/ */
@ -182,7 +181,7 @@ class LSattribute extends LSlog_staticLoggerClass {
public function getLabel() { public function getLabel() {
if (!$this -> html) { if (!$this -> html) {
LSerror :: addErrorCode('LSattribute_09',array('type' => 'html','name' => $this -> name)); LSerror :: addErrorCode('LSattribute_09',array('type' => 'html','name' => $this -> name));
return; return false;
} }
return $this -> html -> getLabel(); return $this -> html -> getLabel();
} }
@ -254,7 +253,7 @@ class LSattribute extends LSlog_staticLoggerClass {
public function getDisplayValue($data=false) { public function getDisplayValue($data=false) {
if (!$this -> ldap) { if (!$this -> ldap) {
LSerror :: addErrorCode('LSattribute_09',array('type' => 'ldap','name' => $this -> name)); LSerror :: addErrorCode('LSattribute_09',array('type' => 'ldap','name' => $this -> name));
return; return false;
} }
if ($data !== false) { if ($data !== false) {
@ -276,7 +275,7 @@ class LSattribute extends LSlog_staticLoggerClass {
} }
else { else {
LSerror :: addErrorCode('LSattribute_02', array('attr' => $this->name, 'func' => $func)); LSerror :: addErrorCode('LSattribute_02', array('attr' => $this->name, 'func' => $func));
return; return false;
} }
} }
return $result; return $result;
@ -336,7 +335,7 @@ class LSattribute extends LSlog_staticLoggerClass {
// Check rule // Check rule
if(!is_empty($rule) && !$form -> isRuleRegistered($rule)) { if(!is_empty($rule) && !$form -> isRuleRegistered($rule)) {
LSerror :: addErrorCode('LSattribute_03', array('attr' => $this->name, 'rule' => $rule)); LSerror :: addErrorCode('LSattribute_03', array('attr' => $this->name, 'rule' => $rule));
return; return false;
} }
// Add rule to form // Add rule to form
$form -> addRule($this -> name, $rule, (is_array($rule_options)?$rule_options:array())); $form -> addRule($this -> name, $rule, (is_array($rule_options)?$rule_options:array()));
@ -437,7 +436,7 @@ class LSattribute extends LSlog_staticLoggerClass {
private function _addToForm(&$form, $idForm, &$obj=NULL, $data=NULL) { private function _addToForm(&$form, $idForm, &$obj=NULL, $data=NULL) {
if (!$this -> html) { if (!$this -> html) {
LSerror :: addErrorCode('LSattribute_09',array('type' => 'html','name' => $this -> name)); LSerror :: addErrorCode('LSattribute_09',array('type' => 'html','name' => $this -> name));
return; return false;
} }
if (is_null($data)) { if (is_null($data)) {
@ -452,7 +451,7 @@ class LSattribute extends LSlog_staticLoggerClass {
$element = $this -> html -> addToForm($form, $idForm, $data); $element = $this -> html -> addToForm($form, $idForm, $data);
if(!$element instanceof LSformElement) { if(!$element instanceof LSformElement) {
LSerror :: addErrorCode('LSform_06',$this -> name); LSerror :: addErrorCode('LSform_06',$this -> name);
return; return false;
} }
return $element; return $element;
} }
@ -471,7 +470,7 @@ class LSattribute extends LSlog_staticLoggerClass {
if ($this -> getConfig("form.$idForm") && ($this -> myRights() != 'n')) { if ($this -> getConfig("form.$idForm") && ($this -> myRights() != 'n')) {
if (!$this -> html) { if (!$this -> html) {
LSerror :: addErrorCode('LSattribute_09',array('type' => 'html','name' => $this -> name)); LSerror :: addErrorCode('LSattribute_09',array('type' => 'html','name' => $this -> name));
return; return false;
} }
$form_element = $form -> getElement($this -> name); $form_element = $form -> getElement($this -> name);
if ($form_element) { if ($form_element) {
@ -599,7 +598,7 @@ class LSattribute extends LSlog_staticLoggerClass {
self :: log_debug($this."generateValue(): generated values = ".varDump($this -> updateData)); self :: log_debug($this."generateValue(): generated values = ".varDump($this -> updateData));
return true; return true;
} }
return; return false;
} }
/** /**
@ -612,7 +611,7 @@ class LSattribute extends LSlog_staticLoggerClass {
*/ */
public function getUpdateData() { public function getUpdateData() {
if (!$this -> isUpdate()) { if (!$this -> isUpdate()) {
return; return null;
} }
if ( $this -> _finalUpdateData ) { if ( $this -> _finalUpdateData ) {
return $this -> _finalUpdateData; return $this -> _finalUpdateData;
@ -627,7 +626,7 @@ class LSattribute extends LSlog_staticLoggerClass {
} }
else { else {
LSerror :: addErrorCode('LSattribute_05',array('attr' => $this->name,'func' => $func)); LSerror :: addErrorCode('LSattribute_05',array('attr' => $this->name,'func' => $func));
return; return false;
} }
} }
} }
@ -637,14 +636,14 @@ class LSattribute extends LSlog_staticLoggerClass {
} }
else { else {
LSerror :: addErrorCode('LSattribute_05',array('attr' => $this->name,'func' => $this -> config['onSave'])); LSerror :: addErrorCode('LSattribute_05',array('attr' => $this->name,'func' => $this -> config['onSave']));
return; return false;
} }
} }
} }
else { else {
if (!$this -> ldap) { if (!$this -> ldap) {
LSerror :: addErrorCode('LSattribute_09',array('type' => 'ldap','name' => $this -> name)); LSerror :: addErrorCode('LSattribute_09',array('type' => 'ldap','name' => $this -> name));
return; return false;
} }
else { else {
$result = $this -> ldap -> getUpdateData($data); $result = $this -> ldap -> getUpdateData($data);
@ -659,13 +658,13 @@ class LSattribute extends LSlog_staticLoggerClass {
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return mixed La configuration de validation de l'attribut * @return array|null La configuration de validation de l'attribut
*/ */
public function getValidateConfig() { public function getValidateConfig() {
if (isset($this -> config['validation'])) { if (isset($this -> config['validation'])) {
return $this -> config['validation']; return $this -> config['validation'];
} }
return; return null;
} }
/** /**

View file

@ -43,6 +43,10 @@ class LSauth extends LSlog_staticLoggerClass {
'displaySelfAccess' => true 'displaySelfAccess' => true
); );
/**
* Start authentication
* @return bool
*/
public static function start() { public static function start() {
self :: log_debug('start()'); self :: log_debug('start()');
// Load Config // Load Config
@ -51,7 +55,7 @@ class LSauth extends LSlog_staticLoggerClass {
} }
if (!LSsession :: loadLSclass('LSauthMethod')) { if (!LSsession :: loadLSclass('LSauthMethod')) {
self :: log_debug('Failed to load LSauthMethod class'); self :: log_debug('Failed to load LSauthMethod class');
return; return false;
} }
$api_mode = LSsession :: get('api_mode'); $api_mode = LSsession :: get('api_mode');
if ($api_mode) if ($api_mode)
@ -63,22 +67,26 @@ class LSauth extends LSlog_staticLoggerClass {
if (LSsession :: loadLSclass($class)) { if (LSsession :: loadLSclass($class)) {
if ($api_mode && !$class :: apiModeSupported()) { if ($api_mode && !$class :: apiModeSupported()) {
LSerror :: addErrorCode('LSauth_08', self :: $method); LSerror :: addErrorCode('LSauth_08', self :: $method);
return; return false;
} }
self :: $provider = new $class(); self :: $provider = new $class();
if (!self :: $provider) { if (!self :: $provider) {
LSerror :: addErrorCode('LSauth_05', self :: $method); LSerror :: addErrorCode('LSauth_05', self :: $method);
return; return false;
} }
self :: log_debug('Provider Started !'); self :: log_debug('Provider Started !');
return true; return true;
} }
else { else {
LSerror :: addErrorCode('LSauth_04', self :: $method); LSerror :: addErrorCode('LSauth_04', self :: $method);
return; return false;
} }
} }
/**
* Force user authentication
* @return LSldapObject|false
*/
public static function forceAuthentication() { public static function forceAuthentication() {
self :: log_debug('LSauth :: forceAuthentication()'); self :: log_debug('LSauth :: forceAuthentication()');
if (!is_null(self :: $provider)) { if (!is_null(self :: $provider)) {
@ -89,10 +97,10 @@ class LSauth extends LSlog_staticLoggerClass {
} }
// No data : user has not filled the login form // No data : user has not filled the login form
self :: log_debug('No data -> user has not filled the login form'); self :: log_debug('No data -> user has not filled the login form');
return; return false;
} }
LSerror :: addErrorCode('LSauth_06'); LSerror :: addErrorCode('LSauth_06');
return; return false;
} }
/** /**
@ -226,14 +234,14 @@ class LSauth extends LSlog_staticLoggerClass {
/** /**
* Logout * Logout
* *
* @return void * @return bool
**/ **/
public static function logout() { public static function logout() {
if (!is_null(self :: $provider)) { if (!is_null(self :: $provider)) {
return self :: $provider -> logout(); return self :: $provider -> logout();
} }
LSerror :: addErrorCode('LSauth_06'); LSerror :: addErrorCode('LSauth_06');
return; return false;
} }
/** /**
@ -245,11 +253,10 @@ class LSauth extends LSlog_staticLoggerClass {
* @return void * @return void
**/ **/
public static function afterLogout() { public static function afterLogout() {
if (!is_null(self :: $provider)) { if (!is_null(self :: $provider))
return self :: $provider -> afterLogout(); self :: $provider -> afterLogout();
} else
LSerror :: addErrorCode('LSauth_06'); LSerror :: addErrorCode('LSauth_06');
return;
} }
/** /**

View file

@ -98,7 +98,7 @@ class LSauthMethod extends LSlog_staticLoggerClass {
* @return void * @return void
**/ **/
public static function afterLogout() { public static function afterLogout() {
return true; return;
} }
/** /**

View file

@ -106,7 +106,7 @@ class LSauthMethod_CAS extends LSauthMethod {
self :: log_debug('LSauthMethod_CAS : auth data : '.varDump($this -> authData)); self :: log_debug('LSauthMethod_CAS : auth data : '.varDump($this -> authData));
return $this -> authData; return $this -> authData;
} }
return; return false;
} }
/** /**
@ -125,7 +125,7 @@ class LSauthMethod_CAS extends LSauthMethod {
else else
self :: log_warning("LSauthMethod_CAS :: logout() : logout is disabled"); self :: log_warning("LSauthMethod_CAS :: logout() : logout is disabled");
} }
return; return false;
} }
} }

View file

@ -137,7 +137,6 @@ class LSauthMethod_HTTP extends LSauthMethod_basic {
LSurl :: redirect(LSAUTHMETHOD_HTTP_LOGOUT_REMOTE_URL); LSurl :: redirect(LSAUTHMETHOD_HTTP_LOGOUT_REMOTE_URL);
} }
self :: log_debug('No logout remote URL configured'); self :: log_debug('No logout remote URL configured');
return true;
} }
} }

View file

@ -42,7 +42,7 @@ class LSauthMethod_basic extends LSauthMethod {
); );
return $this -> authData; return $this -> authData;
} }
return; return false;
} }
/** /**

View file

@ -59,7 +59,7 @@ class LScli extends LSlog_staticLoggerClass {
* @param boolean $override Allow override if a command already exists with the same name (optional, * @param boolean $override Allow override if a command already exists with the same name (optional,
* default: false) * default: false)
* *
* @return void * @return bool
**/ **/
public static function add_command($command, $handler, $short_desc, $usage_args=false, $long_desc=false, public static function add_command($command, $handler, $short_desc, $usage_args=false, $long_desc=false,
$need_ldap_con=true, $args_autocompleter=null, $override=false) { $need_ldap_con=true, $args_autocompleter=null, $override=false) {
@ -272,12 +272,12 @@ class LScli extends LSlog_staticLoggerClass {
* @param string $command The command arguments (optional, default: array()) * @param string $command The command arguments (optional, default: array())
* @param boolean $exit If true, function will exit after command execution (optional, default: true) * @param boolean $exit If true, function will exit after command execution (optional, default: true)
* *
* @return void|boolean If $exit is False, return boolean casted command return * @return boolean If $exit is False, return boolean casted command return, otherwise exit with 1 on error and 0 otherwise
**/ **/
public static function run_command($command, $command_args=array(), $exit=true) { public static function run_command($command, $command_args=array(), $exit=true) {
if (php_sapi_name() != "cli") { if (php_sapi_name() != "cli") {
self :: log_fatal('Try to use LScli :: run_command() in non-CLI context.'); self :: log_fatal('Try to use LScli :: run_command() in non-CLI context.');
return; return false;
} }
if (!array_key_exists($command, self :: $commands)) { if (!array_key_exists($command, self :: $commands)) {
self :: log_warning("LScli :: run_command() : invalid command '$command'."); self :: log_warning("LScli :: run_command() : invalid command '$command'.");
@ -329,7 +329,7 @@ class LScli extends LSlog_staticLoggerClass {
* (optional, default: null = use current PHP * (optional, default: null = use current PHP
* process working directory) * process working directory)
* *
* @return false|array An array of return code, stdout and stderr result or False in case of fatal error * @return array|false An array of return code, stdout and stderr result or False in case of fatal error
**/ **/
public static function run_external_command($command, $data_stdin=null, $escape_command_args=true, $cwd=null) { public static function run_external_command($command, $data_stdin=null, $escape_command_args=true, $cwd=null) {
if (array($command)) if (array($command))
@ -400,10 +400,10 @@ class LScli extends LSlog_staticLoggerClass {
**/ **/
public static function bash_autocomplete($command_args) { public static function bash_autocomplete($command_args) {
if (count($command_args) < 3) if (count($command_args) < 3)
return; return false;
$comp_word_num = intval($command_args[0]); $comp_word_num = intval($command_args[0]);
if ($comp_word_num <= 0) return; if ($comp_word_num <= 0) return false;
if ($command_args[1] != '--') return; if ($command_args[1] != '--') return false;
$comp_words = array_slice($command_args, 2); $comp_words = array_slice($command_args, 2);
$comp_word = (isset($comp_words[$comp_word_num])?$comp_words[$comp_word_num]:''); $comp_word = (isset($comp_words[$comp_word_num])?$comp_words[$comp_word_num]:'');

View file

@ -48,7 +48,7 @@ class LSconfig {
$files=array('config.inc.php','config.LSaddons.php'); $files=array('config.inc.php','config.LSaddons.php');
foreach($files as $file) { foreach($files as $file) {
if (!LSsession::includeFile(LS_CONF_DIR.'/'.$file)) { if (!LSsession::includeFile(LS_CONF_DIR.'/'.$file)) {
return; return false;
} }
} }
if (is_array($GLOBALS['LSconfig'])) { if (is_array($GLOBALS['LSconfig'])) {
@ -56,7 +56,7 @@ class LSconfig {
self :: $data['LSaddons'] = $GLOBALS['LSaddons']; self :: $data['LSaddons'] = $GLOBALS['LSaddons'];
return true; return true;
} }
return; return false;
} }
/** /**

View file

@ -31,7 +31,7 @@ class LSerror {
/** /**
* Registered error codes * Registered error codes
* @var array<string,array> * @var array<string|int,array>
*/ */
private static $_errorCodes = array( private static $_errorCodes = array(
'0' => array('msg' => "%{msg}") '0' => array('msg' => "%{msg}")
@ -87,34 +87,14 @@ class LSerror {
* (default), LSerrors template variable will be assigned * (default), LSerrors template variable will be assigned
* with errors message. * with errors message.
* *
* @return string|null * @return array|null
*/ */
public static function display($return=False) { public static function display($return=False) {
$errors = self :: getErrors(); $errors = self :: getErrors();
if ($errors && $return) if ($errors && $return)
return $errors; return $errors;
LStemplate :: assign('LSerrors', base64_encode(json_encode($errors))); LStemplate :: assign('LSerrors', base64_encode(json_encode($errors)));
return; return null;
}
/**
* Print errors and stop LdapSaisie
*
* @author Benjamin Renard <brenard@easter-eggs.com>
*
* @param string $code Error code (see addErrorCode())
* @param string $msg Error msg (see addErrorCode())
* @param boolean $escape (see addErrorCode())
*
* @return void
*/
public static function stop($code='-1', $msg='', $escape=true) {
if(!empty($_SESSION['LSerror'])) {
print "<h1>"._('Errors')."</h1>\n";
print self :: display(true);
}
print "<h1>"._('Stop')."</h1>\n";
exit (self :: formatError($code, $msg, $escape));
} }
/** /**
@ -122,7 +102,7 @@ class LSerror {
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return string Le texte des erreurs * @return array Array of formated error messages
*/ */
public static function getErrors() { public static function getErrors() {
$return = ( $return = (

View file

@ -175,7 +175,7 @@ class LSform extends LSlog_staticLoggerClass {
$this -> submit = ($submit?$submit:_("Validate")); $this -> submit = ($submit?$submit:_("Validate"));
$this -> api_mode = $api_mode; $this -> api_mode = $api_mode;
$this -> ldapObject =& $ldapObject; $this -> ldapObject =& $ldapObject;
$this -> config = $ldapObject -> getConfig('LSform'); $this -> config = $ldapObject -> getConfig('LSform', array(), 'array');
LSsession :: loadLSclass('LSformElement'); LSsession :: loadLSclass('LSformElement');
} }
@ -305,7 +305,7 @@ class LSform extends LSlog_staticLoggerClass {
LStemplate :: assign('LSform_submittxt',$this -> submit); LStemplate :: assign('LSform_submittxt',$this -> submit);
} }
/* /**
* Méthode chargeant les dépendances d'affichage d'une LSview * Méthode chargeant les dépendances d'affichage d'une LSview
* *
* @return void * @return void
@ -441,19 +441,19 @@ class LSform extends LSlog_staticLoggerClass {
*/ */
public function validate($onlyIfPresent=false){ public function validate($onlyIfPresent=false){
if(!$this -> can_validate) if(!$this -> can_validate)
return; return false;
if ($this -> isSubmit()) { if ($this -> isSubmit()) {
if (!$this -> getPostData($onlyIfPresent)) { if (!$this -> getPostData($onlyIfPresent)) {
LSerror :: addErrorCode('LSform_01'); LSerror :: addErrorCode('LSform_01');
return; return false;
} }
// Check getPostData do not trigger fields errors // Check getPostData do not trigger fields errors
if(!$this -> can_validate) if(!$this -> can_validate)
return; return false;
$this -> setValuesFromPostData(); $this -> setValuesFromPostData();
//Validation des données ici !!! /// //Validation des données ici !!! ///
if (!$this -> checkData()) { if (!$this -> checkData()) {
return; return false;
} }
LSdebug("Data are checked up"); LSdebug("Data are checked up");
$this -> _isValidate = true; $this -> _isValidate = true;
@ -521,7 +521,7 @@ class LSform extends LSlog_staticLoggerClass {
if (!is_empty($val)) if (!is_empty($val))
return true; return true;
} }
return; return false;
} }
/** /**
@ -536,7 +536,7 @@ class LSform extends LSlog_staticLoggerClass {
return true; return true;
if( (isset($_POST['validate']) && ($_POST['validate']=='LSform')) && (isset($_POST['idForm']) && ($_POST['idForm'] == $this -> idForm)) ) if( (isset($_POST['validate']) && ($_POST['validate']=='LSform')) && (isset($_POST['idForm']) && ($_POST['idForm'] == $this -> idForm)) )
return true; return true;
return; return false;
} }
/** /**
@ -574,7 +574,7 @@ class LSform extends LSlog_staticLoggerClass {
return true; return true;
} }
return; return false;
} }
/** /**
@ -591,7 +591,7 @@ class LSform extends LSlog_staticLoggerClass {
foreach($this -> elements as $element_name => $element) { foreach($this -> elements as $element_name => $element) {
if( !($element -> getPostData($this -> _postData, $onlyIfPresent)) ) { if( !($element -> getPostData($this -> _postData, $onlyIfPresent)) ) {
LSerror :: addErrorCode('LSform_02',$element_name); LSerror :: addErrorCode('LSform_02',$element_name);
return; return false;
} }
} }
} }
@ -627,7 +627,7 @@ class LSform extends LSlog_staticLoggerClass {
// Retrieve POST data of the element // Retrieve POST data of the element
if( !($element -> getPostData($this -> _postData, $onlyIfPresent)) ) { if( !($element -> getPostData($this -> _postData, $onlyIfPresent)) ) {
LSerror :: addErrorCode('LSform_02',$elementName); LSerror :: addErrorCode('LSform_02',$elementName);
return; return false;
} }
} }
} }
@ -645,14 +645,14 @@ class LSform extends LSlog_staticLoggerClass {
* @param array $params Paramètres supplémentaires * @param array $params Paramètres supplémentaires
* @param LSattr_html &$attr_html The related LSattr_html * @param LSattr_html &$attr_html The related LSattr_html
* *
* @return LSformElement * @return LSformElement|false The LSformElement on success, false otherwise
*/ */
public function addElement($type,$name,$label,$params,&$attr_html) { public function addElement($type,$name,$label,$params,&$attr_html) {
$elementType='LSformElement_'.$type; $elementType='LSformElement_'.$type;
LSsession :: loadLSclass($elementType); LSsession :: loadLSclass($elementType);
if (!class_exists($elementType)) { if (!class_exists($elementType)) {
LSerror :: addErrorCode('LSform_05',array('type' => $type)); LSerror :: addErrorCode('LSform_05',array('type' => $type));
return; return false;
} }
$element=$this -> elements[$name] = new $elementType($this,$name,$label,$params,$attr_html); $element=$this -> elements[$name] = new $elementType($this,$name,$label,$params,$attr_html);
if ($element) { if ($element) {
@ -661,7 +661,7 @@ class LSform extends LSlog_staticLoggerClass {
else { else {
unset ($this -> elements[$name]); unset ($this -> elements[$name]);
LSerror :: addErrorCode('LSform_06',array('element' => $name)); LSerror :: addErrorCode('LSform_06',array('element' => $name));
return; return false;
} }
} }
@ -709,12 +709,12 @@ class LSform extends LSlog_staticLoggerClass {
} }
else { else {
LSerror :: addErrorCode('LSattribute_03', array('attr' => $element, 'rule' => $rule)); LSerror :: addErrorCode('LSattribute_03', array('attr' => $element, 'rule' => $rule));
return; return false;
} }
} }
else { else {
LSerror :: addErrorCode('LSform_04', array('element' => $element)); LSerror :: addErrorCode('LSform_04', array('element' => $element));
return; return false;
} }
} }
@ -768,7 +768,7 @@ class LSform extends LSlog_staticLoggerClass {
return $retval; return $retval;
} }
else { else {
return; return false;
} }
} }
@ -807,7 +807,7 @@ class LSform extends LSlog_staticLoggerClass {
*/ */
public function setValuesFromPostData() { public function setValuesFromPostData() {
if (empty($this -> _postData)) { if (empty($this -> _postData)) {
return; return false;
} }
foreach($this -> _postData as $element => $values) { foreach($this -> _postData as $element => $values) {
$this -> elements[$element] -> setValueFromPostData($values); $this -> elements[$element] -> setValueFromPostData($values);
@ -829,7 +829,7 @@ class LSform extends LSlog_staticLoggerClass {
return $element -> getEmptyField($value_idx); return $element -> getEmptyField($value_idx);
} }
else { else {
return; return null;
} }
} }
@ -875,7 +875,7 @@ class LSform extends LSlog_staticLoggerClass {
return true; return true;
} }
LSerror :: addErrorCode('LSform_07',$dataEntryForm); LSerror :: addErrorCode('LSform_07',$dataEntryForm);
return; return false;
} }
/** /**

View file

@ -443,7 +443,7 @@ class LSformElement extends LSlog_staticLoggerClass {
$attr_values = explode($multiple_value_delimiter, $attr_value); $attr_values = explode($multiple_value_delimiter, $attr_value);
if (count($attr_values) > 1 && !$this -> getParam('multiple', false, 'bool')) { if (count($attr_values) > 1 && !$this -> getParam('multiple', false, 'bool')) {
self :: log_error("The attribute ".$this -> name." is not multivalued."); self :: log_error("The attribute ".$this -> name." is not multivalued.");
return; return false;
} }
self :: log_debug("split_autocomplete_attr_values('$attr_value', '$multiple_value_delimiter'): values = '".implode("', '", $attr_values)."'"); self :: log_debug("split_autocomplete_attr_values('$attr_value', '$multiple_value_delimiter'): values = '".implode("', '", $attr_values)."'");
$last_attr_value = array_pop($attr_values); $last_attr_value = array_pop($attr_values);

View file

@ -267,7 +267,7 @@ class LSformElement_date extends LSformElement {
/** /**
* Convertis un format de date Php (strftime) en JS (jscalendar) * Convertis un format de date Php (strftime) en JS (jscalendar)
* *
* @return mixed Format de date jscalendar (string) ou False si la convertion * @return string|false Format de date jscalendar (string) ou False si la convertion
* n'a pas réussi. * n'a pas réussi.
*/ */
public function php2js_format($format) { public function php2js_format($format) {
@ -283,7 +283,7 @@ class LSformElement_date extends LSformElement {
} }
else { else {
$this -> _cache_php2js_format[$format]=false; $this -> _cache_php2js_format[$format]=false;
return; return false;
} }
} }
else { else {

View file

@ -168,7 +168,7 @@ class LSformElement_image extends LSformElement {
* @param boolean $details If true, returned values will contain details if this field type * @param boolean $details If true, returned values will contain details if this field type
* support it (optional, default: false) * support it (optional, default: false)
* *
* @return mixed API value(s) or null/empty array if no value * @return string|array|null API value(s) or null/empty array if no value
*/ */
public function getApiValue($details=false) { public function getApiValue($details=false) {
if ($this -> isMultiple()) { if ($this -> isMultiple()) {

View file

@ -206,7 +206,7 @@ class LSformElement_jsonCompositeAttribute extends LSformElement {
* @param string $c The component name * @param string $c The component name
* @param string $value The value * @param string $value The value
* *
* @return array * @return array|false
**/ **/
protected function getSelectListComponentValueLabel($c, $value) { protected function getSelectListComponentValueLabel($c, $value) {
if ($this -> getSelectListComponentPossibleValues($c)) { if ($this -> getSelectListComponentPossibleValues($c)) {
@ -220,7 +220,7 @@ class LSformElement_jsonCompositeAttribute extends LSformElement {
} }
} }
self :: log_trace("No label found for value '$value'"); self :: log_trace("No label found for value '$value'");
return; return false;
} }
/** /**

View file

@ -91,7 +91,7 @@ class LSformElement_labeledValue extends LSformElement {
* @param string $value The value to parse * @param string $value The value to parse
* @param boolean $details Enable/disable details return (optional, default: true) * @param boolean $details Enable/disable details return (optional, default: true)
* *
* @return array Parsed value * @return array|string Parsed value as array if $details enabled, the raw value otherwise
*/ */
public function parseValue($value, $details=true) { public function parseValue($value, $details=true) {
if (!$details) if (!$details)

View file

@ -47,7 +47,7 @@ class LSformElement_mailQuota extends LSformElement {
* @param string $value The value to parse * @param string $value The value to parse
* @param boolean $details Enable/disable details return (optional, default: true) * @param boolean $details Enable/disable details return (optional, default: true)
* *
* @return array Parsed value * @return array|int|false Parsed value as array if $details enabled, the size as integer otherwise, or false on failed to parse the provided valuearray|int|false Parsed value
*/ */
public function parseValue($value, $details=true) { public function parseValue($value, $details=true) {
if (preg_match('/^([0-9]+)'.$this -> getSuffix().'$/', $value, $regs)) { if (preg_match('/^([0-9]+)'.$this -> getSuffix().'$/', $value, $regs)) {

View file

@ -39,7 +39,7 @@ class LSformElement_password extends LSformElement {
* Mail to send info * Mail to send info
* @see self::getPostData() * @see self::getPostData()
* @see self::send() * @see self::send()
* @var array|false * @var array|bool
*/ */
var $sendMail = false; var $sendMail = false;

View file

@ -48,7 +48,7 @@ class LSformElement_quota extends LSformElement {
* @param string $value The value to parse * @param string $value The value to parse
* @param boolean $details Enable/disable details return (optional, default: true) * @param boolean $details Enable/disable details return (optional, default: true)
* *
* @return array Parsed value * @return array|int|false Parsed value as array if $details enabled, the size as integer otherwise, or false on failed to parse the provided value
*/ */
public function parseValue($value, $details=true) { public function parseValue($value, $details=true) {
if (preg_match('/^([0-9]+)$/', $value, $regs)) { if (preg_match('/^([0-9]+)$/', $value, $regs)) {
@ -56,7 +56,7 @@ class LSformElement_quota extends LSformElement {
'size' => ceil(intval($regs[1]) / $this -> getFactor()), 'size' => ceil(intval($regs[1]) / $this -> getFactor()),
); );
if (!$details) if (!$details)
return $infos['size']; return intval($infos['size']);
if ($infos['size'] == 0) { if ($infos['size'] == 0) {
return array( return array(
'size' => 0, 'size' => 0,

View file

@ -38,7 +38,7 @@ class LSformElement_sambaAcctFlags extends LSformElement_select_box {
* *
* This method return display data of this element * This method return display data of this element
* *
* @return array * @return bool
*/ */
public function isMultiple(){ public function isMultiple(){
return true; return true;

View file

@ -83,7 +83,7 @@ class LSformElement_select extends LSformElement {
* @param string $value The value to check * @param string $value The value to check
* @param array $possible_values The possible values * @param array $possible_values The possible values
* *
* @return string or False The value's label or False if this value is incorrect * @return string|false The value's label or False if this value is incorrect
*/ */
public static function _isValidValue($value, $possible_values) { public static function _isValidValue($value, $possible_values) {
if (!is_array($possible_values)) { if (!is_array($possible_values)) {

View file

@ -148,8 +148,8 @@ class LSformElement_select_object extends LSformElement {
/** /**
* Function use with uasort to sort two values * Function use with uasort to sort two values
* *
* @param string $va One value * @param array $va One value
* @param string $va One value * @param array $va One value
* *
* @return int Value for uasort * @return int Value for uasort
**/ **/
@ -204,13 +204,13 @@ class LSformElement_select_object extends LSformElement {
* *
* @param string $pattern The pattern of the search * @param string $pattern The pattern of the search
* *
* @return array Found objects with DN as key and display name as value * @return array|false Found objects with DN as key and display name as value, or false
*/ */
public function searchAdd($pattern) { public function searchAdd($pattern) {
$objs = array(); $objs = array();
$confs = $this -> attr_html -> getSelectableObjectsConfig($objs); $confs = $this -> attr_html -> getSelectableObjectsConfig($objs);
if (!is_array($confs)) if (!is_array($confs))
return; return false;
$selectable_objects = array(); $selectable_objects = array();
foreach($confs as $object_type => $conf) { foreach($confs as $object_type => $conf) {
$obj_type = $this -> getParam('html_options.selectable_object.object_type'); $obj_type = $this -> getParam('html_options.selectable_object.object_type');

View file

@ -42,7 +42,7 @@ class LSformElement_ssh_key extends LSformElement {
* @param string $value The value to parse * @param string $value The value to parse
* @param boolean $details Enable/disable details return (optional, default: true) * @param boolean $details Enable/disable details return (optional, default: true)
* *
* @return array Parsed value * @return array|string Parsed value as array is $details is enabled, the raw value otherwise
*/ */
public function parseValue($value, $details=true) { public function parseValue($value, $details=true) {
if (!$details) if (!$details)

View file

@ -140,7 +140,7 @@ class LSformElement_supannCompositeAttribute extends LSformElement {
* composite. * composite.
* *
* @param $value string La valeur à parser * @param $value string La valeur à parser
* @return array|null|false La valeur formatée, NULL en cas de valeur vide, ou False en cas de problème * @return string La valeur formatée, NULL en cas de valeur vide, ou False en cas de problème
*/ */
public function formatCompositeValue($value) { public function formatCompositeValue($value) {
return supannFormatCompositeValue($value); return supannFormatCompositeValue($value);

View file

@ -183,9 +183,9 @@ class LSformElement_supannLabeledValue extends LSformElement {
// Check all parameters is provided // Check all parameters is provided
foreach(array('attribute', 'objecttype', 'pattern', 'idform') as $parameter) foreach(array('attribute', 'objecttype', 'pattern', 'idform') as $parameter)
if (!isset($_REQUEST[$parameter])) if (!isset($_REQUEST[$parameter]))
return; return false;
if (!LSsession ::loadLSobject($_REQUEST['objecttype'])) if (!LSsession ::loadLSobject($_REQUEST['objecttype']))
return; return false;
$object = new $_REQUEST['objecttype'](); $object = new $_REQUEST['objecttype']();
$form = $object -> getForm($_REQUEST['idform']); $form = $object -> getForm($_REQUEST['idform']);
$field = $form -> getElement($_REQUEST['attribute']); $field = $form -> getElement($_REQUEST['attribute']);

View file

@ -77,14 +77,14 @@ class LSformElement_supannRessourceEtat extends LSformElement_supannCompositeAtt
$parseValue['sous_etat'] = $matches['sous_etat']; $parseValue['sous_etat'] = $matches['sous_etat'];
return $parseValue; return $parseValue;
} }
return; return null;
} }
/** /**
* Format une valeur composite gérer par ce type d'attribut * Format une valeur composite gérer par ce type d'attribut
* *
* @param $value string La valeur à parser * @param $value string La valeur à parser
* @return array|null|false La valeur formatée, NULL en cas de valeur vide, ou False en cas de problème * @return string|null|false La valeur formatée, NULL en cas de valeur vide, ou False en cas de problème
*/ */
public function formatCompositeValue($value) { public function formatCompositeValue($value) {
if (is_array($value)) { if (is_array($value)) {

View file

@ -90,14 +90,14 @@ class LSformElement_supannRessourceEtatDate extends LSformElement_supannComposit
$parseValue[$c] = $matches[$c]; $parseValue[$c] = $matches[$c];
return $parseValue; return $parseValue;
} }
return; return null;
} }
/** /**
* Format une valeur composite gérer par ce type d'attribut * Format une valeur composite gérer par ce type d'attribut
* *
* @param string $value La valeur à parser * @param string $value La valeur à parser
* @return array|null|false La valeur formatée, NULL en cas de valeur vide, ou False en cas de problème * @return string|null|false La valeur formatée, NULL en cas de valeur vide, ou False en cas de problème
*/ */
public function formatCompositeValue($value) { public function formatCompositeValue($value) {
if (is_array($value)) { if (is_array($value)) {

View file

@ -52,7 +52,7 @@ class LSformElement_valueWithUnit extends LSformElement {
return $units; return $units;
} }
LSerror :: addErrorCode('LSformElement_valueWithUnit_01', $this -> name); LSerror :: addErrorCode('LSformElement_valueWithUnit_01', $this -> name);
return; return false;
} }
/** /**
@ -80,7 +80,7 @@ class LSformElement_valueWithUnit extends LSformElement {
* @param string $value The value to parse * @param string $value The value to parse
* @param boolean $details Enable/disable details return (optional, default: true) * @param boolean $details Enable/disable details return (optional, default: true)
* *
* @return array Parsed value * @return array|int|false Parsed value as array if $details enabled, the vaue as integer otherwise, or false on failed to parse the provided value
*/ */
public function parseValue($value, $details=true) { public function parseValue($value, $details=true) {
if (preg_match('/^([0-9]*)$/' ,$value, $regs)) { if (preg_match('/^([0-9]*)$/' ,$value, $regs)) {

View file

@ -56,7 +56,7 @@ class LSformRule extends LSlog_staticLoggerClass {
* @param array $options Validation options * @param array $options Validation options
* @param LSformElement &$formElement The attached LSformElement object * @param LSformElement &$formElement The attached LSformElement object
* *
* @return boolean True if value is valid, False otherwise * @return array<string>|true True if value is valid, array of error messages otherwise
*/ */
public static function validate_values($rule_name, $values, $options, &$formElement) { public static function validate_values($rule_name, $values, $options, &$formElement) {
// Compute PHP class name of the rule // Compute PHP class name of the rule
@ -160,12 +160,12 @@ class LSformRule extends LSlog_staticLoggerClass {
/** /**
* Args autocompleter for CLI test_form_rule command * Args autocompleter for CLI test_form_rule command
* *
* @param array[string] $command_args List of already typed words of the command * @param array<string> $command_args List of already typed words of the command
* @param int $comp_word_num The command word number to autocomplete * @param int $comp_word_num The command word number to autocomplete
* @param string $comp_word The command word to autocomplete * @param string $comp_word The command word to autocomplete
* @param array[string] $opts List of global available options * @param array<string> $opts List of global available options
* *
* @return array[string] List of available options for the word to autocomplete * @return array<string> List of available options for the word to autocomplete
**/ **/
public static function cli_test_form_rule_args_autocompleter($command_args, $comp_word_num, $comp_word, $opts) { public static function cli_test_form_rule_args_autocompleter($command_args, $comp_word_num, $comp_word, $opts) {
$opts = array_merge($opts, array('-p', '--param')); $opts = array_merge($opts, array('-p', '--param'));
@ -184,7 +184,7 @@ class LSformRule extends LSlog_staticLoggerClass {
$quote_char = LScli :: unquote_word($command_args[$i]); $quote_char = LScli :: unquote_word($command_args[$i]);
$param_parts = explode('=', $command_args[$i]); $param_parts = explode('=', $command_args[$i]);
if (count($param_parts) > 2) if (count($param_parts) > 2)
return; break;
$params[$i] = array( $params[$i] = array(
'name' => $param_parts[0], 'name' => $param_parts[0],
'value' => (isset($param_parts[1])?$param_parts[1]:null), 'value' => (isset($param_parts[1])?$param_parts[1]:null),
@ -247,7 +247,7 @@ class LSformRule extends LSlog_staticLoggerClass {
* @param string $prefix Parameter name prefix (optional, default=empty string) * @param string $prefix Parameter name prefix (optional, default=empty string)
* @param string $quote_char Quote character (optional, default=empty string) * @param string $quote_char Quote character (optional, default=empty string)
* *
* @return array[string] List of available options for the word to autocomplete * @return array<string> List of available options for the word to autocomplete
**/ **/
public static function cli_test_form_rule_param_name_autocompleter($prefix='', $quote_char='') { public static function cli_test_form_rule_param_name_autocompleter($prefix='', $quote_char='') {
$opts = LScli :: autocomplete_opts(array_keys(static :: $cli_params_autocompleters), $prefix); $opts = LScli :: autocomplete_opts(array_keys(static :: $cli_params_autocompleters), $prefix);
@ -264,17 +264,17 @@ class LSformRule extends LSlog_staticLoggerClass {
* @param string $prefix Parameter name prefix (optional, default=empty string) * @param string $prefix Parameter name prefix (optional, default=empty string)
* @param string $quote_char Quote character (optional, default=empty string) * @param string $quote_char Quote character (optional, default=empty string)
* *
* @return array[string] List of available options for the word to autocomplete * @return array<string> List of available options for the word to autocomplete
**/ **/
public static function cli_test_form_rule_param_value_autocompleter($param_name, $prefix='', $quote_char='') { public static function cli_test_form_rule_param_value_autocompleter($param_name, $prefix='', $quote_char='') {
if ( if (
!array_key_exists($param_name, static :: $cli_params_autocompleters) || !array_key_exists($param_name, static :: $cli_params_autocompleters) ||
!is_callable(static :: $cli_params_autocompleters[$param_name]) !is_callable(static :: $cli_params_autocompleters[$param_name])
) )
return; return array();
$opts = call_user_func(static :: $cli_params_autocompleters[$param_name], $prefix); $opts = call_user_func(static :: $cli_params_autocompleters[$param_name], $prefix);
if (!is_array($opts)) if (!is_array($opts))
return; return array();
for($i=0; $i<count($opts); $i++) for($i=0; $i<count($opts); $i++)
$opts[$i] = $param_name."=".$opts[$i]; $opts[$i] = $param_name."=".$opts[$i];
self :: log_debug("Options: ".varDump($opts)); self :: log_debug("Options: ".varDump($opts));

View file

@ -88,7 +88,7 @@ class LSformRule_compare extends LSformRule {
$operator = LSconfig :: get('params.operator', null, 'string', $options); $operator = LSconfig :: get('params.operator', null, 'string', $options);
if (!$operator) { if (!$operator) {
LSerror :: addErrorCode('LSformRule_01',array('type' => 'compare', 'param' => 'operator')); LSerror :: addErrorCode('LSformRule_01',array('type' => 'compare', 'param' => 'operator'));
return; return false;
} }
$compareFn = self :: _findOperatorCompareFunction($operator); $compareFn = self :: _findOperatorCompareFunction($operator);
return $compareFn($values[0], $values[1]); return $compareFn($values[0], $values[1]);

View file

@ -51,7 +51,7 @@ class LSformRule_date extends LSformRule {
$format = LSconfig :: get('params.format', null, 'string', $options); $format = LSconfig :: get('params.format', null, 'string', $options);
if (is_null($format)) { if (is_null($format)) {
LSerror :: addErrorCode('LSformRule_date_01'); LSerror :: addErrorCode('LSformRule_date_01');
return; return false;
} }
$date = strptime($value, $format); $date = strptime($value, $format);
if(is_array($date)) { if(is_array($date)) {
@ -60,7 +60,7 @@ class LSformRule_date extends LSformRule {
return true; return true;
} }
} }
return; return false;
} }
} }

View file

@ -56,25 +56,25 @@ class LSformRule_imagesize extends LSformRule {
$maxWidth = LSconfig :: get('params.maxWidth', null, 'int', $options); $maxWidth = LSconfig :: get('params.maxWidth', null, 'int', $options);
if ($maxWidth && $width > $maxWidth) { if ($maxWidth && $width > $maxWidth) {
self :: log_debug("validate(): max width error ($width > $maxWidth)"); self :: log_debug("validate(): max width error ($width > $maxWidth)");
return; return false;
} }
$minWidth = LSconfig :: get('params.minWidth', null, 'int', $options); $minWidth = LSconfig :: get('params.minWidth', null, 'int', $options);
if ($minWidth && $width < $minWidth) { if ($minWidth && $width < $minWidth) {
self :: log_debug("validate(): min width error ($width < $minWidth)"); self :: log_debug("validate(): min width error ($width < $minWidth)");
return; return false;
} }
$maxHeight = LSconfig :: get('params.maxHeight', null, 'int', $options); $maxHeight = LSconfig :: get('params.maxHeight', null, 'int', $options);
if ($maxHeight && $height > $maxHeight) { if ($maxHeight && $height > $maxHeight) {
self :: log_debug("validate(): max height error ($height > $maxHeight)"); self :: log_debug("validate(): max height error ($height > $maxHeight)");
return; return false;
} }
$minHeight = LSconfig :: get('params.minHeight', null, 'int', $options); $minHeight = LSconfig :: get('params.minHeight', null, 'int', $options);
if ($minHeight && $height < $minHeight) { if ($minHeight && $height < $minHeight) {
self :: log_debug("validate(): min height error ($height < $minHeight)"); self :: log_debug("validate(): min height error ($height < $minHeight)");
return; return false;
} }
return true; return true;

View file

@ -50,7 +50,7 @@ class LSformRule_inarray extends LSformRule {
$reverse = LSconfig :: get('params.reverse', false, 'bool', $options); $reverse = LSconfig :: get('params.reverse', false, 'bool', $options);
if (!is_array($possible_values)) { if (!is_array($possible_values)) {
LSerror :: addErrorCode('LSformRule_inarray_01'); LSerror :: addErrorCode('LSformRule_inarray_01');
return; return false;
} }
if (!in_array($value, $possible_values)) if (!in_array($value, $possible_values))
return $reverse; return $reverse;

View file

@ -52,13 +52,13 @@ class LSformRule_integer extends LSformRule{
$max = LSconfig :: get('params.max', null, 'int', $options); $max = LSconfig :: get('params.max', null, 'int', $options);
if(is_int($max) && $max != 0 && $value > $max) { if(is_int($max) && $max != 0 && $value > $max) {
self :: log_debug("value is too higth ($value > $max)"); self :: log_debug("value is too higth ($value > $max)");
return; return false;
} }
$min = LSconfig :: get('params.min', null, 'int', $options); $min = LSconfig :: get('params.min', null, 'int', $options);
if(is_int($min) && $min != 0 && $value < $min) { if(is_int($min) && $min != 0 && $value < $min) {
self :: log_debug("value is too low ($value < $min)"); self :: log_debug("value is too low ($value < $min)");
return; return false;
} }
if(LSconfig :: get('params.negative', false, 'bool', $options)) { if(LSconfig :: get('params.negative', false, 'bool', $options)) {
@ -73,7 +73,7 @@ class LSformRule_integer extends LSformRule{
LSsession :: loadLSclass('LSformRule_regex'); LSsession :: loadLSclass('LSformRule_regex');
if (!LSformRule_regex :: validate($value,$regex,$formElement)) { if (!LSformRule_regex :: validate($value,$regex,$formElement)) {
self :: log_debug("value '$value' does not respect regex '$regex'"); self :: log_debug("value '$value' does not respect regex '$regex'");
return; return false;
} }
return true; return true;
} }

View file

@ -46,7 +46,7 @@ class LSformRule_maxlength extends LSformRule {
$limit = LSconfig :: get('params.limit', null, 'int', $options); $limit = LSconfig :: get('params.limit', null, 'int', $options);
if(is_null($limit)) { if(is_null($limit)) {
LSerror :: addErrorCode('LSformRule_01',array('type' => 'maxlength', 'param' => 'limit')); LSerror :: addErrorCode('LSformRule_01',array('type' => 'maxlength', 'param' => 'limit'));
return; return false;
} }
return (strlen($value) <= $limit); return (strlen($value) <= $limit);
} }

View file

@ -46,7 +46,7 @@ class LSformRule_minlength extends LSformRule {
$limit = LSconfig :: get('params.limit', null, 'int', $options); $limit = LSconfig :: get('params.limit', null, 'int', $options);
if(is_null($limit)) { if(is_null($limit)) {
LSerror :: addErrorCode('LSformRule_01',array('type' => 'minlength', 'param' => 'limit')); LSerror :: addErrorCode('LSformRule_01',array('type' => 'minlength', 'param' => 'limit'));
return; return false;
} }
return (strlen($value) >= $limit); return (strlen($value) >= $limit);
} }

View file

@ -54,11 +54,11 @@ class LSformRule_numberOfValues extends LSformRule {
$min_values = LSconfig :: get('params.min', null, 'int', $options); $min_values = LSconfig :: get('params.min', null, 'int', $options);
if(is_null($max_values) && is_null($min_values)) { if(is_null($max_values) && is_null($min_values)) {
LSerror :: addErrorCode('LSformRule_01',array('type' => 'numberOfValues', 'param' => _('max (or min)'))); LSerror :: addErrorCode('LSformRule_01',array('type' => 'numberOfValues', 'param' => _('max (or min)')));
return; return false;
} }
if (!is_null($max_values) && !is_null($min_values) && $max_values < $min_values) { if (!is_null($max_values) && !is_null($min_values) && $max_values < $min_values) {
LSerror :: addErrorCode('LSformRule_numberOfValues_01'); LSerror :: addErrorCode('LSformRule_numberOfValues_01');
return; return false;
} }
$count = count($value); $count = count($value);

View file

@ -47,7 +47,7 @@ class LSformRule_rangelength extends LSformRule {
$limits = LSconfig :: get('params.limits', null, null, $options); $limits = LSconfig :: get('params.limits', null, null, $options);
if(!is_array($limits) || count($limits) != 2) { if(!is_array($limits) || count($limits) != 2) {
LSerror :: addErrorCode('LSformRule_01',array('type' => 'rangelength', 'param' => 'limits')); LSerror :: addErrorCode('LSformRule_01',array('type' => 'rangelength', 'param' => 'limits'));
return; return false;
} }
$len = strlen($value); $len = strlen($value);
if ($len < $limits[0]) if ($len < $limits[0])

View file

@ -47,7 +47,7 @@ class LSformRule_regex extends LSformRule {
$regex = LSconfig :: get('params.regex', null, 'string', $options); $regex = LSconfig :: get('params.regex', null, 'string', $options);
if (!is_string($regex)) { if (!is_string($regex)) {
LSerror :: addErrorCode('LSformRule_regex_01'); LSerror :: addErrorCode('LSformRule_regex_01');
return; return false;
} }
} }
else { else {

View file

@ -42,14 +42,14 @@ class LSio extends LSlog_staticLoggerClass {
public static function isSubmit($action) { public static function isSubmit($action) {
if (isset($_REQUEST['validate']) && ($_REQUEST['validate']==$action)) if (isset($_REQUEST['validate']) && ($_REQUEST['validate']==$action))
return true; return true;
return; return false;
} }
/** /**
* Retrieve the post file * Retrieve the post file
* *
* @return mixed The path of the temporary file, false on error * @return string|false The path of the temporary file, false on error
*/ */
public static function getPostFile() { public static function getPostFile() {
if (is_uploaded_file($_FILES['importfile']['tmp_name'])) { if (is_uploaded_file($_FILES['importfile']['tmp_name'])) {
@ -506,12 +506,12 @@ class LSio extends LSlog_staticLoggerClass {
/** /**
* Args autocompleter for CLI import command * Args autocompleter for CLI import command
* *
* @param array[string] $command_args List of already typed words of the command * @param array<string> $command_args List of already typed words of the command
* @param int $comp_word_num The command word number to autocomplete * @param int $comp_word_num The command word number to autocomplete
* @param string $comp_word The command word to autocomplete * @param string $comp_word The command word to autocomplete
* @param array[string] $opts List of global available options * @param array<string> $opts List of global available options
* *
* @return array[string] List of available options for the word to autocomplete * @return array<string> List of available options for the word to autocomplete
**/ **/
public static function cli_import_args_autocompleter($command_args, $comp_word_num, $comp_word, $opts) { public static function cli_import_args_autocompleter($command_args, $comp_word_num, $comp_word, $opts) {
$opts = array_merge($opts, array ('-i', '--input', '-U', '--update', '-j', '--just-try')); $opts = array_merge($opts, array ('-i', '--input', '-U', '--update', '-j', '--just-try'));
@ -610,12 +610,12 @@ class LSio extends LSlog_staticLoggerClass {
/** /**
* Args autocompleter for CLI export command * Args autocompleter for CLI export command
* *
* @param array[string] $command_args List of already typed words of the command * @param array<string> $command_args List of already typed words of the command
* @param int $comp_word_num The command word number to autocomplete * @param int $comp_word_num The command word number to autocomplete
* @param string $comp_word The command word to autocomplete * @param string $comp_word The command word to autocomplete
* @param array[string] $opts List of global available options * @param array<string> $opts List of global available options
* *
* @return array[string] List of available options for the word to autocomplete * @return array<string> List of available options for the word to autocomplete
**/ **/
public static function cli_export_args_autocompleter($command_args, $comp_word_num, $comp_word, $opts) { public static function cli_export_args_autocompleter($command_args, $comp_word_num, $comp_word, $opts) {
$opts = array_merge($opts, array ('-o', '--output')); $opts = array_merge($opts, array ('-o', '--output'));

View file

@ -122,7 +122,7 @@ class LSioFormat extends LSlog_staticLoggerClass {
/** /**
* Export objects * Export objects
* *
* @param array[LSldapObject] $objects The objects to export * @param array<LSldapObject> $objects The objects to export
* @param resource|null $stream The output stream (optional, default: STDOUT) * @param resource|null $stream The output stream (optional, default: STDOUT)
* *
* @return boolean True on success, False otherwise * @return boolean True on success, False otherwise

View file

@ -271,7 +271,7 @@ class LSioFormatCSV extends LSioFormatDriver {
* Write CSV row to stream * Write CSV row to stream
* *
* @param resource $stream The CSV file description reference * @param resource $stream The CSV file description reference
* @param array[string] $row An array of a CSV row fields to write * @param array<string> $row An array of a CSV row fields to write
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *

View file

@ -120,7 +120,7 @@ class LSioFormatDriver extends LSlog_staticLoggerClass {
* @param array $fields of file's fields name mapping with object attribute * @param array $fields of file's fields name mapping with object attribute
* @param array $generated_fields of object attribute to generate using other object data * @param array $generated_fields of object attribute to generate using other object data
* *
* @return array All objects data of the loaded file formated * @return array|false All objects data of the loaded file formated, or false
**/ **/
public function getAllFormated($fields, $generated_fields) { public function getAllFormated($fields, $generated_fields) {
if (!is_array($fields)) return False; if (!is_array($fields)) return False;

View file

@ -213,7 +213,7 @@ class LSlang extends LSlog_staticLoggerClass {
**/ **/
public static function localeExist($lang, $encoding) { public static function localeExist($lang, $encoding) {
if ( !$lang && !$encoding ) { if ( !$lang && !$encoding ) {
return; return false;
} }
$locale=$lang.(($encoding)?'.'.$encoding:''); $locale=$lang.(($encoding)?'.'.$encoding:'');
if ($locale == 'en_US.UTF8') { if ($locale == 'en_US.UTF8') {
@ -267,7 +267,7 @@ function _cli_absolute2relative_path($path) {
* CLI Helper to ask user to translate a string * CLI Helper to ask user to translate a string
* @param string $context The context of the string to translate * @param string $context The context of the string to translate
* @param string $msg The string to convert * @param string $msg The string to convert
* @return boolean True on success, False otherwise * @return string|true The translated message string, true if $interactive_exit enabled
*/ */
function _cli_interactive_ask($context, $msg) { function _cli_interactive_ask($context, $msg) {
global $copyoriginalvalue, $interactive_exit; global $copyoriginalvalue, $interactive_exit;
@ -397,7 +397,7 @@ function _cli_add_str_to_translate_from_LSconfig($pattern, $what='value', $exclu
/** /**
* CLI helper to add string to translate from list of possible values retreive from LSconfig * CLI helper to add string to translate from list of possible values retreive from LSconfig
* @param string $context The context == prefix of the LSconfig parameter key to retreive possible values * @param string $context The context == prefix of the LSconfig parameter key to retreive possible values
* @param array[string] $withouts FIXME * @param array<string> $withouts FIXME
* @param integer $level The level of the possible value (used to identify recursion level) * @param integer $level The level of the possible value (used to identify recursion level)
* @return void * @return void
*/ */
@ -405,9 +405,9 @@ function _cli_add_possible_values_from_LSconfig($context, $withouts, $level=0) {
global $LSlang_cli_logger; global $LSlang_cli_logger;
$LSlang_cli_logger -> trace("_cli_add_possible_values_from_LSconfig($context)"); $LSlang_cli_logger -> trace("_cli_add_possible_values_from_LSconfig($context)");
if (in_array('select-list', $withouts)) if (in_array('select-list', $withouts))
return true; return;
if (!LSconfig :: get("$context.translate_labels", True, "bool")) if (!LSconfig :: get("$context.translate_labels", True, "bool"))
return true; return;
foreach(LSconfig :: get("$context.possible_values", array()) as $pkey => $plabel) { foreach(LSconfig :: get("$context.possible_values", array()) as $pkey => $plabel) {
if (is_array($plabel)) { if (is_array($plabel)) {
// Sub possible values // Sub possible values
@ -416,7 +416,7 @@ function _cli_add_possible_values_from_LSconfig($context, $withouts, $level=0) {
$LSlang_cli_logger -> warning( $LSlang_cli_logger -> warning(
"_cli_add_possible_values_from_LSconfig($context): Level to hight to handle sub possible values of $context.possible_values.$pkey" "_cli_add_possible_values_from_LSconfig($context): Level to hight to handle sub possible values of $context.possible_values.$pkey"
); );
return true; return;
} }
_cli_add_str_to_translate_from_LSconfig("$context.possible_values.$pkey.label"); _cli_add_str_to_translate_from_LSconfig("$context.possible_values.$pkey.label");
$LSlang_cli_logger -> trace("_cli_add_possible_values_from_LSconfig($context): handle sub possible values of $context.possible_values.$pkey"); $LSlang_cli_logger -> trace("_cli_add_possible_values_from_LSconfig($context): handle sub possible values of $context.possible_values.$pkey");
@ -1047,9 +1047,9 @@ function cli_generate_lang_file($command_args) {
* @param array $comp_words List of already typed words of the command * @param array $comp_words List of already typed words of the command
* @param int $comp_word_num The command word number to autocomplete * @param int $comp_word_num The command word number to autocomplete
* @param string $comp_word The command word to autocomplete * @param string $comp_word The command word to autocomplete
* @param array[string] $opts List of global available options * @param array<string> $opts List of global available options
* *
* @return array[string] List of available options for the word to autocomplete * @return array<string> List of available options for the word to autocomplete
**/ **/
function cli_generate_lang_file_args_autocompleter($comp_words, $comp_word_num, $comp_word, $opts) { function cli_generate_lang_file_args_autocompleter($comp_words, $comp_word_num, $comp_word, $opts) {
global $available_withouts, $available_onlys; global $available_withouts, $available_onlys;
@ -1158,6 +1158,7 @@ function cli_generate_ldapsaisie_pot($command_args) {
); );
if (!is_array($php_files) || $php_files[0] != 0) { if (!is_array($php_files) || $php_files[0] != 0) {
$LSlang_cli_logger -> fatal("Fail to list PHP files."); $LSlang_cli_logger -> fatal("Fail to list PHP files.");
return false;
} }
// Extract messages from LdapSaisie PHP files using xgettext // Extract messages from LdapSaisie PHP files using xgettext

View file

@ -85,7 +85,7 @@ class LSldap extends LSlog_staticLoggerClass {
if (Net_LDAP2::isError(self :: $cnx)) { if (Net_LDAP2::isError(self :: $cnx)) {
LSerror :: addErrorCode('LSldap_01',self :: $cnx -> getMessage()); LSerror :: addErrorCode('LSldap_01',self :: $cnx -> getMessage());
self :: $cnx = NULL; self :: $cnx = NULL;
return; return false;
} }
return true; return true;
} }
@ -116,7 +116,7 @@ class LSldap extends LSlog_staticLoggerClass {
if (Net_LDAP2::isError(self :: $cnx)) { if (Net_LDAP2::isError(self :: $cnx)) {
LSerror :: addErrorCode('LSldap_01', self :: $cnx -> getMessage()); LSerror :: addErrorCode('LSldap_01', self :: $cnx -> getMessage());
self :: $cnx = NULL; self :: $cnx = NULL;
return; return false;
} }
return true; return true;
} }
@ -180,11 +180,12 @@ class LSldap extends LSlog_staticLoggerClass {
* *
* @see Net_LDAP2::search() * @see Net_LDAP2::search()
* *
* @return array Return an array of entries returned by the LDAP directory. Each element * @return array|false Return an array of entries returned by the LDAP directory.
* of this array corresponded to one returned entry and is an array with * Each element of this array corresponded to one returned entry and is
* the following keys: * an array with the following keys:
* - dn: The DN of the entry * - dn: The DN of the entry
* - attrs: Associative array of the entry's attributes values * - attrs: Associative array of the entry's attributes values
* False returned in case of error.
*/ */
public static function search($filter, $basedn=NULL, $params=array()) { public static function search($filter, $basedn=NULL, $params=array()) {
$filterstr = (is_a($filter, 'Net_LDAP2_Filter')?$filter->asString():$filter); $filterstr = (is_a($filter, 'Net_LDAP2_Filter')?$filter->asString():$filter);
@ -192,7 +193,7 @@ class LSldap extends LSlog_staticLoggerClass {
$basedn = self :: getConfig('basedn'); $basedn = self :: getConfig('basedn');
if (is_empty($basedn)) { if (is_empty($basedn)) {
LSerror :: addErrorCode('LSldap_08'); LSerror :: addErrorCode('LSldap_08');
return; return false;
} }
self :: log_debug("LSldap::search($filterstr): empty basedn provided, use basedn from configuration: ".varDump($basedn)); self :: log_debug("LSldap::search($filterstr): empty basedn provided, use basedn from configuration: ".varDump($basedn));
} }
@ -200,7 +201,7 @@ class LSldap extends LSlog_staticLoggerClass {
$ret = self :: $cnx -> search($basedn, $filter, $params); $ret = self :: $cnx -> search($basedn, $filter, $params);
if (Net_LDAP2::isError($ret)) { if (Net_LDAP2::isError($ret)) {
LSerror :: addErrorCode('LSldap_02', $ret -> getMessage()); LSerror :: addErrorCode('LSldap_02', $ret -> getMessage());
return; return false;
} }
self :: log_debug("LSldap::search($filterstr, $basedn) : return ".$ret->count()." objet(s)"); self :: log_debug("LSldap::search($filterstr, $basedn) : return ".$ret->count()." objet(s)");
$retInfos = array(); $retInfos = array();
@ -241,7 +242,7 @@ class LSldap extends LSlog_staticLoggerClass {
$basedn = self :: getConfig('basedn'); $basedn = self :: getConfig('basedn');
if (is_empty($basedn)) { if (is_empty($basedn)) {
LSerror :: addErrorCode('LSldap_08'); LSerror :: addErrorCode('LSldap_08');
return; return null;
} }
self :: log_debug("LSldap::getNumberResult($filterstr): empty basedn provided, use basedn from configuration: ".varDump($basedn)); self :: log_debug("LSldap::getNumberResult($filterstr): empty basedn provided, use basedn from configuration: ".varDump($basedn));
} }
@ -249,7 +250,7 @@ class LSldap extends LSlog_staticLoggerClass {
$ret = self :: $cnx -> search($basedn, $filter, $params); $ret = self :: $cnx -> search($basedn, $filter, $params);
if (Net_LDAP2::isError($ret)) { if (Net_LDAP2::isError($ret)) {
LSerror :: addErrorCode('LSldap_02',$ret -> getMessage()); LSerror :: addErrorCode('LSldap_02',$ret -> getMessage());
return; return null;
} }
$count = $ret -> count(); $count = $ret -> count();
self :: log_trace("LSldap::getNumberResult($filterstr, $basedn): result=$count"); self :: log_trace("LSldap::getNumberResult($filterstr, $basedn): result=$count");
@ -274,7 +275,7 @@ class LSldap extends LSlog_staticLoggerClass {
public static function getAttrs($dn, $filter=null, $attrs=null, $include_internal=false) { public static function getAttrs($dn, $filter=null, $attrs=null, $include_internal=false) {
$infos = ldap_explode_dn($dn,0); $infos = ldap_explode_dn($dn,0);
if((!$infos)||($infos['count']==0)) if((!$infos)||($infos['count']==0))
return; return false;
if (!$filter) if (!$filter)
$filter = '(objectClass=*)'; $filter = '(objectClass=*)';
$params = array( $params = array(
@ -290,15 +291,19 @@ class LSldap extends LSlog_staticLoggerClass {
} }
/** /**
* Return a date string * Parse a date string as Datetime object
* *
* @param string $value LDAP date * @param string $value LDAP date string to parse
* *
* @return string Date YYYY/MM/DD HH:mm:ss * @return Datetime|false Datetime object, or false
*/ */
public static function parseDate($value) { public static function parseDate($value) {
$datetime = date_create_from_format('YmdHis.uO', $value); $datetime = date_create_from_format('YmdHis.uO', $value);
return ($datetime instanceof DateTime) ? $datetime -> setTimezone(timezone_open(date_default_timezone_get())) : $datetime; return (
$datetime instanceof DateTime?
$datetime -> setTimezone(timezone_open(date_default_timezone_get())):
false
);
} }
/** /**
@ -348,25 +353,26 @@ class LSldap extends LSlog_staticLoggerClass {
* @param string $object_type The object type * @param string $object_type The object type
* @param string $dn The DN of the LDAP entry * @param string $dn The DN of the LDAP entry
* *
* @return Net_LDAP2_Entry|array A Net_LDAP2_Entry object or an array if * @return Net_LDAP2_Entry|array|false A Net_LDAP2_Entry object or an array if
* it's a new entry: * it's a new entry:
* Array ( * Array (
* 'entry' => Net_LDAP2_Entry, * 'entry' => Net_LDAP2_Entry,
* 'new' => true * 'new' => true
* ) * )
* False returned in case of error
*/ */
public static function getEntry($object_type, $dn) { public static function getEntry($object_type, $dn) {
$obj_classes = LSconfig :: get("LSobjects.$object_type.objectclass"); $obj_classes = LSconfig :: get("LSobjects.$object_type.objectclass");
if(!is_array($obj_classes)){ if(!is_array($obj_classes)){
LSerror :: addErrorCode('LSldap_03'); LSerror :: addErrorCode('LSldap_03');
return; return false;
} }
$attrs = array_keys(LSconfig :: get("LSobjects.$object_type.attrs", array(), 'array')); $attrs = array_keys(LSconfig :: get("LSobjects.$object_type.attrs", array(), 'array'));
$entry = self :: getLdapEntry($dn, $attrs); $entry = self :: getLdapEntry($dn, $attrs);
if ($entry === false) { if ($entry === false) {
$newentry = self :: getNewEntry($dn, $obj_classes, array()); $newentry = self :: getNewEntry($dn, $obj_classes, array());
if (!$newentry) { if (!$newentry) {
return; return false;
} }
// Mark entry as new // Mark entry as new
@ -416,7 +422,7 @@ class LSldap extends LSlog_staticLoggerClass {
* Return a new Net_LDAP2_Entry object * Return a new Net_LDAP2_Entry object
* *
* @param string $dn The DN of the object * @param string $dn The DN of the object
* @param array[string] $objectClass Array of the object's object classes * @param array<string> $objectClass Array of the object's object classes
* @param array $attrs Array of the object's attributes values * @param array $attrs Array of the object's attributes values
* @param boolean $add Set to true to add the new entry to LDAP directory (default: false) * @param boolean $add Set to true to add the new entry to LDAP directory (default: false)
* *
@ -461,7 +467,7 @@ class LSldap extends LSlog_staticLoggerClass {
$entry = self :: getEntry($object_type, $dn); $entry = self :: getEntry($object_type, $dn);
if(!is_a($entry, 'Net_LDAP2_Entry')) { if(!is_a($entry, 'Net_LDAP2_Entry')) {
LSerror :: addErrorCode('LSldap_04'); LSerror :: addErrorCode('LSldap_04');
return; return false;
} }
// Distinguish drop attributes from change attributes // Distinguish drop attributes from change attributes
@ -578,7 +584,7 @@ class LSldap extends LSlog_staticLoggerClass {
$config['bindpw'] = $pwd; $config['bindpw'] = $pwd;
$cnx = Net_LDAP2::connect($config); $cnx = Net_LDAP2::connect($config);
if (Net_LDAP2::isError($cnx)) { if (Net_LDAP2::isError($cnx)) {
return; return false;
} }
return true; return true;
} }
@ -603,7 +609,7 @@ class LSldap extends LSlog_staticLoggerClass {
$ret = self :: $cnx -> delete($dn,array('recursive' => true)); $ret = self :: $cnx -> delete($dn,array('recursive' => true));
if (Net_LDAP2::isError($ret)) { if (Net_LDAP2::isError($ret)) {
LSerror :: addErrorCode(0,'NetLdap-Error : '.$ret->getMessage()); LSerror :: addErrorCode(0,'NetLdap-Error : '.$ret->getMessage());
return; return false;
} }
return true; return true;
} }
@ -621,7 +627,7 @@ class LSldap extends LSlog_staticLoggerClass {
if (Net_LDAP2::isError($ret)) { if (Net_LDAP2::isError($ret)) {
LSerror :: addErrorCode('LSldap_07'); LSerror :: addErrorCode('LSldap_07');
LSerror :: addErrorCode(0,'NetLdap-Error : '.$ret->getMessage()); LSerror :: addErrorCode(0,'NetLdap-Error : '.$ret->getMessage());
return; return false;
} }
return true; return true;
} }
@ -664,7 +670,7 @@ class LSldap extends LSlog_staticLoggerClass {
LSerror :: addErrorCode(0,$filter -> getMessage()); LSerror :: addErrorCode(0,$filter -> getMessage());
} }
} }
return; return false;
} }
/** /**
@ -684,7 +690,7 @@ class LSldap extends LSlog_staticLoggerClass {
LSerror :: addErrorCode(0,$filter -> getMessage()); LSerror :: addErrorCode(0,$filter -> getMessage());
} }
} }
return; return false;
} }
/** /**
* Update userPassword attribute * Update userPassword attribute
@ -697,7 +703,7 @@ class LSldap extends LSlog_staticLoggerClass {
* *
* @author Emmanuel Saracco <esaracco@easter-eggs.com> * @author Emmanuel Saracco <esaracco@easter-eggs.com>
* *
* @return mixed New array of changed attributes or false * @return array|false New array of changed attributes or false
**/ **/
private static function updateUserPassword($object_type, $changed_attrs, $dn) { private static function updateUserPassword($object_type, $changed_attrs, $dn) {
if (self :: getConfig('version') < 3 || !function_exists('ldap_mod_replace_ext')) { if (self :: getConfig('version') < 3 || !function_exists('ldap_mod_replace_ext')) {

View file

@ -86,7 +86,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
/** /**
* Cache of LSsession::whoami() result for the current connected user * Cache of LSsession::whoami() result for the current connected user
* @var string|null * @var array<string>|null
*/ */
var $_whoami=NULL; var $_whoami=NULL;
@ -128,7 +128,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return boolean true si l'objet a été construit, false sinon. * @return void
*/ */
public function __construct() { public function __construct() {
$this -> type_name = get_class($this); $this -> type_name = get_class($this);
@ -146,8 +146,6 @@ class LSldapObject extends LSlog_staticLoggerClass {
return; return;
} }
} }
return true;
} }
/** /**
@ -178,12 +176,12 @@ class LSldapObject extends LSlog_staticLoggerClass {
if(is_array($data) && !empty($data)) { if(is_array($data) && !empty($data)) {
foreach($this -> attrs as $attr_name => $attr) { foreach($this -> attrs as $attr_name => $attr) {
if( !$this -> attrs[$attr_name] -> loadData( (isset($data[$attr_name])?$data[$attr_name]:NULL) ) ) if( !$this -> attrs[$attr_name] -> loadData( (isset($data[$attr_name])?$data[$attr_name]:NULL) ) )
return; return false;
} }
$this->cache=array(); $this->cache=array();
return true; return true;
} }
return; return false;
} }
/** /**
@ -197,7 +195,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
$data = LSldap :: getAttrs($this -> dn); $data = LSldap :: getAttrs($this -> dn);
foreach($this -> attrs as $attr_name => $attr) { foreach($this -> attrs as $attr_name => $attr) {
if(!$this -> attrs[$attr_name] -> reloadData( (isset($data[$attr_name])?$data[$attr_name]:NULL) )) if(!$this -> attrs[$attr_name] -> reloadData( (isset($data[$attr_name])?$data[$attr_name]:NULL) ))
return; return false;
} }
return true; return true;
} }
@ -355,7 +353,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
$LSform = $this -> forms[$idForm][0]; $LSform = $this -> forms[$idForm][0];
foreach($this -> attrs as $attr_name => $attr) { foreach($this -> attrs as $attr_name => $attr) {
if(!$this -> attrs[$attr_name] -> refreshForm($LSform,$idForm)) { if(!$this -> attrs[$attr_name] -> refreshForm($LSform,$idForm)) {
return; return false;
} }
} }
return true; return true;
@ -382,7 +380,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
$LSform = $this -> forms[$idForm][0]; $LSform = $this -> forms[$idForm][0];
else { else {
LSerror :: addErrorCode('LSldapObject_02',$this -> getType()); LSerror :: addErrorCode('LSldapObject_02',$this -> getType());
return; return false;
} }
} }
else { else {
@ -395,7 +393,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
} }
else { else {
LSerror :: addErrorCode('LSldapObject_03',$this -> getType()); LSerror :: addErrorCode('LSldapObject_03',$this -> getType());
return; return false;
} }
} }
$new_data = $LSform -> exportValues(); $new_data = $LSform -> exportValues();
@ -423,7 +421,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
*/ */
protected function _updateData($new_data, $idForm=null, $justCheck=False) { protected function _updateData($new_data, $idForm=null, $justCheck=False) {
if(!is_array($new_data)) { if(!is_array($new_data)) {
return; return false;
} }
foreach($new_data as $attr_name => $attr_val) { foreach($new_data as $attr_name => $attr_val) {
if(isset($this -> attrs[$attr_name])) { if(isset($this -> attrs[$attr_name])) {
@ -438,13 +436,13 @@ class LSldapObject extends LSlog_staticLoggerClass {
} }
if (!$this -> fireEvent('before_modify')) { if (!$this -> fireEvent('before_modify')) {
return; return false;
} }
// $this -> attrs[ {inNewData} ] -> fireEvent('before_modify') // $this -> attrs[ {inNewData} ] -> fireEvent('before_modify')
foreach($new_data as $attr_name => $attr_val) { foreach($new_data as $attr_name => $attr_val) {
if ($this -> attrs[$attr_name] -> isUpdate() && !$this -> attrs[$attr_name] -> fireEvent('before_modify')) { if ($this -> attrs[$attr_name] -> isUpdate() && !$this -> attrs[$attr_name] -> fireEvent('before_modify')) {
return; return false;
} }
} }
@ -466,13 +464,13 @@ class LSldapObject extends LSlog_staticLoggerClass {
$this -> refreshForm($idForm); $this -> refreshForm($idForm);
} }
else { else {
return; return false;
} }
return true; return true;
} }
else { else {
return; return false;
} }
} }
@ -745,7 +743,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
self :: log_debug("$this -> submitChange($idForm): renaming detected"); self :: log_debug("$this -> submitChange($idForm): renaming detected");
if (!$this -> fireEvent('before_rename')) { if (!$this -> fireEvent('before_rename')) {
LSerror :: addErrorCode('LSldapObject_16'); LSerror :: addErrorCode('LSldapObject_16');
return; return false;
} }
$oldDn = $this -> getDn(); $oldDn = $this -> getDn();
$this -> dn = false; $this -> dn = false;
@ -754,7 +752,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
self :: log_debug("$this -> submitChange($idForm): Rename me from '$oldDn' to '$newDn'"); self :: log_debug("$this -> submitChange($idForm): Rename me from '$oldDn' to '$newDn'");
if (!LSldap :: move($oldDn, $newDn)) { if (!LSldap :: move($oldDn, $newDn)) {
self :: log_error("$this -> submitChange($idForm): Fail to rename me from '$oldDn' to '$newDn'. Stop."); self :: log_error("$this -> submitChange($idForm): Fail to rename me from '$oldDn' to '$newDn'. Stop.");
return; return false;
} }
$this -> dn = $newDn; $this -> dn = $newDn;
$this -> oldDn = $oldDn; $this -> oldDn = $oldDn;
@ -764,12 +762,12 @@ class LSldapObject extends LSlog_staticLoggerClass {
if (!$this -> fireEvent('after_rename')) { if (!$this -> fireEvent('after_rename')) {
LSerror :: addErrorCode('LSldapObject_17'); LSerror :: addErrorCode('LSldapObject_17');
return; return false;
} }
} }
else { else {
self :: log_error("$this -> submitChange($idForm): fail to retrieve new DN"); self :: log_error("$this -> submitChange($idForm): fail to retrieve new DN");
return; return false;
} }
} }
else { else {
@ -781,7 +779,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
$dn = $this -> getDn(); $dn = $this -> getDn();
if (!$dn) { if (!$dn) {
LSerror :: addErrorCode('LSldapObject_13'); LSerror :: addErrorCode('LSldapObject_13');
return; return false;
} }
$this -> dn = $dn; $this -> dn = $dn;
@ -789,33 +787,33 @@ class LSldapObject extends LSlog_staticLoggerClass {
if ($new) { if ($new) {
// Check DN is not already exist // Check DN is not already exist
if (LSldap :: exists($dn)) { if (LSldap :: exists($dn)) {
return; return false;
} }
if (!$this -> fireEvent('before_create')) { if (!$this -> fireEvent('before_create')) {
LSerror :: addErrorCode('LSldapObject_20'); LSerror :: addErrorCode('LSldapObject_20');
return; return false;
} }
foreach ($submitData as $attr_name => $attr) { foreach ($submitData as $attr_name => $attr) {
if (!$this -> attrs[$attr_name] -> fireEvent('before_create')) { if (!$this -> attrs[$attr_name] -> fireEvent('before_create')) {
LSerror :: addErrorCode('LSldapObject_20'); LSerror :: addErrorCode('LSldapObject_20');
return; return false;
} }
} }
} }
if (!LSldap :: update($this -> getType(),$dn, $submitData)) { if (!LSldap :: update($this -> getType(),$dn, $submitData)) {
self :: log_debug($this." -> submitChange($idForm): LSldap :: update() failed"); self :: log_debug($this." -> submitChange($idForm): LSldap :: update() failed");
return; return false;
} }
self :: log_debug($this." -> submitChange($idForm): changes applied in LDAP"); self :: log_debug($this." -> submitChange($idForm): changes applied in LDAP");
if ($new) { if ($new) {
if (!$this -> fireEvent('after_create')) { if (!$this -> fireEvent('after_create')) {
LSerror :: addErrorCode('LSldapObject_21'); LSerror :: addErrorCode('LSldapObject_21');
return; return false;
} }
foreach ($submitData as $attr_name => $attr) { foreach ($submitData as $attr_name => $attr) {
if (!$this -> attrs[$attr_name] -> fireEvent('after_create')) { if (!$this -> attrs[$attr_name] -> fireEvent('after_create')) {
LSerror :: addErrorCode('LSldapObject_21'); LSerror :: addErrorCode('LSldapObject_21');
return; return false;
} }
} }
} }
@ -834,14 +832,14 @@ class LSldapObject extends LSlog_staticLoggerClass {
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return array Tableau : * @return array|false Tableau :
* - [0] : le premier paramètre * - [0] : le premier paramètre
* - [1] : les paramètres suivants * - [1] : les paramètres suivants
*/ */
public static function getDnInfos($dn) { public static function getDnInfos($dn) {
$infos = ldap_explode_dn($dn, 0); $infos = ldap_explode_dn($dn, 0);
if(!$infos) if(!$infos)
return; return false;
$first = true; $first = true;
$basedn = ""; $basedn = "";
for($i=1; $i<$infos['count']; $i++) for($i=1; $i<$infos['count']; $i++)
@ -870,11 +868,11 @@ class LSldapObject extends LSlog_staticLoggerClass {
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return Net_LDAP2_Filter le filtre ldap correspondant au type de l'objet * @return Net_LDAP2_Filter|false le filtre ldap correspondant au type de l'objet, ou false
*/ */
public static function _getObjectFilter($type) { public static function _getObjectFilter($type) {
$oc=LSconfig::get("LSobjects.$type.objectclass"); $oc=LSconfig::get("LSobjects.$type.objectclass");
if(!is_array($oc)) return; if(!is_array($oc)) return false;
$filters=array(); $filters=array();
foreach ($oc as $class) { foreach ($oc as $class) {
$filters[]=Net_LDAP2_Filter::create('objectClass','equals',$class); $filters[]=Net_LDAP2_Filter::create('objectClass','equals',$class);
@ -889,7 +887,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
if ($filter) if ($filter)
return $filter; return $filter;
LSerror :: addErrorCode('LSldapObject_30',$type); LSerror :: addErrorCode('LSldapObject_30',$type);
return; return false;
} }
/** /**
@ -900,7 +898,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* @param string $pattern Le mot clé recherché * @param string $pattern Le mot clé recherché
* @param bool $approx booléen Booléen activant ou non la recherche approximative * @param bool $approx booléen Booléen activant ou non la recherche approximative
* *
* @return string le filtre ldap correspondant * @return string|null le filtre ldap correspondant ou null si le pattern spécifié et vide
*/ */
public function getPatternFilter($pattern=null,$approx=null) { public function getPatternFilter($pattern=null,$approx=null) {
if ($pattern) { if ($pattern) {
@ -925,12 +923,12 @@ class LSldapObject extends LSlog_staticLoggerClass {
* @param string|null $basedn DN de base pour la recherche * @param string|null $basedn DN de base pour la recherche
* @param array $params Search parameters (as expected by Net_LDAP2::search()) * @param array $params Search parameters (as expected by Net_LDAP2::search())
* *
* @return array Tableau d'objets correspondant au resultat de la recherche * @return array|false Tableau d'objets correspondant au resultat de la recherche, ou false
*/ */
public function listObjects($filter=NULL,$basedn=NULL,$params=array()) { public function listObjects($filter=NULL,$basedn=NULL,$params=array()) {
if (!LSsession :: loadLSclass('LSsearch')) { if (!LSsession :: loadLSclass('LSsearch')) {
LSerror::addErrorCode('LSsession_05','LSsearch'); LSerror::addErrorCode('LSsession_05','LSsearch');
return; return false;
} }
$sparams = array( $sparams = array(
@ -962,12 +960,12 @@ class LSldapObject extends LSlog_staticLoggerClass {
* @param string|false $displayFormat LSformat of objects's display name * @param string|false $displayFormat LSformat of objects's display name
* @param bool $cache Enable/disable cache (default: true) * @param bool $cache Enable/disable cache (default: true)
* *
* @return array Tableau dn => name correspondant au resultat de la recherche * @return array|false Tableau dn => name correspondant au resultat de la recherche, ou false
*/ */
public function listObjectsName($filter=NULL,$sbasedn=NULL,$sparams=array(),$displayFormat=false,$cache=true) { public function listObjectsName($filter=NULL,$sbasedn=NULL,$sparams=array(),$displayFormat=false,$cache=true) {
if (!LSsession :: loadLSclass('LSsearch')) { if (!LSsession :: loadLSclass('LSsearch')) {
LSerror::addErrorCode('LSsession_05','LSsearch'); LSerror::addErrorCode('LSsession_05','LSsearch');
return; return false;
} }
if (!$displayFormat) { if (!$displayFormat) {
@ -1068,7 +1066,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* *
* @param string $val Le nom de la valeur demandee * @param string $val Le nom de la valeur demandee
* *
* @return mixed la valeur demandee ou ' ' si celle-ci est inconnue. * @return string la valeur demandee ou ' ' si celle-ci est inconnue.
*/ */
public function getDisplayValue($val) { public function getDisplayValue($val) {
if(isset($this -> attrs[$val])){ if(isset($this -> attrs[$val])){
@ -1114,7 +1112,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return string Le DN de l'objet * @return string|false Le DN de l'objet, ou false
*/ */
public function getDn() { public function getDn() {
if($this -> dn) { if($this -> dn) {
@ -1131,15 +1129,15 @@ class LSldapObject extends LSlog_staticLoggerClass {
} }
else { else {
LSerror :: addErrorCode('LSldapObject_12', $rdn_attr); LSerror :: addErrorCode('LSldapObject_12', $rdn_attr);
return; return false;
} }
} }
else { else {
LSerror :: addErrorCode('LSldapObject_11',$this -> getType()); LSerror :: addErrorCode('LSldapObject_11',$this -> getType());
return; return false;
} }
} }
return; return false;
} }
} }
@ -1150,7 +1148,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return string Le container DN de l'objet * @return string|false Le container DN de l'objet, ou false
*/ */
public function getContainerDn() { public function getContainerDn() {
$topDn = LSsession :: getTopDn(); $topDn = LSsession :: getTopDn();
@ -1177,7 +1175,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
LSerror :: addErrorCode('LSldapObject_11',$this -> getType()); LSerror :: addErrorCode('LSldapObject_11',$this -> getType());
} }
LSerror :: addErrorCode('LSldapObject_32'); LSerror :: addErrorCode('LSldapObject_32');
return; return false;
} }
/** /**
@ -1211,14 +1209,14 @@ class LSldapObject extends LSlog_staticLoggerClass {
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return string The translated object type label * @return string|false The translated object type label, or false
*/ */
public static function getLabel($type=null) { public static function getLabel($type=null) {
if (is_null($type)) if (is_null($type))
$type = get_called_class(); $type = get_called_class();
self :: log_debug("getLabel($type): LSobjects.$type.label"); self :: log_debug("getLabel($type): LSobjects.$type.label");
$label = LSconfig::get("LSobjects.$type.label"); $label = LSconfig::get("LSobjects.$type.label");
if (!$label) return; if (!$label) return false;
return __($label); return __($label);
} }
@ -1242,7 +1240,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
else { else {
LSerror :: addErrorCode('LSldapObject_18'); LSerror :: addErrorCode('LSldapObject_18');
} }
return; return false;
} }
/** /**
@ -1291,7 +1289,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* Methode créant la liste des objets en relations avec l'objet courant et qui * Methode créant la liste des objets en relations avec l'objet courant et qui
* la met en cache ($this -> _LSrelationsCache) * la met en cache ($this -> _LSrelationsCache)
* *
* @return True en cas de cas ce succès, False sinon. * @return bool True en cas de cas ce succès, False sinon.
*/ */
private function updateLSrelationsCache() { private function updateLSrelationsCache() {
$this -> _LSrelationsCache=array(); $this -> _LSrelationsCache=array();
@ -1311,7 +1309,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
} }
else { else {
self :: log_debug('Problème durant la mise en cache de la relation '.$relation_name); self :: log_debug('Problème durant la mise en cache de la relation '.$relation_name);
return; return false;
} }
} }
} }
@ -1325,7 +1323,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* Cette méthode n'est qu'un exemple et elle doit être certainement réécrite * Cette méthode n'est qu'un exemple et elle doit être certainement réécrite
* pour les objets plus complexe. * pour les objets plus complexe.
* *
* @return True en cas de cas ce succès, False sinon. * @return bool True en cas de cas ce succès, False sinon.
*/ */
private function beforeRename() { private function beforeRename() {
// LSrelations // LSrelations
@ -1339,7 +1337,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* Cette méthode n'est qu'un exemple et elle doit être certainement réécrite * Cette méthode n'est qu'un exemple et elle doit être certainement réécrite
* pour les objets plus complexe. * pour les objets plus complexe.
* *
* @return True en cas de cas ce succès, False sinon. * @return bool True en cas de cas ce succès, False sinon.
*/ */
private function afterRename() { private function afterRename() {
$error = 0; $error = 0;
@ -1370,7 +1368,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* Cette méthode n'est qu'un exemple et elle doit être certainement réécrite * Cette méthode n'est qu'un exemple et elle doit être certainement réécrite
* pour les objets plus complexe. * pour les objets plus complexe.
* *
* @return True en cas de cas ce succès, False sinon. * @return bool True en cas de cas ce succès, False sinon.
*/ */
private function beforeDelete() { private function beforeDelete() {
$return = $this -> updateLSrelationsCache(); $return = $this -> updateLSrelationsCache();
@ -1391,7 +1389,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* Cette méthode n'est qu'un exemple et elle doit être certainement réécrite * Cette méthode n'est qu'un exemple et elle doit être certainement réécrite
* pour les objets plus complexe. * pour les objets plus complexe.
* *
* @return True en cas de cas ce succès, False sinon. * @return bool True en cas de cas ce succès, False sinon.
*/ */
private function afterDelete() { private function afterDelete() {
$error = 0; $error = 0;
@ -1431,7 +1429,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* Cette méthode n'est qu'un exemple et elle doit être certainement réécrite * Cette méthode n'est qu'un exemple et elle doit être certainement réécrite
* pour les objets plus complexe. * pour les objets plus complexe.
* *
* @return True en cas de cas ce succès, False sinon. * @return bool True en cas de cas ce succès, False sinon.
*/ */
private function afterCreate() { private function afterCreate() {
self :: log_debug('after'); self :: log_debug('after');
@ -1479,7 +1477,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* Cette méthode n'est qu'un exemple et elle doit être certainement réécrite * Cette méthode n'est qu'un exemple et elle doit être certainement réécrite
* pour les objets plus complexe. * pour les objets plus complexe.
* *
* @return True en cas de cas ce succès, False sinon. * @return bool True en cas de cas ce succès, False sinon.
*/ */
private function afterModify() { private function afterModify() {
$error = 0; $error = 0;
@ -1501,12 +1499,12 @@ class LSldapObject extends LSlog_staticLoggerClass {
* - soit le dn (par defaut) * - soit le dn (par defaut)
* - soit une des valeurs d'un attribut * - soit une des valeurs d'un attribut
* *
* @return Mixed La valeur clef d'un objet en relation * @return array|false La liste des valeurs clefs d'un objet en relation, ou false
**/ **/
public static function getObjectKeyValueInRelation($object, $objectType, $attrValues='dn') { public static function getObjectKeyValueInRelation($object, $objectType, $attrValues='dn') {
if (!$objectType) { if (!$objectType) {
LSerror :: addErrorCode('LSrelation_05','getObjectKeyValueInRelation'); LSerror :: addErrorCode('LSrelation_05','getObjectKeyValueInRelation');
return; return false;
} }
$keyValues = array(); $keyValues = array();
foreach (ensureIsArray($attrValues) as $attrValue) { foreach (ensureIsArray($attrValues) as $attrValue) {
@ -1542,12 +1540,12 @@ class LSldapObject extends LSlog_staticLoggerClass {
* - soit le dn (par defaut) * - soit le dn (par defaut)
* - soit une des valeurs d'un attribut * - soit une des valeurs d'un attribut
* *
* @return array of $objectType Les objets en relations * @return array|false Array of $objectType Les objets en relations, or false
**/ **/
public function listObjectsInRelation($object, $attr, $objectType, $attrValues='dn') { public function listObjectsInRelation($object, $attr, $objectType, $attrValues='dn') {
if ((!$attr)||(!$objectType)) { if ((!$attr)||(!$objectType)) {
LSerror :: addErrorCode('LSrelation_05','listObjectsInRelation'); LSerror :: addErrorCode('LSrelation_05','listObjectsInRelation');
return; return false;
} }
$keyValues = self :: getObjectKeyValueInRelation($object, $objectType, $attrValues); $keyValues = self :: getObjectKeyValueInRelation($object, $objectType, $attrValues);
if (!empty($keyValues)) { if (!empty($keyValues)) {
@ -1588,18 +1586,18 @@ class LSldapObject extends LSlog_staticLoggerClass {
public function addOneObjectInRelation($object,$attr,$objectType,$attrValue='dn',$canEditFunction=NULL) { public function addOneObjectInRelation($object,$attr,$objectType,$attrValue='dn',$canEditFunction=NULL) {
if ((!$attr)||(!$objectType)) { if ((!$attr)||(!$objectType)) {
LSerror :: addErrorCode('LSrelation_05','addOneObjectInRelation'); LSerror :: addErrorCode('LSrelation_05','addOneObjectInRelation');
return; return false;
} }
if ($object instanceof $objectType) { if ($object instanceof $objectType) {
if ($canEditFunction) { if ($canEditFunction) {
if (!$this -> $canEditFunction()) { if (!$this -> $canEditFunction()) {
LSerror :: addErrorCode('LSsession_11'); LSerror :: addErrorCode('LSsession_11');
return; return false;
} }
} }
elseif (!LSsession::canEdit($this -> getType(), $this -> getDn(), $attr)) { elseif (!LSsession::canEdit($this -> getType(), $this -> getDn(), $attr)) {
LSerror :: addErrorCode('LSsession_11'); LSerror :: addErrorCode('LSsession_11');
return; return false;
} }
if ($this -> attrs[$attr] instanceof LSattribute) { if ($this -> attrs[$attr] instanceof LSattribute) {
if ($attrValue=='dn') { if ($attrValue=='dn') {
@ -1630,7 +1628,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
return true; return true;
} }
} }
return; return false;
} }
/** /**
@ -1653,18 +1651,18 @@ class LSldapObject extends LSlog_staticLoggerClass {
public function deleteOneObjectInRelation($object,$attr,$objectType,$attrValue='dn',$canEditFunction=NULL,$attrValues=null) { public function deleteOneObjectInRelation($object,$attr,$objectType,$attrValue='dn',$canEditFunction=NULL,$attrValues=null) {
if ((!$attr)||(!$objectType)) { if ((!$attr)||(!$objectType)) {
LSerror :: addErrorCode('LSrelation_05','deleteOneObjectInRelation'); LSerror :: addErrorCode('LSrelation_05','deleteOneObjectInRelation');
return; return false;
} }
if ($object instanceof $objectType) { if ($object instanceof $objectType) {
if ($canEditFunction) { if ($canEditFunction) {
if (!$this -> $canEditFunction()) { if (!$this -> $canEditFunction()) {
LSerror :: addErrorCode('LSsession_11'); LSerror :: addErrorCode('LSsession_11');
return; return false;
} }
} }
elseif (!LSsession::canEdit($this -> getType(), $this -> getDn(), $attr)) { elseif (!LSsession::canEdit($this -> getType(), $this -> getDn(), $attr)) {
LSerror :: addErrorCode('LSsession_11'); LSerror :: addErrorCode('LSsession_11');
return; return false;
} }
if ($this -> attrs[$attr] instanceof LSattribute) { if ($this -> attrs[$attr] instanceof LSattribute) {
if (!$attrValues) if (!$attrValues)
@ -1682,7 +1680,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
} }
} }
} }
return; return false;
} }
/** /**
@ -1702,15 +1700,15 @@ class LSldapObject extends LSlog_staticLoggerClass {
public function renameOneObjectInRelation($object, $oldValues, $attr, $objectType, $attrValue='dn') { public function renameOneObjectInRelation($object, $oldValues, $attr, $objectType, $attrValue='dn') {
if ((!$attr)||(!$objectType)) { if ((!$attr)||(!$objectType)) {
LSerror :: addErrorCode('LSrelation_05','renameOneObjectInRelation'); LSerror :: addErrorCode('LSrelation_05','renameOneObjectInRelation');
return; return false;
} }
if (!($object instanceof $objectType)) if (!($object instanceof $objectType))
return; return false;
if (!($this -> attrs[$attr] instanceof LSattribute)) if (!($this -> attrs[$attr] instanceof LSattribute))
return; return false;
$values = ensureIsArray($this -> attrs[$attr] -> getValue()); $values = ensureIsArray($this -> attrs[$attr] -> getValue());
if (!$values) if (!$values)
return; return false;
$updateData = array(); $updateData = array();
$oldValues = ensureIsArray($oldValues); $oldValues = ensureIsArray($oldValues);
foreach($values as $value) { foreach($values as $value) {
@ -1754,14 +1752,14 @@ class LSldapObject extends LSlog_staticLoggerClass {
public function updateObjectsInRelation($object,$listDns,$attr,$objectType,$attrValue='dn',$canEditFunction=NULL,$attrValues=null) { public function updateObjectsInRelation($object,$listDns,$attr,$objectType,$attrValue='dn',$canEditFunction=NULL,$attrValues=null) {
if ((!$attr)||(!$objectType)) { if ((!$attr)||(!$objectType)) {
LSerror :: addErrorCode('LSrelation_05','updateObjectsInRelation'); LSerror :: addErrorCode('LSrelation_05','updateObjectsInRelation');
return; return false;
} }
if (!$attrValues) if (!$attrValues)
$attrValues = array($attrValue); $attrValues = array($attrValue);
$currentDns = array(); $currentDns = array();
$currentObjects = $this -> listObjectsInRelation($object, $attr, $objectType, $attrValues); $currentObjects = $this -> listObjectsInRelation($object, $attr, $objectType, $attrValues);
if(!is_array($currentObjects)) if(!is_array($currentObjects))
return; return false;
for ($i=0; $i<count($currentObjects); $i++) { for ($i=0; $i<count($currentObjects); $i++) {
$currentDns[] = $currentObjects[$i] -> getDn(); $currentDns[] = $currentObjects[$i] -> getDn();
} }
@ -1772,7 +1770,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
for($i=0; $i<count($currentObjects); $i++) { for($i=0; $i<count($currentObjects); $i++) {
if (in_array($currentObjects[$i] -> getDn(), $dontTouch)) continue; if (in_array($currentObjects[$i] -> getDn(), $dontTouch)) continue;
if (!$currentObjects[$i] -> deleteOneObjectInRelation($object, $attr, $objectType, $attrValue, $canEditFunction, $attrValues)) { if (!$currentObjects[$i] -> deleteOneObjectInRelation($object, $attr, $objectType, $attrValue, $canEditFunction, $attrValues)) {
return; return false;
} }
} }
@ -1782,11 +1780,11 @@ class LSldapObject extends LSlog_staticLoggerClass {
$obj = new $type(); $obj = new $type();
if ($obj -> loadData($dn)) { if ($obj -> loadData($dn)) {
if (!$obj -> addOneObjectInRelation($object, $attr, $objectType, $attrValue, $canEditFunction)) { if (!$obj -> addOneObjectInRelation($object, $attr, $objectType, $attrValue, $canEditFunction)) {
return; return false;
} }
} }
else { else {
return; return false;
} }
} }
return true; return true;
@ -2007,7 +2005,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* *
* @param string $attr_name The attribute name * @param string $attr_name The attribute name
* *
* @teval boolean True if object type have a attribute of this name, False otherwise * @return boolean True if object type have a attribute of this name, False otherwise
*/ */
public static function hasAttr($attr_name) { public static function hasAttr($attr_name) {
return array_key_exists($attr_name, LSconfig :: get('LSobjects.'.get_called_class().'.attrs', array())); return array_key_exists($attr_name, LSconfig :: get('LSobjects.'.get_called_class().'.attrs', array()));
@ -2016,7 +2014,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
/** /**
* List IOformats of this object type * List IOformats of this object type
* *
* @return mixed Array of valid IOformats of this object type * @return array Array of valid IOformats of this object type
**/ **/
public function listValidIOformats() { public function listValidIOformats() {
$ret = array(); $ret = array();
@ -2251,11 +2249,11 @@ class LSldapObject extends LSlog_staticLoggerClass {
* @param bool $raw_values Show attributes raw values (instead of display ones) * @param bool $raw_values Show attributes raw values (instead of display ones)
* @param string $prefix Prefix for each line displayed (optional, default: no prefix) * @param string $prefix Prefix for each line displayed (optional, default: no prefix)
* *
* @return string The formated attribute message * @return string|false The formated attribute message, or false
**/ **/
private function _cli_show_attr($attr_name, $raw_values=false, $prefix="") { private function _cli_show_attr($attr_name, $raw_values=false, $prefix="") {
if (!isset($this -> attrs[$attr_name])) if (!isset($this -> attrs[$attr_name]))
return; return false;
$values = ($raw_values?$this -> attrs[$attr_name]->getValue():$this -> attrs[$attr_name]->getDisplayValue()); $values = ($raw_values?$this -> attrs[$attr_name]->getValue():$this -> attrs[$attr_name]->getDisplayValue());
return self :: _cli_show_attr_values($attr_name, $values, $prefix); return self :: _cli_show_attr_values($attr_name, $values, $prefix);
} }
@ -2370,7 +2368,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
/** /**
* CLI remove command * CLI remove command
* *
* @param string $command_args Command arguments : * @param array $command_args Command arguments :
* - Positional arguments : * - Positional arguments :
* - LSobject type * - LSobject type
* - object DN * - object DN

View file

@ -66,7 +66,7 @@ class LSlog_console extends LSlog_handler {
* @return void * @return void
**/ **/
public function logging($level, $message, $logger=null) { public function logging($level, $message, $logger=null) {
return fwrite( fwrite(
(in_array($level, array('INFO', 'DEBUG', 'TRACE'))?$this -> stdout:$this -> stderr), (in_array($level, array('INFO', 'DEBUG', 'TRACE'))?$this -> stdout:$this -> stderr),
$this -> format($level, $message, $logger)."\n" $this -> format($level, $message, $logger)."\n"
); );

View file

@ -77,11 +77,10 @@ class LSlog_email extends LSlog_handler {
**/ **/
public function logging($level, $message, $logger=null) { public function logging($level, $message, $logger=null) {
if ($this -> recipient) if ($this -> recipient)
return error_log( error_log(
$this -> format($level, $message, $logger), $this -> format($level, $message, $logger),
1, 1,
$this -> recipient $this -> recipient
); );
return false;
} }
} }

View file

@ -69,7 +69,7 @@ class LSlog_file extends LSlog_handler {
* @return void * @return void
**/ **/
public function logging($level, $message, $logger=null) { public function logging($level, $message, $logger=null) {
return error_log( error_log(
$this -> format($level, $message, $logger)."\n", $this -> format($level, $message, $logger)."\n",
3, 3,
$this -> path $this -> path

View file

@ -230,8 +230,8 @@ class LSlog_handler extends LSlog_staticLoggerClass {
/** /**
* Log a message * Log a message
* *
* @param array $level The message level * @param string $level The message level
* @param array $message The message * @param string $message The message
* @param string|null $logger The logger name (optional, default: null) * @param string|null $logger The logger name (optional, default: null)
* *
* @return void * @return void

View file

@ -104,7 +104,7 @@ class LSlog_syslog extends LSlog_handler {
* @return void * @return void
**/ **/
public function logging($level, $message, $logger=null) { public function logging($level, $message, $logger=null) {
return syslog( syslog(
$this -> level2priority($level), $this -> level2priority($level),
$this -> format($level, $message, $logger) $this -> format($level, $message, $logger)
); );

View file

@ -51,7 +51,7 @@ class LSgroup extends LSldapObject {
* *
* @param LSldapObject $userObject Un object user (type : $this -> userObjectType) * @param LSldapObject $userObject Un object user (type : $this -> userObjectType)
* *
* @return array[LSgroup] Les groupes de l'utilisateur * @return array<LSgroup> Les groupes de l'utilisateur
**/ **/
public function listUserGroups($userObject) { public function listUserGroups($userObject) {
return $this -> listObjectsInRelation($userObject,$this -> memberAttr,$this -> userObjectType,$this -> memberAttrValue); return $this -> listObjectsInRelation($userObject,$this -> memberAttr,$this -> userObjectType,$this -> memberAttrValue);
@ -95,7 +95,7 @@ class LSgroup extends LSldapObject {
* Met à jour les groupes d'un utilisateur * Met à jour les groupes d'un utilisateur
* *
* @param Mixed $object Un object (type : $this -> userObjectType) : l'utilisateur * @param Mixed $object Un object (type : $this -> userObjectType) : l'utilisateur
* @param array[string] $listDns Array(string) Un tableau des DNs des groupes de l'utilisateur * @param array<string> $listDns Array(string) Un tableau des DNs des groupes de l'utilisateur
* *
* @return boolean true si tout c'est bien passé, False sinon * @return boolean true si tout c'est bien passé, False sinon
**/ **/

View file

@ -372,7 +372,7 @@ class LSrelation extends LSlog_staticLoggerClass {
/** /**
* Get the value to store to created the relation with $this -> obj * Get the value to store to created the relation with $this -> obj
* *
* @return array List of value of the link attribute * @return array|false List of value of the link attribute, or false
*/ */
public function getRelatedKeyValue() { public function getRelatedKeyValue() {
// Check relation is correctly configured // Check relation is correctly configured
@ -447,7 +447,7 @@ class LSrelation extends LSlog_staticLoggerClass {
if (!$this -> correctly_configured) if (!$this -> correctly_configured)
return false; return false;
if (!$this -> canEdit()) return; if (!$this -> canEdit()) return false;
// Use canEdit_function // Use canEdit_function
if ($this -> canEdit_function) { if ($this -> canEdit_function) {
@ -788,7 +788,7 @@ class LSrelation extends LSlog_staticLoggerClass {
* @param LSldapObject &$object Reference to the related LSldapObject * @param LSldapObject &$object Reference to the related LSldapObject
* @param array|string|null $additional_required_parameters List of additional required parameter * @param array|string|null $additional_required_parameters List of additional required parameter
* *
* @return array|false Array with LSobject and LSrelation * @return bool
*/ */
public static function _ajax_check_call(&$data, &$conf, &$object, &$relation, $additional_required_parameters=null) { public static function _ajax_check_call(&$data, &$conf, &$object, &$relation, $additional_required_parameters=null) {
$data['success'] = false; $data['success'] = false;

View file

@ -50,7 +50,7 @@ class LSsearch extends LSlog_staticLoggerClass {
/** /**
* The LdapObject type of search * The LdapObject type of search
* @var string * @var string|null
*/ */
private $LSobject = NULL; private $LSobject = NULL;
@ -227,7 +227,7 @@ class LSsearch extends LSlog_staticLoggerClass {
} }
else else
self :: log_trace("loadParamsFromSession(): no params in session for context ".$this -> context); self :: log_trace("loadParamsFromSession(): no params in session for context ".$this -> context);
return; return false;
} }
/** /**
@ -631,12 +631,12 @@ class LSsearch extends LSlog_staticLoggerClass {
$filter = Net_LDAP2_Filter::parse($value); $filter = Net_LDAP2_Filter::parse($value);
if (Net_LDAP2::isError($filter)) { if (Net_LDAP2::isError($filter)) {
LSerror :: addErrorCode('LSsearch_03', 'filter'); LSerror :: addErrorCode('LSsearch_03', 'filter');
return; return false;
} }
$filter_parts = $filter -> getComponents(); $filter_parts = $filter -> getComponents();
if (!is_array($filter_parts) || !LSsession :: canAccess($this -> LSobject, null, 'r', $filter_parts[0])) { if (!is_array($filter_parts) || !LSsession :: canAccess($this -> LSobject, null, 'r', $filter_parts[0])) {
LSerror :: addErrorCode('LSsearch_03', 'filter'); LSerror :: addErrorCode('LSsearch_03', 'filter');
return; return false;
} }
break; break;
@ -651,11 +651,11 @@ class LSsearch extends LSlog_staticLoggerClass {
foreach(ensureIsArray($value) as $attr) { foreach(ensureIsArray($value) as $attr) {
if (!is_string($attr)) { if (!is_string($attr)) {
LSerror :: addErrorCode('LSsearch_06'); LSerror :: addErrorCode('LSsearch_06');
return; return false;
} }
if (!LSsession :: canAccess($this -> LSobject, null, 'r', $attr)) { if (!LSsession :: canAccess($this -> LSobject, null, 'r', $attr)) {
LSerror :: addErrorCode('LSsearch_11', $attr); LSerror :: addErrorCode('LSsearch_11', $attr);
return; return false;
} }
} }
break; break;
@ -663,7 +663,7 @@ class LSsearch extends LSlog_staticLoggerClass {
case 'displayFormat': case 'displayFormat':
if (!LSsession :: canComputeLSformat($value, $this -> LSobject)) { if (!LSsession :: canComputeLSformat($value, $this -> LSobject)) {
LSerror :: addErrorCode('LSsearch_11', 'displayFormat'); LSerror :: addErrorCode('LSsearch_11', 'displayFormat');
return; return false;
} }
break; break;
} }
@ -714,7 +714,7 @@ class LSsearch extends LSlog_staticLoggerClass {
* *
* @param string|null $pattern The pattern of search. If is null, the pattern in params will be used. * @param string|null $pattern The pattern of search. If is null, the pattern in params will be used.
* *
* @return mixed Net_LDAP2_Filter on success or False * @return Net_LDAP2_Filter|false Net_LDAP2_Filter on success or False
*/ */
public function getFilterFromPattern($pattern=NULL) { public function getFilterFromPattern($pattern=NULL) {
if ($pattern==NULL) { if ($pattern==NULL) {
@ -741,7 +741,7 @@ class LSsearch extends LSlog_staticLoggerClass {
if (empty($attrsList)) { if (empty($attrsList)) {
LSerror :: addErrorCode('LSsearch_07'); LSerror :: addErrorCode('LSsearch_07');
return; return false;
} }
$filters=array(); $filters=array();
@ -768,7 +768,7 @@ class LSsearch extends LSlog_staticLoggerClass {
} }
else { else {
LSerror :: addErrorCode('LSsearch_08',array('attr' => $attr,'pattern' => $pattern)); LSerror :: addErrorCode('LSsearch_08',array('attr' => $attr,'pattern' => $pattern));
return; return false;
} }
} }
if($filters) { if($filters) {
@ -784,7 +784,7 @@ class LSsearch extends LSlog_staticLoggerClass {
else { else {
LSerror :: addErrorCode('LSsearch_10'); LSerror :: addErrorCode('LSsearch_10');
} }
return; return false;
} }
/** /**
@ -991,7 +991,7 @@ class LSsearch extends LSlog_staticLoggerClass {
**/ **/
private function formatSearchParams() { private function formatSearchParams() {
if (!$this -> _searchParams) if (!$this -> _searchParams)
return; return null;
if ($this -> _searchParams['filter'] instanceof Net_LDAP2_Filter) if ($this -> _searchParams['filter'] instanceof Net_LDAP2_Filter)
$return = "filter=".$this -> _searchParams['filter']->asString(); $return = "filter=".$this -> _searchParams['filter']->asString();
else else
@ -1060,7 +1060,7 @@ class LSsearch extends LSlog_staticLoggerClass {
// Check result // Check result
if ($list === false) { if ($list === false) {
LSerror :: addErrorCode('LSsearch_12'); LSerror :: addErrorCode('LSsearch_12');
return; return false;
} }
// Handle onlyAccessible parameter // Handle onlyAccessible parameter
@ -1093,7 +1093,7 @@ class LSsearch extends LSlog_staticLoggerClass {
* @param array $searchParams An optional search params array * @param array $searchParams An optional search params array
* @param boolean $onlyAccessible An optional onlyAccessible boolean flag * @param boolean $onlyAccessible An optional onlyAccessible boolean flag
* *
* @return string The hash of the parameters of the search * @return string|false The hash of the parameters of the search, or false in case of error
**/ **/
public function getHash($searchParams=null, $onlyAccessible=null) { public function getHash($searchParams=null, $onlyAccessible=null) {
if (is_null($searchParams)) { if (is_null($searchParams)) {
@ -1143,7 +1143,7 @@ class LSsearch extends LSlog_staticLoggerClass {
} }
else else
self :: log_trace('getResultFromCache(): cache is disabled.'); self :: log_trace('getResultFromCache(): cache is disabled.');
return; return false;
} }
/** /**
@ -1151,12 +1151,12 @@ class LSsearch extends LSlog_staticLoggerClass {
* *
* @param int $page The number of the page * @param int $page The number of the page
* *
* @return array The information of the page * @return array|false The information of the page, or false in case of error
**/ **/
public function getPage($page=1) { public function getPage($page=1) {
if (!LSsession::loadLSclass('LSsearchEntry')) { if (!LSsession::loadLSclass('LSsearchEntry')) {
LSerror::addErrorCode('LSsession_05',$this -> LSobject); LSerror::addErrorCode('LSsession_05',$this -> LSobject);
return; return false;
} }
$page = (int)$page; $page = (int)$page;
if ($page < 1) if ($page < 1)
@ -1199,14 +1199,14 @@ class LSsearch extends LSlog_staticLoggerClass {
/** /**
* Get search entries * Get search entries
* *
* @return array The entries * @return array|false The entries, or false in case of error
**/ **/
public function getSearchEntries() { public function getSearchEntries() {
if (!LSsession::loadLSclass('LSsearchEntry')) { if (!LSsession::loadLSclass('LSsearchEntry')) {
LSerror::addErrorCode('LSsession_05',$this -> LSobject); LSerror::addErrorCode('LSsession_05',$this -> LSobject);
return; return false;
} }
$retval=array(); $retval = array();
if ($this -> total>0) { if ($this -> total>0) {
$sortTable=$this -> getSortTable(); $sortTable=$this -> getSortTable();
@ -1371,8 +1371,9 @@ class LSsearch extends LSlog_staticLoggerClass {
public function redirectWhenOnlyOneResult() { public function redirectWhenOnlyOneResult() {
if ($this -> total == 1 && $this -> result && self::formIsSubmited()) { if ($this -> total == 1 && $this -> result && self::formIsSubmited()) {
LSurl :: redirect('object/'.$this -> LSobject.'/'.urlencode($this -> result['list'][0]['dn'])); LSurl :: redirect('object/'.$this -> LSobject.'/'.urlencode($this -> result['list'][0]['dn']));
return true;
} }
return; return false;
} }
/** /**
@ -1386,7 +1387,7 @@ class LSsearch extends LSlog_staticLoggerClass {
return true; return true;
} }
if (is_null($this -> params['sortBy'])) { if (is_null($this -> params['sortBy'])) {
return; return false;
} }
if (is_null($this -> params['sortDirection'])) { if (is_null($this -> params['sortDirection'])) {
$this -> params['sortDirection']='ASC'; $this -> params['sortDirection']='ASC';
@ -1409,7 +1410,7 @@ class LSsearch extends LSlog_staticLoggerClass {
if (!LSsession :: loadLSClass('LSsearchEntry')) { if (!LSsession :: loadLSClass('LSsearchEntry')) {
LSerror::addErrorCode('LSsession_05','LSsearchEntry'); LSerror::addErrorCode('LSsession_05','LSsearchEntry');
return; return false;
} }
if (!uasort( if (!uasort(
@ -1417,7 +1418,7 @@ class LSsearch extends LSlog_staticLoggerClass {
array($this,'_sortTwoEntry') array($this,'_sortTwoEntry')
)) { )) {
LSerror :: addErrorCode('LSsearch_13'); LSerror :: addErrorCode('LSsearch_13');
return; return false;
} }
return true; return true;
@ -1439,12 +1440,12 @@ class LSsearch extends LSlog_staticLoggerClass {
/** /**
* List LSsearchEntry objects * List LSsearchEntry objects
* *
* @return array DN associate with name * @return array|false DN associate with name, or false in case of error
**/ **/
public function listEntries() { public function listEntries() {
if (!LSsession::loadLSclass('LSsearchEntry')) { if (!LSsession::loadLSclass('LSsearchEntry')) {
LSerror::addErrorCode('LSsession_05',$this -> LSobject); LSerror::addErrorCode('LSsession_05',$this -> LSobject);
return; return false;
} }
$retval=array(); $retval=array();
@ -1470,12 +1471,12 @@ class LSsearch extends LSlog_staticLoggerClass {
/** /**
* List objects name * List objects name
* *
* @return array DN associate with name * @return array|false DN associate with name, or false in case of error
**/ **/
public function listObjectsName() { public function listObjectsName() {
$entries = $this -> listEntries(); $entries = $this -> listEntries();
if (!is_array($entries)) if (!is_array($entries))
return; return false;
$retval = array(); $retval = array();
foreach($entries as $entry) foreach($entries as $entry)
$retval[$entry -> dn] = $entry -> displayName; $retval[$entry -> dn] = $entry -> displayName;
@ -1770,12 +1771,12 @@ class LSsearch extends LSlog_staticLoggerClass {
/** /**
* Args autocompleter for CLI command search * Args autocompleter for CLI command search
* *
* @param array[string] $command_args List of already typed words of the command * @param array<string> $command_args List of already typed words of the command
* @param int $comp_word_num The command word number to autocomplete * @param int $comp_word_num The command word number to autocomplete
* @param string $comp_word The command word to autocomplete * @param string $comp_word The command word to autocomplete
* @param array[string] $opts List of global available options * @param array<string> $opts List of global available options
* *
* @return array[string] List of available options for the word to autocomplete * @return array<string> List of available options for the word to autocomplete
**/ **/
public static function cli_search_args_autocompleter($command_args, $comp_word_num, $comp_word, $opts) { public static function cli_search_args_autocompleter($command_args, $comp_word_num, $comp_word, $opts) {
$command_opts = array ( $command_opts = array (

View file

@ -39,13 +39,13 @@ class LSsearchEntry extends LSlog_staticLoggerClass {
/** /**
* Reference of the related LSsearch object * Reference of the related LSsearch object
* @var LSsearch * @var LSsearch|null
*/ */
private $LSsearch = NULL; private $LSsearch = NULL;
/** /**
* The LdapObject type of search * The LdapObject type of search
* @var string * @var string|null
*/ */
private $LSobject = NULL; private $LSobject = NULL;
@ -85,7 +85,7 @@ class LSsearchEntry extends LSlog_staticLoggerClass {
* Cached information of the entry * Cached information of the entry
* @var array<string,mixed> * @var array<string,mixed>
*/ */
private array $cache = array(); private $cache = array();
/** /**
* Other values * Other values
@ -100,7 +100,7 @@ class LSsearchEntry extends LSlog_staticLoggerClass {
* *
* @param LSsearch &$LSsearch A reference to the current LSsearch object * @param LSsearch &$LSsearch A reference to the current LSsearch object
* @param string $LSobject The LdapObject type of search * @param string $LSobject The LdapObject type of search
* @param string $params The parameters of the search * @param array $params The parameters of the search
* @param array &$result The data of the search result * @param array &$result The data of the search result
* @param int $id The index of the entry in the search result * @param int $id The index of the entry in the search result
* *

View file

@ -450,9 +450,8 @@ class LSselect extends LSlog_staticLoggerClass {
$editableAttr = self :: getConfig($id, "LSobjects.".$obj->type.".editableAttr"); $editableAttr = self :: getConfig($id, "LSobjects.".$obj->type.".editableAttr");
if (!$editableAttr) if (!$editableAttr)
return true; return true;
if ($editableAttr && call_user_func(array($obj->type, 'hasAttr'), $editableAttr)) { if ($editableAttr && call_user_func(array($obj->type, 'hasAttr'), $editableAttr))
return (LSsession::canEdit($obj->type, $obj->dn, $editableAttr))?1:0; return LSsession::canEdit($obj->type, $obj->dn, $editableAttr);
}
return false; return false;
} }

View file

@ -35,14 +35,14 @@ class LSsession {
/** /**
* Current LDAP server ID * Current LDAP server ID
* @var int * @var int|null
*/ */
private static $ldapServerId = NULL; private static $ldapServerId = NULL;
/** /**
* LDAP servers subDns * LDAP servers subDns
* @see self::getSubDnLdapServer() * @see self::getSubDnLdapServer()
* @var array<int,string> * @var array<string,array>
*/ */
private static $_subDnLdapServer = array(); private static $_subDnLdapServer = array();
@ -54,19 +54,19 @@ class LSsession {
/** /**
* The LSldapObject type of current connected user * The LSldapObject type of current connected user
* @var string * @var string|null
*/ */
private static $LSuserObjectType = NULL; private static $LSuserObjectType = NULL;
/** /**
* Current connected user DN * Current connected user DN
* @var string * @var string|null
*/ */
private static $dn = NULL; private static $dn = NULL;
/** /**
* Current connected user RDN value (his login) * Current connected user RDN value (his login)
* @var string * @var string|null
*/ */
private static $rdn = NULL; private static $rdn = NULL;
@ -158,14 +158,14 @@ class LSsession {
* Current LDAP server config * Current LDAP server config
* (LSconfig.ldap_servers.<idx>) * (LSconfig.ldap_servers.<idx>)
* @see self::setLdapServer() * @see self::setLdapServer()
* @var array * @var array|null
*/ */
public static $ldapServer = NULL; public static $ldapServer = NULL;
/** /**
* The template to display * The template to display
* @see self::setTemplate() * @see self::setTemplate()
* @var string * @var string|null
*/ */
private static $template = NULL; private static $template = NULL;
@ -180,9 +180,9 @@ class LSsession {
/** /**
* The LSldapObject of connected user * The LSldapObject of connected user
* @see self::getLSuserObject() * @see self::getLSuserObject()
* @var LSldapObject * @var LSldapObject|null
*/ */
private static $LSuserObject = NULL; private static $LSuserObject = null;
/** /**
* Initialized session telltale * Initialized session telltale
@ -317,7 +317,7 @@ class LSsession {
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return true si tout c'est bien passé, false sinon * @return bool true si tout c'est bien passé, false sinon
*/ */
private static function startLSconfig() { private static function startLSconfig() {
if (self :: loadLSclass('LSconfig')) { if (self :: loadLSclass('LSconfig')) {
@ -334,7 +334,7 @@ class LSsession {
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return true si tout c'est bien passé, false sinon * @return bool true si tout c'est bien passé, false sinon
*/ */
private static function startLSlog() { private static function startLSlog() {
if (self :: loadLSclass('LSlog')) { if (self :: loadLSclass('LSlog')) {
@ -463,7 +463,7 @@ class LSsession {
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return True on success, false otherwise * @return bool true on success, false otherwise
*/ */
private static function startLSurl() { private static function startLSurl() {
if (self :: loadLSclass('LSurl') && self :: includeFile(LS_INCLUDE_DIR . "routes.php")) { if (self :: loadLSclass('LSurl') && self :: includeFile(LS_INCLUDE_DIR . "routes.php")) {
@ -477,7 +477,7 @@ class LSsession {
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return True on success, false otherwise * @return bool true on success, false otherwise
*/ */
private static function startLStemplate() { private static function startLStemplate() {
if ( self :: loadLSclass('LStemplate') ) { if ( self :: loadLSclass('LStemplate') ) {
@ -539,11 +539,11 @@ class LSsession {
* *
* @author Benjamin Renard <brenard@easter-eggs.com * @author Benjamin Renard <brenard@easter-eggs.com
* *
* @return True on success, false otherwise * @return bool True on success, false otherwise
*/ */
private static function startLSerror() { private static function startLSerror() {
if(!self :: loadLSclass('LSerror')) { if(!self :: loadLSclass('LSerror')) {
return; return false;
} }
self :: defineLSerrors(); self :: defineLSerrors();
return true; return true;
@ -653,12 +653,12 @@ class LSsession {
self :: log_debug("loadLSaddon($addon): config file '$conf_file' not found."); self :: log_debug("loadLSaddon($addon): config file '$conf_file' not found.");
if (!call_user_func('LSaddon_'. $addon .'_support')) { if (!call_user_func('LSaddon_'. $addon .'_support')) {
LSerror :: addErrorCode('LSsession_02',$addon); LSerror :: addErrorCode('LSsession_02',$addon);
return; return false;
} }
self :: $loadedAddons[] = $addon; self :: $loadedAddons[] = $addon;
return true; return true;
} }
return; return false;
} }
@ -687,7 +687,7 @@ class LSsession {
* *
* @author Benjamin Renard <brenard@easter-eggs.com * @author Benjamin Renard <brenard@easter-eggs.com
* *
* @return True on success, false otherwise * @return bool True on success, false otherwise
*/ */
public static function loadLSauth() { public static function loadLSauth() {
if (self :: loadLSclass('LSauth')) { if (self :: loadLSclass('LSauth')) {
@ -696,7 +696,7 @@ class LSsession {
else { else {
LSerror :: addErrorCode('LSsession_05','LSauth'); LSerror :: addErrorCode('LSsession_05','LSauth');
} }
return; return false;
} }
/** /**
@ -713,7 +713,7 @@ class LSsession {
else { else {
LSerror :: addErrorCode('LSsession_05','LScli'); LSerror :: addErrorCode('LSsession_05','LScli');
} }
return; return false;
} }
/** /**
@ -727,7 +727,7 @@ class LSsession {
$conf = LSconfig :: get('LSaddons.loads'); $conf = LSconfig :: get('LSaddons.loads');
if(!is_array($conf)) { if(!is_array($conf)) {
LSerror :: addErrorCode('LSsession_01',"LSaddons['loads']"); LSerror :: addErrorCode('LSsession_01',"LSaddons['loads']");
return; return false;
} }
$error = false; $error = false;
@ -751,7 +751,7 @@ class LSsession {
*/ */
private static function startLSlang($lang=null, $encoding=null) { private static function startLSlang($lang=null, $encoding=null) {
if(!self :: loadLSclass('LSlang')) { if(!self :: loadLSclass('LSlang')) {
return; return false;
} }
LSlang :: setLocale($lang, $encoding); LSlang :: setLocale($lang, $encoding);
return true; return true;
@ -770,7 +770,7 @@ class LSsession {
return true; return true;
try { try {
if (!self :: startLSconfig()) { if (!self :: startLSconfig()) {
return; return false;
} }
self :: startLSerror(); self :: startLSerror();
@ -810,7 +810,7 @@ class LSsession {
*/ */
public static function startLSsession() { public static function startLSsession() {
if (!self :: initialize()) { if (!self :: initialize()) {
return; return false;
} }
if(isset($_SESSION['LSsession']['LSuserObjectType']) && isset($_SESSION['LSsession']['dn']) && !isset($_GET['LSsession_recoverPassword'])) { if(isset($_SESSION['LSsession']['LSuserObjectType']) && isset($_SESSION['LSsession']['dn']) && !isset($_GET['LSsession_recoverPassword'])) {
@ -828,22 +828,22 @@ class LSsession {
self :: setLdapServer(self :: $ldapServerId); self :: setLdapServer(self :: $ldapServerId);
if (!LSauth :: start()) { if (!LSauth :: start()) {
self :: log_error("startLSsession(): can't start LSauth -> stop"); self :: log_error("startLSsession(): can't start LSauth -> stop");
return; return false;
} }
self :: $LSprofiles = $_SESSION['LSsession']['LSprofiles']; self :: $LSprofiles = $_SESSION['LSsession']['LSprofiles'];
self :: $LSaccess = $_SESSION['LSsession']['LSaccess']; self :: $LSaccess = $_SESSION['LSsession']['LSaccess'];
self :: $LSaddonsViewsAccess = $_SESSION['LSsession']['LSaddonsViewsAccess']; self :: $LSaddonsViewsAccess = $_SESSION['LSsession']['LSaddonsViewsAccess'];
if (!self :: LSldapConnect()) if (!self :: LSldapConnect())
return; return false;
} }
else { else {
self :: setLdapServer(self :: $ldapServerId); self :: setLdapServer(self :: $ldapServerId);
if (!LSauth :: start()) { if (!LSauth :: start()) {
self :: log_error("startLSsession(): can't start LSauth -> stop"); self :: log_error("startLSsession(): can't start LSauth -> stop");
return; return false;
} }
if (!self :: LSldapConnect()) if (!self :: LSldapConnect())
return; return false;
self :: loadLSprofiles(); self :: loadLSprofiles();
} }
@ -852,7 +852,7 @@ class LSsession {
} }
if (!self :: loadLSobject(self :: $LSuserObjectType)) { if (!self :: loadLSobject(self :: $LSuserObjectType)) {
return; return false;
} }
LStemplate :: assign('globalSearch', self :: globalSearch()); LStemplate :: assign('globalSearch', self :: globalSearch());
@ -876,7 +876,7 @@ class LSsession {
// Redirect user on home page // Redirect user on home page
LSurl :: redirect(); LSurl :: redirect();
return; return false;
} }
if ( !self :: cacheLSprofiles() || isset($_REQUEST['LSsession_refresh']) ) { if ( !self :: cacheLSprofiles() || isset($_REQUEST['LSsession_refresh']) ) {
@ -920,7 +920,7 @@ class LSsession {
if (!LSauth :: start()) { if (!LSauth :: start()) {
self :: log_error("startLSsession(): can't start LSauth -> stop"); self :: log_error("startLSsession(): can't start LSauth -> stop");
return; return false;
} }
if (isset($_GET['LSsession_recoverPassword'])) { if (isset($_GET['LSsession_recoverPassword'])) {
@ -946,7 +946,7 @@ class LSsession {
self :: $ldapServer['useAuthzProxyControl'] self :: $ldapServer['useAuthzProxyControl']
) { ) {
if (!LSldap :: setAuthzProxyControl(self :: $dn)) { if (!LSldap :: setAuthzProxyControl(self :: $dn)) {
return; return false;
} }
} }
else { else {
@ -954,7 +954,7 @@ class LSsession {
if (!is_array(self :: $userLDAPcreds)) { if (!is_array(self :: $userLDAPcreds)) {
LSerror :: addErrorCode('LSsession_14'); LSerror :: addErrorCode('LSsession_14');
self :: $userLDAPcreds = false; self :: $userLDAPcreds = false;
return; return false;
} }
if (!LSldap :: reconnectAs( if (!LSldap :: reconnectAs(
self :: $userLDAPcreds['dn'], self :: $userLDAPcreds['dn'],
@ -962,7 +962,7 @@ class LSsession {
self :: $ldapServer['ldap_config'] self :: $ldapServer['ldap_config']
)) { )) {
LSerror :: addErrorCode('LSsession_15'); LSerror :: addErrorCode('LSsession_15');
return; return false;
} }
} }
} }
@ -993,7 +993,7 @@ class LSsession {
self :: setTemplate('base.tpl'); self :: setTemplate('base.tpl');
LSerror :: addErrorCode('LSsession_10'); LSerror :: addErrorCode('LSsession_10');
} }
return; return false;
} }
} }
@ -1003,9 +1003,9 @@ class LSsession {
* @return boolean True if intialized, false otherwise. * @return boolean True if intialized, false otherwise.
*/ */
public static function startCliLSsession() { public static function startCliLSsession() {
if (php_sapi_name() != "cli") return; if (php_sapi_name() != "cli") return false;
if (!self :: initialize()) return; if (!self :: initialize()) return false;
if (!self :: loadLScli()) return; if (!self :: loadLScli()) return false;
return True; return True;
} }
@ -1015,19 +1015,19 @@ class LSsession {
* @param string $username The submited username * @param string $username The submited username
* @param string $recoveryHash The submited recoveryHash * @param string $recoveryHash The submited recoveryHash
* *
* @return array The recoveryPassword infos for template * @return array|false The recoveryPassword infos for template, or false in case of error
**/ **/
private static function recoverPasswd($username, $recoveryHash) { private static function recoverPasswd($username, $recoveryHash) {
// Check feature is enabled and LSmail available // Check feature is enabled and LSmail available
if (!isset(self :: $ldapServer['recoverPassword']) || !self :: loadLSaddon('mail')) { if (!isset(self :: $ldapServer['recoverPassword']) || !self :: loadLSaddon('mail')) {
LSerror :: addErrorCode('LSsession_18'); LSerror :: addErrorCode('LSsession_18');
return; return false;
} }
// Start LSauth // Start LSauth
if (!LSauth :: start()) { if (!LSauth :: start()) {
self :: log_error("recoverPasswd(): can't start LSauth -> stop"); self :: log_error("recoverPasswd(): can't start LSauth -> stop");
return; return false;
} }
// Search user by recoveryHash or username // Search user by recoveryHash or username
@ -1051,11 +1051,11 @@ class LSsession {
elseif (!empty($username)) { elseif (!empty($username)) {
$users = LSauth :: username2LSobjects($username); $users = LSauth :: username2LSobjects($username);
if (!is_array($users)) if (!is_array($users))
return; return false;
} }
else { else {
self :: log_debug('recoverPasswd(): no username or recoveryHash provided.'); self :: log_debug('recoverPasswd(): no username or recoveryHash provided.');
return; return false;
} }
// Check user found (and not duplicated) // Check user found (and not duplicated)
@ -1063,12 +1063,12 @@ class LSsession {
if ($nbresult == 0) { if ($nbresult == 0) {
self :: log_debug('recoverPasswd(): incorrect hash/username'); self :: log_debug('recoverPasswd(): incorrect hash/username');
LSerror :: addErrorCode('LSsession_06'); LSerror :: addErrorCode('LSsession_06');
return; return false;
} }
elseif ($nbresult > 1) { elseif ($nbresult > 1) {
self :: log_debug("recoverPasswd(): duplicated user found with hash='$recoveryHash' / username='$username'"); self :: log_debug("recoverPasswd(): duplicated user found with hash='$recoveryHash' / username='$username'");
LSerror :: addErrorCode('LSsession_07'); LSerror :: addErrorCode('LSsession_07');
return; return false;
} }
$user = array_pop($users); $user = array_pop($users);
@ -1083,7 +1083,7 @@ class LSsession {
if (!checkEmail($emailAddress)) { if (!checkEmail($emailAddress)) {
LSerror :: addErrorCode('LSsession_19'); LSerror :: addErrorCode('LSsession_19');
return; return false;
} }
self :: log_debug("recoverPasswd(): Email = '$emailAddress'"); self :: log_debug("recoverPasswd(): Email = '$emailAddress'");
self :: $dn = $user -> getDn(); self :: $dn = $user -> getDn();
@ -1148,7 +1148,7 @@ class LSsession {
if (!sendMail($mail,$subject,$msg,$sendParams)) { if (!sendMail($mail,$subject,$msg,$sendParams)) {
self :: log_debug("recoverPasswdSendMail($mail, $step): error sending email."); self :: log_debug("recoverPasswdSendMail($mail, $step): error sending email.");
LSerror :: addErrorCode('LSsession_20',4); LSerror :: addErrorCode('LSsession_20',4);
return; return false;
} }
return true; return true;
} }
@ -1159,7 +1159,7 @@ class LSsession {
* *
* @param LSldapObject $user The LSldapObject of the user * @param LSldapObject $user The LSldapObject of the user
* *
* @return string|False The recory hash on success or False * @return string|false The recory hash on success or False
**/ **/
private static function recoverPasswdFirstStep($user) { private static function recoverPasswdFirstStep($user) {
// Generer un hash // Generer un hash
@ -1191,7 +1191,7 @@ class LSsession {
self :: log_error("recoverPasswdFirstStep($user): error validating form."); self :: log_error("recoverPasswdFirstStep($user): error validating form.");
LSerror :: addErrorCode('LSsession_20',5); LSerror :: addErrorCode('LSsession_20',5);
} }
return; return false;
} }
/** /**
@ -1199,7 +1199,7 @@ class LSsession {
* *
* @param LSldapObject $user The LSldapObject of the user * @param LSldapObject $user The LSldapObject of the user
* *
* @return string|False The new password on success or False * @return string|false The new password on success or False
**/ **/
private static function recoverPasswdSecondStep($user) { private static function recoverPasswdSecondStep($user) {
$pwd_attr_name = LSauth :: getUserPasswordAttribute($user); $pwd_attr_name = LSauth :: getUserPasswordAttribute($user);
@ -1239,7 +1239,7 @@ class LSsession {
self :: log_error("recoverPasswdSecondStep($user): password attribute '$pwd_attr_name' does not exists."); self :: log_error("recoverPasswdSecondStep($user): password attribute '$pwd_attr_name' does not exists.");
LSerror :: addErrorCode('LSsession_20',1); LSerror :: addErrorCode('LSsession_20',1);
} }
return; return false;
} }
/** /**
@ -1285,7 +1285,7 @@ class LSsession {
"getLSuserObject($dn): Fail to retrieve current connected user ". "getLSuserObject($dn): Fail to retrieve current connected user ".
"information from LDAP" "information from LDAP"
); );
return; return false;
} }
} }
else { else {
@ -1293,7 +1293,7 @@ class LSsession {
"getLSuserObject($dn): Current connected user object type not ". "getLSuserObject($dn): Current connected user object type not ".
"defined or can not be loaded (".self :: $LSuserObjectType.")" "defined or can not be loaded (".self :: $LSuserObjectType.")"
); );
return; return false;
} }
} }
return self :: $LSuserObject; return self :: $LSuserObject;
@ -1335,14 +1335,14 @@ class LSsession {
self :: log_error( self :: log_error(
"changeAuthUser(): An LSldapObject must be provided, not ".get_class($object) "changeAuthUser(): An LSldapObject must be provided, not ".get_class($object)
); );
return; return false;
} }
if(!array_key_exists($object -> getType(), LSauth :: getAuthObjectTypes())) { if(!array_key_exists($object -> getType(), LSauth :: getAuthObjectTypes())) {
self :: log_error( self :: log_error(
"changeAuthUser(): Invalid object provided, must be one of following types (not a ". "changeAuthUser(): Invalid object provided, must be one of following types (not a ".
$object -> getType().') : '.implode(', ', array_keys(LSauth :: getAuthObjectTypes())) $object -> getType().') : '.implode(', ', array_keys(LSauth :: getAuthObjectTypes()))
); );
return; return false;
} }
self :: log_info( self :: log_info(
"Change authenticated user info ('".self :: $dn."' -> '".$object -> getDn()."')" "Change authenticated user info ('".self :: $dn."' -> '".$object -> getDn()."')"
@ -1364,7 +1364,7 @@ class LSsession {
return true; return true;
} }
self :: log_error("Fail to reload LSprofiles after updating auth user info."); self :: log_error("Fail to reload LSprofiles after updating auth user info.");
return; return false;
} }
/** /**
@ -1407,7 +1407,7 @@ class LSsession {
$_SESSION['LSsession']['topDn'] = $subDn; $_SESSION['LSsession']['topDn'] = $subDn;
return true; return true;
} }
return; return false;
} }
/** /**
@ -1417,12 +1417,15 @@ class LSsession {
*/ */
public static function LSldapConnect() { public static function LSldapConnect() {
if (!self :: $ldapServer && !self :: setLdapServer(0)) { if (!self :: $ldapServer && !self :: setLdapServer(0)) {
return; return false;
}
if (!self :: $ldapServer) {
LSerror :: addErrorCode('LSsession_03');
return false;
} }
if (self :: $ldapServer) {
self :: includeFile(LSconfig :: get('NetLDAP2'), true); self :: includeFile(LSconfig :: get('NetLDAP2'), true);
if (!self :: loadLSclass('LSldap')) { if (!self :: loadLSclass('LSldap')) {
return; return false;
} }
if ( if (
self :: $dn && isset(self :: $ldapServer['useUserCredentials']) && self :: $dn && isset(self :: $ldapServer['useUserCredentials']) &&
@ -1438,7 +1441,7 @@ class LSsession {
!LSldap :: setAuthzProxyControl(self :: $dn) !LSldap :: setAuthzProxyControl(self :: $dn)
) { ) {
LSerror :: addErrorCode('LSsession_15'); LSerror :: addErrorCode('LSsession_15');
return; return false;
} }
} }
else { else {
@ -1452,17 +1455,7 @@ class LSsession {
else { else {
LSldap :: connect(self :: $ldapServer['ldap_config']); LSldap :: connect(self :: $ldapServer['ldap_config']);
} }
if (LSldap :: isConnected()) { return LSldap :: isConnected();
return true;
}
else {
return;
}
}
else {
LSerror :: addErrorCode('LSsession_03');
return;
}
} }
/** /**
@ -1472,10 +1465,10 @@ class LSsession {
**/ **/
public static function subDnIsEnabled() { public static function subDnIsEnabled() {
if (!isset(self :: $ldapServer['subDn'])) { if (!isset(self :: $ldapServer['subDn'])) {
return; return false;
} }
if ( !is_array(self :: $ldapServer['subDn']) ) { if ( !is_array(self :: $ldapServer['subDn']) ) {
return; return false;
} }
return true; return true;
} }
@ -1588,12 +1581,12 @@ class LSsession {
/** /**
* Retrieve HTML options of current LDAP server topDNs * Retrieve HTML options of current LDAP server topDNs
* *
* @return string HTML options of current LDAP server topDNs * @return string|false HTML options of current LDAP server topDNs, or false in case of error
*/ */
public static function getSubDnLdapServerOptions($selected=NULL, $login=false) { public static function getSubDnLdapServerOptions($selected=NULL, $login=false) {
$list = self :: getSubDnLdapServer($login); $list = self :: getSubDnLdapServer($login);
if (!$list) if (!$list)
return; return false;
asort($list); asort($list);
$options = array(); $options = array();
foreach($list as $dn => $txt) { foreach($list as $dn => $txt) {
@ -1624,7 +1617,7 @@ class LSsession {
} // end if } // end if
} // end foreach } // end foreach
} // end if } // end if
return; return false;
} }
/** /**
@ -2016,7 +2009,7 @@ class LSsession {
* array is returned. * array is returned.
* *
* @param string $LSobject The default LSobject type * @param string $LSobject The default LSobject type
* @param array[LSldapObject] $set Array of LSobjects * @param array<LSldapObject> $set Array of LSobjects
* @param array $filter_def Definition of the search filter for reduction * @param array $filter_def Definition of the search filter for reduction
* @param string|null $basedn Base DN for search, null by default * @param string|null $basedn Base DN for search, null by default
* *
@ -2127,7 +2120,7 @@ class LSsession {
private static function loadLSprofiles() { private static function loadLSprofiles() {
if (!is_array(self :: $ldapServer['LSprofiles'])) { if (!is_array(self :: $ldapServer['LSprofiles'])) {
self :: log_warning('loadLSprofiles(): Current LDAP server have no configured LSprofile.'); self :: log_warning('loadLSprofiles(): Current LDAP server have no configured LSprofile.');
return; return false;
} }
self :: log_trace("loadLSprofiles(): Current LDAP server LSprofile configuration: ".varDump(self :: $ldapServer['LSprofiles'])); self :: log_trace("loadLSprofiles(): Current LDAP server LSprofile configuration: ".varDump(self :: $ldapServer['LSprofiles']));
foreach (self :: $ldapServer['LSprofiles'] as $profile => $profileInfos) { foreach (self :: $ldapServer['LSprofiles'] as $profile => $profileInfos) {
@ -2373,14 +2366,14 @@ class LSsession {
} }
} }
} }
return; return false;
} }
/** /**
* Check if user is at least one of specified profiles on specified DN * Check if user is at least one of specified profiles on specified DN
* *
* @param string $dn DN of the object to check * @param string $dn DN of the object to check
* @param array[string] $profiles The profiles list * @param array<string> $profiles The profiles list
* *
* @return boolean True if user is at least one of specified profiles on specified DN, false otherwise. * @return boolean True if user is at least one of specified profiles on specified DN, false otherwise.
*/ */
@ -2434,7 +2427,7 @@ class LSsession {
*/ */
public static function canAccess($LSobject, $dn=NULL, $right=NULL, $attr=NULL) { public static function canAccess($LSobject, $dn=NULL, $right=NULL, $attr=NULL) {
if (!self :: loadLSobject($LSobject)) { if (!self :: loadLSobject($LSobject)) {
return; return false;
} }
// Access always granted in CLI mode // Access always granted in CLI mode
@ -2446,7 +2439,7 @@ class LSsession {
if ($dn == self :: getLSuserObject() -> getValue('dn')) { if ($dn == self :: getLSuserObject() -> getValue('dn')) {
if (!self :: in_menu('SELF')) { if (!self :: in_menu('SELF')) {
self :: log_trace("canAccess('$LSobject', '$dn', '$right', '$attr'): SELF not in menu"); self :: log_trace("canAccess('$LSobject', '$dn', '$right', '$attr'): SELF not in menu");
return; return false;
} }
} }
else { else {
@ -2454,7 +2447,7 @@ class LSsession {
$obj -> dn = $dn; $obj -> dn = $dn;
if (!self :: in_menu($LSobject,$obj -> subDnValue)) { if (!self :: in_menu($LSobject,$obj -> subDnValue)) {
self :: log_trace("canAccess('$LSobject', '$dn', '$right', '$attr'): $LSobject (for subDN='".$obj -> subDnValue."') not in menu"); self :: log_trace("canAccess('$LSobject', '$dn', '$right', '$attr'): $LSobject (for subDN='".$obj -> subDnValue."') not in menu");
return; return false;
} }
} }
} }
@ -2472,7 +2465,7 @@ class LSsession {
} }
if (!is_array(LSconfig :: get('LSobjects.'.$LSobject.'.attrs.'.$attr))) { if (!is_array(LSconfig :: get('LSobjects.'.$LSobject.'.attrs.'.$attr))) {
self :: log_warning("canAccess('$LSobject', '$dn', '$right', '$attr'): Attribute '$attr' doesn't exists"); self :: log_warning("canAccess('$LSobject', '$dn', '$right', '$attr'): Attribute '$attr' doesn't exists");
return; return false;
} }
$r = 'n'; $r = 'n';
@ -2491,15 +2484,10 @@ class LSsession {
} }
self :: log_trace("canAccess($LSobject,$dn,$right,$attr): right detected = '$r'"); self :: log_trace("canAccess($LSobject,$dn,$right,$attr): right detected = '$r'");
if (($right=='r')||($right=='w')) { if ($right == 'r' || $right=='w')
return self :: checkRight($right, $r); return self :: checkRight($right, $r);
}
else { return ($r == 'r' || $r == 'w');
if ( ($r=='r') || ($r=='w') ) {
return true;
}
return;
}
} }
// On any attributes // On any attributes
@ -2524,7 +2512,7 @@ class LSsession {
} }
} }
} }
return; return false;
} }
/** /**
@ -2575,10 +2563,10 @@ class LSsession {
*/ */
public static function canCreate($LSobject) { public static function canCreate($LSobject) {
if (!self :: loadLSobject($LSobject)) { if (!self :: loadLSobject($LSobject)) {
return; return false;
} }
if (LSconfig :: get("LSobjects.$LSobject.disable_creation")) { if (LSconfig :: get("LSobjects.$LSobject.disable_creation")) {
return; return false;
} }
return self :: canAccess($LSobject,NULL,'w','rdn'); return self :: canAccess($LSobject,NULL,'w','rdn');
} }
@ -2613,7 +2601,7 @@ class LSsession {
$relConf=LSconfig :: get('LSobjects.'.$LSobject.'.LSrelation.'.$relationName); $relConf=LSconfig :: get('LSobjects.'.$LSobject.'.LSrelation.'.$relationName);
if (!is_array($relConf)) { if (!is_array($relConf)) {
self :: log_trace("relationCanAccess($dn,$LSobject,$relationName,$right): unknown relation"); self :: log_trace("relationCanAccess($dn,$LSobject,$relationName,$right): unknown relation");
return; return false;
} }
// Access always granted in CLI mode // Access always granted in CLI mode
@ -2652,7 +2640,7 @@ class LSsession {
} }
} }
} }
return; return false;
} }
/** /**
@ -2680,7 +2668,7 @@ class LSsession {
public static function canExecuteCustomAction($dn, $LSobject, $customActionName) { public static function canExecuteCustomAction($dn, $LSobject, $customActionName) {
$conf=LSconfig :: get('LSobjects.'.$LSobject.'.customActions.'.$customActionName); $conf=LSconfig :: get('LSobjects.'.$LSobject.'.customActions.'.$customActionName);
if (!is_array($conf)) if (!is_array($conf))
return; return false;
// Access always granted in CLI mode // Access always granted in CLI mode
if (php_sapi_name() == "cli") if (php_sapi_name() == "cli")
@ -2696,7 +2684,7 @@ class LSsession {
} }
} }
return; return false;
} }
/** /**
@ -2710,7 +2698,7 @@ class LSsession {
public static function canExecuteLSsearchCustomAction($LSsearch,$customActionName) { public static function canExecuteLSsearchCustomAction($LSsearch,$customActionName) {
$conf=LSconfig :: get('LSobjects.'.$LSsearch -> LSobject.'.LSsearch.customActions.'.$customActionName); $conf=LSconfig :: get('LSobjects.'.$LSsearch -> LSobject.'.LSsearch.customActions.'.$customActionName);
if (!is_array($conf)) if (!is_array($conf))
return; return false;
// Access always granted in CLI mode // Access always granted in CLI mode
if (php_sapi_name() == "cli") if (php_sapi_name() == "cli")
@ -2729,7 +2717,7 @@ class LSsession {
} }
} }
return; return false;
} }
/** /**
@ -2743,7 +2731,7 @@ class LSsession {
public static function canAccessLSaddonView($LSaddon,$viewId) { public static function canAccessLSaddonView($LSaddon,$viewId) {
if (self :: loadLSaddon($LSaddon)) { if (self :: loadLSaddon($LSaddon)) {
if (!isset(self :: $LSaddonsViews[$LSaddon]) || !isset(self :: $LSaddonsViews[$LSaddon][$viewId])) if (!isset(self :: $LSaddonsViews[$LSaddon]) || !isset(self :: $LSaddonsViews[$LSaddon][$viewId]))
return; return false;
if (!is_array(self :: $LSaddonsViews[$LSaddon][$viewId]['allowedLSprofiles'])) { if (!is_array(self :: $LSaddonsViews[$LSaddon][$viewId]['allowedLSprofiles'])) {
return true; return true;
} }
@ -2757,7 +2745,7 @@ class LSsession {
} }
} }
} }
return; return false;
} }
@ -3255,7 +3243,7 @@ class LSsession {
* @param string $viewId The view ID * @param string $viewId The view ID
* @param string $label The view's label * @param string $label The view's label
* @param callable $viewFunction The view's function name * @param callable $viewFunction The view's function name
* @param array[string]|null $allowedLSprofiles Array listing allowed profiles. * @param array<string>|null $allowedLSprofiles Array listing allowed profiles.
* If null, no access control will * If null, no access control will
* be done for this view. * be done for this view.
* @param boolean $showInMenu Show (or not) this view in menu * @param boolean $showInMenu Show (or not) this view in menu

View file

@ -97,13 +97,13 @@ class LStemplate extends LSlog_staticLoggerClass {
* Smarty object * Smarty object
* @var Smarty * @var Smarty
*/ */
public static $_smarty = NULL; public static $_smarty;
/** /**
* Smarty version * Smarty version
* @var int * @var int
*/ */
private static $_smarty_version = NULL; private static $_smarty_version;
/** /**
* Array of directories where file have to be search * Array of directories where file have to be search
@ -166,7 +166,7 @@ class LStemplate extends LSlog_staticLoggerClass {
// cache files are always regenerated // cache files are always regenerated
self :: $_smarty -> force_compile = TRUE; self :: $_smarty -> force_compile = TRUE;
// recompile template if it is changed // recompile template if it is changed
self :: $_smarty -> compile_check = TRUE; self :: $_smarty -> compile_check = 1;
if (self :: $config['debug_smarty']) { if (self :: $config['debug_smarty']) {
// debug smarty // debug smarty
self :: $_smarty -> debugging = true; self :: $_smarty -> debugging = true;
@ -237,7 +237,7 @@ class LStemplate extends LSlog_staticLoggerClass {
* @param string|null $default_dir The default directory (eg: default) * @param string|null $default_dir The default directory (eg: default)
* @param bool $with_nocache If true, include nocache URL param (default: false) * @param bool $with_nocache If true, include nocache URL param (default: false)
* *
* @return string The path of the file * @return string|false The path of the file, or false if file can't be located
**/ **/
public static function getFilePath($file, $root_dir, $default_dir=null, $with_nocache=false) { public static function getFilePath($file, $root_dir, $default_dir=null, $with_nocache=false) {
if ($default_dir === null) if ($default_dir === null)
@ -264,7 +264,7 @@ class LStemplate extends LSlog_staticLoggerClass {
} }
if (!$path) { if (!$path) {
if (!$default_dir) if (!$default_dir)
return; return false;
$path = $root_dir.'/'.$default_dir.'/'.$file; $path = $root_dir.'/'.$default_dir.'/'.$file;
} }
if ($with_nocache) if ($with_nocache)
@ -385,7 +385,7 @@ class LStemplate extends LSlog_staticLoggerClass {
* *
* @param string $template The template name (eg: base.tpl) * @param string $template The template name (eg: base.tpl)
* *
* @return string The timestamp of the last change of the Smarty template file * @return int|null The timestamp of the last change of the Smarty template file
**/ **/
public static function getTemplateTimestamp($template) { public static function getTemplateTimestamp($template) {
$tpl_path=self :: getTemplatePath($template); $tpl_path=self :: getTemplatePath($template);
@ -394,7 +394,7 @@ class LStemplate extends LSlog_staticLoggerClass {
if ($time) if ($time)
return $time; return $time;
} }
return NULL; return null;
} }
/** /**
@ -406,7 +406,7 @@ class LStemplate extends LSlog_staticLoggerClass {
* @return void * @return void
**/ **/
public static function assign($name,$value) { public static function assign($name,$value) {
return self :: $_smarty -> assign($name,$value); self :: $_smarty -> assign($name,$value);
} }
/** /**

View file

@ -45,16 +45,6 @@ class Smarty_Resource_LdapSaisie extends Smarty_Resource_Custom {
$mtime = LStemplate :: getTemplateTimestamp($name); $mtime = LStemplate :: getTemplateTimestamp($name);
} }
/**
* Fetch a template's modification time from database
*
* @note implementing this method is optional. Only implement it if modification times can be accessed faster than loading the comple template source.
* @param string $name template name
* @return integer timestamp (epoch) the template was modified
*/
protected function fetchTimestamp($name) {
return LStemplate :: getTemplateTimestamp($name);
}
} }
// Register 'ls' template ressource // Register 'ls' template ressource

View file

@ -69,7 +69,7 @@ class LSurl extends LSlog_staticLoggerClass {
* @param boolean $authenticated Permit to define if this URL is accessible only for authenticated users (optional, default: true) * @param boolean $authenticated Permit to define if this URL is accessible only for authenticated users (optional, default: true)
* @param boolean $authenticated Allow override if a command already exists with the same name (optional, default: false) * @param boolean $authenticated Allow override if a command already exists with the same name (optional, default: false)
* @param boolean $authenticated Enable API mode (optional, default: false) * @param boolean $authenticated Enable API mode (optional, default: false)
* @param array[string]|string|null $methods HTTP method (optional, default: array('GET', 'POST')) * @param array<string>|string|null $methods HTTP method (optional, default: array('GET', 'POST'))
**/ **/
public static function add_handler($pattern, $handler=null, $authenticated=true, $override=true, $api_mode=false, $methods=null) { public static function add_handler($pattern, $handler=null, $authenticated=true, $override=true, $api_mode=false, $methods=null) {
if (is_null($methods)) if (is_null($methods))
@ -163,7 +163,7 @@ class LSurl extends LSlog_staticLoggerClass {
* *
* @param string $pattern The URL pattern * @param string $pattern The URL pattern
* @param string|false $current_url The current URL (optional) * @param string|false $current_url The current URL (optional)
* @param array[string]|string|null $methods HTTP method (optional, default: no check) * @param array<string>|string|null $methods HTTP method (optional, default: no check)
* *
* @return array|false The URL info if pattern matched, false otherwise. * @return array|false The URL info if pattern matched, false otherwise.
**/ **/
@ -295,11 +295,11 @@ class LSurl extends LSlog_staticLoggerClass {
// Check authentication (if need) // Check authentication (if need)
if(self :: $request -> authenticated && ! LSsession :: startLSsession()) { if(self :: $request -> authenticated && ! LSsession :: startLSsession()) {
LSsession :: displayTemplate(); LSsession :: displayTemplate();
return true; return;
} }
try { try {
return call_user_func(self :: $request -> handler, self :: $request); call_user_func(self :: $request -> handler, self :: $request);
} }
catch (Exception $e) { catch (Exception $e) {
self :: log_exception( self :: log_exception(

View file

@ -339,10 +339,10 @@ function LSdebugDefined() {
function isCompatibleDNs($dn1,$dn2) { function isCompatibleDNs($dn1,$dn2) {
$infos1=ldap_explode_dn($dn1,0); $infos1=ldap_explode_dn($dn1,0);
if(!$infos1) if(!$infos1)
return; return false;
$infos2=ldap_explode_dn($dn2,0); $infos2=ldap_explode_dn($dn2,0);
if(!$infos2) if(!$infos2)
return; return false;
if($infos2['count']>$infos1['count']) { if($infos2['count']>$infos1['count']) {
$tmp=$infos1; $tmp=$infos1;
$infos1=$infos2; $infos1=$infos2;
@ -370,15 +370,15 @@ function isCompatibleDNs($dn1,$dn2) {
* *
* @author Benjamin Renard <brenard@easter-eggs.com> * @author Benjamin Renard <brenard@easter-eggs.com>
* *
* @return string Un DN (ou false si les DN ne sont pas valide) * @return string|false Un DN (ou false si les DN ne sont pas valide)
*/ */
function sumDn($dn1,$dn2) { function sumDn($dn1,$dn2) {
$infos1=ldap_explode_dn($dn1,0); $infos1=ldap_explode_dn($dn1,0);
if(!$infos1) if(!$infos1)
return; return false;
$infos2=ldap_explode_dn($dn2,0); $infos2=ldap_explode_dn($dn2,0);
if(!$infos2) if(!$infos2)
return; return false;
if($infos2['count']>$infos1['count']) { if($infos2['count']>$infos1['count']) {
$tmp=$infos1; $tmp=$infos1;
$infos1=$infos2; $infos1=$infos2;