Compare commits

..

No commits in common. "e71823b644f4007eece83b8a00fa64f07988effb" and "a8e0707e7a7b784cec1d85e269cafd656430515f" have entirely different histories.

85 changed files with 634 additions and 699 deletions

3
.gitignore vendored
View file

@ -1,6 +1,3 @@
upgrade.log upgrade.log
*.sav *.sav
*~ *~
vendor
/src/local.*
tests-report.xml

View file

@ -1,18 +0,0 @@
stages:
- tests
tests:
image: composer
stage: tests
rules:
- changes:
- src/*
script:
- composer install
- ./vendor/bin/phpstan analyse --no-interaction --configuration=phpstan.neon --error-format=junit > tests-report.xml
artifacts:
when: always
paths:
- tests-report.xml
reports:
junit: tests-report.xml

View file

@ -1,5 +0,0 @@
{
"require-dev": {
"phpstan/phpstan": "^1.9"
}
}

View file

@ -1,32 +0,0 @@
parameters:
level: 1
paths:
- src
excludePaths:
- src/local
- src/tmp
# Error message "Class Smarty_Resource_LdapSaisie extends unknown class Smarty_Resource_Custom." cannot be ignored, use excludePaths instead.
- src/includes/class/class.LStemplate_smarty3_support.php
bootstrapFiles:
- src/includes/core.php
universalObjectCratesClasses:
- LSsearch
- LSsearchEntry
- LSrelation
- LSlog_handler
- LSlog_logger
- LSldapObject
- LSurlRequest
ignoreErrors:
- "#Instantiated class (Smarty|Console_Table|ZxcvbnPhp\\\\Zxcvbn|phpseclib\\\\Crypt\\\\RSA|phpseclib\\\\Net\\\\SFTP|phpseclib\\\\Net\\\\SSH2|Net_FTP) not found\\.#"
- "#Call to static method (connect|isError)\\(\\) on an unknown class Net_LDAP2\\.#"
- "#(Class|Constant) (Net_LDAP2_Filter|Net_LDAP2_Entry|PEAR_Error) not found\\.#"
- "#Call to static method (create|parse|combine|escape)\\(\\) on an unknown class Net_LDAP2_Filter\\.#"
- "#Call to static method (createFresh)\\(\\) on an unknown class Net_LDAP2_Entry\\.#"
- "#Call to static method (forceAuthentication|getUser|logout|setDebug|client|setNoCasServerValidation|setCasServerCACert|setExtraCurlOption)\\(\\) on an unknown class phpCAS\\.#"
-
message: "#Call to static method factory\\(\\) on an unknown class Mail\\.#"
path: src/includes/addons/LSaddons.mail.php
-
message: "#Instantiated class Mail_mime not found\\.#"
path: src/includes/addons/LSaddons.mail.php

View file

@ -122,6 +122,10 @@ $GLOBALS['LSobjects']['LSpeople'] = array (
), ),
), ),
'before_modify' => 'valid',
'after_modify' => 'valid',
//'after_create' => 'createMaildirByFTP',
//'after_delete' => 'removeMaildirByFTP',
'display_name_format' => '%{cn}', 'display_name_format' => '%{cn}',
'label' => 'Users', 'label' => 'Users',

View file

@ -105,7 +105,7 @@ LSerror :: defineError('ASTERISK_03',
} }
$password = $ldapObject -> attrs[ LS_ASTERISK_USERPASSWORD_ATTR ] -> ldap -> getClearPassword(); $password = $ldapObject -> attrs[ LS_ASTERISK_USERPASSWORD_ATTR ] -> ldap -> getClearPassword();
if (!$password) { if (!$password or empty($password)) {
LSerror :: addErrorCode('ASTERISK_03'); LSerror :: addErrorCode('ASTERISK_03');
return; return;
} }

View file

@ -304,15 +304,15 @@ function triggerUpdateDynGroupsMembersCacheOnUserChanges(&$user, &$changed_attrs
continue; continue;
} }
$impacted_attr = null; $is_impacted = false;
foreach($filter_attrs as $attr) { foreach($filter_attrs as $attr) {
if (in_array(strtolower($attr), $changed_attrs)) { if (in_array(strtolower($attr), $changed_attrs)) {
$impacted_attr = $attr; $is_impacted = true;
break; break;
} }
} }
if (!$impacted_attr) { if (!$is_impacted) {
LSlog :: get_logger('LSaddon_dyngroup') -> debug( LSlog :: get_logger('LSaddon_dyngroup') -> debug(
"triggerUpdateDynGroupsMembersCacheOnUserChanges($user): $group is NOT impacted by user's changes." "triggerUpdateDynGroupsMembersCacheOnUserChanges($user): $group is NOT impacted by user's changes."
); );
@ -320,7 +320,7 @@ function triggerUpdateDynGroupsMembersCacheOnUserChanges(&$user, &$changed_attrs
} }
LSlog :: get_logger('LSaddon_dyngroup') -> debug( LSlog :: get_logger('LSaddon_dyngroup') -> debug(
"triggerUpdateDynGroupsMembersCacheOnUserChanges($user): $group is impacted by user's changes ". "triggerUpdateDynGroupsMembersCacheOnUserChanges($user): $group is impacted by user's changes ".
"(at least by attribute '$impacted_attr')." "(at least by attribute '$attr')."
); );
$impacted_dyngroups++; $impacted_dyngroups++;
if (updateDynGroupMembersCache($group, false)) if (updateDynGroupMembersCache($group, false))

View file

@ -115,7 +115,7 @@ function organizationalChartData() {
$parent_id_attr = LSconfig :: get('parent_id_attr', '', 'string', $conf); $parent_id_attr = LSconfig :: get('parent_id_attr', '', 'string', $conf);
if ($parent_id_attr) { if ($parent_id_attr) {
if (!$obj_type :: hasAttr($parent_id_attr)) if (!$obj_type :: hasAttr($parent_id_attr))
LStemplate :: fatal_error("Object '$obj_type' does not have attribute '$parent_id_attr'."); LStemplate :: fatal_error("Object '$obj_type' does not have attribute '$id_attr'.");
$requested_attrs[$obj_type][] = $parent_id_attr; $requested_attrs[$obj_type][] = $parent_id_attr;
} }
$objects_conf[$obj_type]['parent_id_attr'] = $parent_id_attr; $objects_conf[$obj_type]['parent_id_attr'] = $parent_id_attr;
@ -130,7 +130,7 @@ function organizationalChartData() {
foreach(getFieldInFormat($attr) as $a) { foreach(getFieldInFormat($attr) as $a) {
if (!$obj_type :: hasAttr($a)) if (!$obj_type :: hasAttr($a))
LStemplate :: fatal_error("Object '$obj_type' does not have attribute '$a'."); LStemplate :: fatal_error("Object '$obj_type' does not have attribute '$a'.");
if (!in_array($a, $requested_attrs[$obj_type])) if (!in_array($a, $attrs))
$requested_attrs[$obj_type][] = $a; $requested_attrs[$obj_type][] = $a;
} }
} }
@ -276,7 +276,7 @@ function organizationalChartData() {
echo json_encode( echo json_encode(
$entities, $entities,
( (
isset($_REQUEST['pretty'])? $pretty || isset($_REQUEST['pretty'])?
JSON_PRETTY_PRINT: JSON_PRETTY_PRINT:
0 0
) )

View file

@ -201,7 +201,6 @@ function ppolicy_extraDisplayColumn_password_expiration($entry) {
* @return boolean Void if CSV file is successfully generated and upload, false in other case * @return boolean Void if CSV file is successfully generated and upload, false in other case
*/ */
function ppolicy_export_search_info($LSsearch, $as_csv=true, $return=false) { function ppolicy_export_search_info($LSsearch, $as_csv=true, $return=false) {
$csv = null;
if ($as_csv) { if ($as_csv) {
$csv = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+'); $csv = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');
@ -225,7 +224,6 @@ function ppolicy_export_search_info($LSsearch, $as_csv=true, $return=false) {
return false; return false;
} }
$data = array();
if ($as_csv) { if ($as_csv) {
$headers = array($LSsearch->label_objectName, 'DN'); $headers = array($LSsearch->label_objectName, 'DN');
foreach($attrs as $attr) { foreach($attrs as $attr) {
@ -238,6 +236,9 @@ function ppolicy_export_search_info($LSsearch, $as_csv=true, $return=false) {
return false; return false;
} }
} }
else {
$data = array();
}
foreach ($LSsearch -> getSearchEntries() as $e) { foreach ($LSsearch -> getSearchEntries() as $e) {
$row = array( $row = array(
@ -249,7 +250,7 @@ function ppolicy_export_search_info($LSsearch, $as_csv=true, $return=false) {
if ($as_csv) { if ($as_csv) {
$values = ensureIsArray($e -> get($attr)); $values = ensureIsArray($e -> get($attr));
if ($values) { if ($values) {
$row[] = implode('|', $values); $row[] = ($as_json?$values:implode('|', $values));
} }
else { else {
$no_value_label = LSconfig::get( $no_value_label = LSconfig::get(
@ -281,7 +282,7 @@ function ppolicy_export_search_info($LSsearch, $as_csv=true, $return=false) {
if ($return) if ($return)
return $data; return $data;
header("Content-disposition: attachment; filename=ppolicy-".$LSsearch->LSobject.".json"); header("Content-disposition: attachment; filename=ppolicy-".$LSsearch->LSobject.".json");
LSsession :: displayAjaxReturn($data); displayAjaxReturn($data);
exit(); exit();
} }
@ -329,11 +330,9 @@ function _ppolicy_write_row_in_csv(&$csv, &$row) {
* @return void * @return void
**/ **/
function handle_api_LSobject_exportPpolicyInfo($request) { function handle_api_LSobject_exportPpolicyInfo($request) {
$object = get_LSobject_from_API_request($request); get_LSobject_from_API_request($request);
if (!$object)
return;
$container_dn = LSconfig::get( $container_dn = LSconfig::get(
"LSobjects.".$object->LSobject.".container_dn", "LSobjects.".$LSsearch->LSobject.".container_dn",
"", "string"); "", "string");
$whoami = LSsession :: whoami( $whoami = LSsession :: whoami(
$container_dn? $container_dn?
@ -424,8 +423,8 @@ function cli_export_ppolicy_info($command_args) {
print($data); print($data);
exit(); exit();
} }
$fd = fopen($output, 'w') or LStemplate::fatal_error("Fail to open output file '$output'"); $fd = fopen($output, 'w') or fatal_error("Fail to open output file '$output'");
fwrite($fd, $data) or LStemplate::fatal_error("Fail to write result in output file '$output'"); fwrite($fd, $data) or fatal_error("Fail to write result in output file '$output'");
@fclose($fd); @fclose($fd);
} }

View file

@ -491,7 +491,7 @@ function generate_sambaProfilePath($ldapObject) {
function generate_shadowExpire_from_sambaPwdMustChange($ldapObject) { function generate_shadowExpire_from_sambaPwdMustChange($ldapObject) {
$time = $ldapObject -> getValue('sambaPwdMustChange', true, null); $time = $ldapObject -> getValue('sambaPwdMustChange', true, null);
if ($time) if ($time)
return strval(round(intval($time)/86400)); return str_val(round(int_val($time)/86400));
return ''; return '';
} }
@ -507,7 +507,7 @@ function generate_shadowExpire_from_sambaPwdMustChange($ldapObject) {
function generate_timestamp_from_shadowExpire($ldapObject) { function generate_timestamp_from_shadowExpire($ldapObject) {
$days = $ldapObject -> getValue('shadowExpire', true, null); $days = $ldapObject -> getValue('shadowExpire', true, null);
if ($days) if ($days)
return strval(intval($days) * 86400); return str_val(int_val($days) * 86400);
return ''; return '';
} }

View file

@ -65,6 +65,7 @@ function showTechInfo($object) {
'creatorsName' => _('Creator DN'), 'creatorsName' => _('Creator DN'),
'modifyTimestamp' => _('Last modification date'), 'modifyTimestamp' => _('Last modification date'),
'modifiersName' => _('Last modifier DN'), 'modifiersName' => _('Last modifier DN'),
'modifiersName' => _('Last modifier DN'),
'entryCSN' => _('LDAP entry change sequence number'), 'entryCSN' => _('LDAP entry change sequence number'),
'entryUUID' => _('LDAP entry UUID'), 'entryUUID' => _('LDAP entry UUID'),
'hasSubordinates' => _('LDAP entry has children'), 'hasSubordinates' => _('LDAP entry has children'),

View file

@ -223,7 +223,7 @@ LSerror :: defineError('SSH_07',
* *
* @retval boolean * @retval boolean
*/ */
function removeDirsBySFTP($connection_params, $dirs, $recursive=false, $continue=false) { function removeDirsBySFTP($connection_params, $dirs, $recursive=false) {
$cnx = connectToSSH($connection_params, true); $cnx = connectToSSH($connection_params, true);
if (! $cnx){ if (! $cnx){
return; return;

View file

@ -814,26 +814,6 @@ function supannGetOIDCGenrePossibleValues($options, $name, $ldapObject) {
return supannGetNomenclaturePossibleValues('oidc_genre', false); return supannGetNomenclaturePossibleValues('oidc_genre', false);
} }
/**
* Détecte et alimente la liste des codes de populations dans la variable
* $GLOBALS['supannNomenclatures']['SUPANN']['codePopulation'].
*
* @param array $populations
* @param string $prefix
* @return void
*/
function supannDetectCodesPopulations($populations, $prefix="") {
if (!$populations) {
return;
}
foreach($populations as $letter => $infos) {
$code = "$prefix$letter";
if (isset($infos['label']))
$GLOBALS['supannNomenclatures']['SUPANN']['codePopulation'][$code] = $infos['label']." ($code)";
supannDetectCodesPopulations($infos['subpopulations'], $code);
}
}
/* /*
* Charge une nomenclature SUPANN * Charge une nomenclature SUPANN
* *
@ -886,7 +866,19 @@ function supannLoadNomenclature($table) {
return false; return false;
} }
$GLOBALS['supannNomenclatures']['SUPANN']['codePopulation'] = array(); $GLOBALS['supannNomenclatures']['SUPANN']['codePopulation'] = array();
supannDetectCodesPopulations($GLOBALS['supannPopulations']);
function _detectCodesPopulations($populations, $prefix="") {
if (!$populations) {
return;
}
foreach($populations as $letter => $infos) {
$code = "$prefix$letter";
if (isset($infos['label']))
$GLOBALS['supannNomenclatures']['SUPANN']['codePopulation'][$code] = $infos['label']." ($code)";
_detectCodesPopulations($infos['subpopulations'], $code);
}
}
_detectCodesPopulations($GLOBALS['supannPopulations']);
break; break;
case 'etuDiplome': case 'etuDiplome':

View file

@ -35,7 +35,7 @@ class LSattr_html_maildir extends LSattr_html {
public function __construct($name, $config, &$attribute) { public function __construct($name, $config, &$attribute) {
$attribute -> addObjectEvent('before_delete',$this,'beforeDelete'); $attribute -> addObjectEvent('before_delete',$this,'beforeDelete');
$attribute -> addObjectEvent('after_delete',$this,'deleteMaildirByFTP'); $attribute -> addObjectEvent('after_delete',$this,'deleteMaildirByFTP');
parent :: __construct($name, $config, $attribute); return parent :: __construct($name, $config, $attribute);
} }
public function doOnModify($action,$cur,$new) { public function doOnModify($action,$cur,$new) {

View file

@ -309,7 +309,7 @@ class LSattr_html_select_list extends LSattr_html{
* @retval array Tableau associatif des valeurs possible de la liste avec en clé * @retval array 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é.
*/ */
protected static function getLSattributePossibleValues($attr, $options ,$name ,&$ldapObject) { protected function getLSattributePossibleValues($attr, $options ,$name ,&$ldapObject) {
$retInfos=array(); $retInfos=array();
if (is_string($attr)) { if (is_string($attr)) {
if (isset($ldapObject->attrs[$attr]) && $ldapObject->attrs[$attr] instanceof LSattribute) { if (isset($ldapObject->attrs[$attr]) && $ldapObject->attrs[$attr] instanceof LSattribute) {
@ -410,7 +410,7 @@ class LSattr_html_select_list extends LSattr_html{
); );
} }
catch (Exception $er) { catch (Exception $er) {
self :: log_exception($er, get_called_class()." -> _getPossibleValues(): exception occured running ".format_callable($get_possible_values)); self :: log_exception($er, strval($this)." -> _getPossibleValues(): exception occured running ".format_callable($get_possible_values));
$retInfos = null; $retInfos = null;
} }

View file

@ -146,7 +146,6 @@ class LSattr_ldap_password extends LSattr_ldap {
break; break;
case 'sha256': case 'sha256':
case 'sha512': case 'sha512':
$mhash_type = null;
switch($encode) { switch($encode) {
case 'sha256': case 'sha256':
$mhash_type = MHASH_SHA256; $mhash_type = MHASH_SHA256;
@ -164,7 +163,6 @@ class LSattr_ldap_password extends LSattr_ldap {
case 'ssha': case 'ssha':
case 'ssha256': case 'ssha256':
case 'ssha512': case 'ssha512':
$mhash_type = null;
switch($encode) { switch($encode) {
case 'ssha': case 'ssha':
$mhash_type = MHASH_SHA1; $mhash_type = MHASH_SHA1;
@ -190,7 +188,7 @@ class LSattr_ldap_password extends LSattr_ldap {
if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) { if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
mt_srand( (double) microtime() * 1000000 ); mt_srand( (double) microtime() * 1000000 );
if (is_null($salt)) if (is_null($salt))
$salt = mhash_keygen_s2k( MHASH_MD5, $clearPassword, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 ); $salt = mhash_keygen_s2k( MHASH_MD5, $password_clear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
return "{SMD5}".base64_encode( mhash( MHASH_MD5, $clearPassword.$salt ).$salt ); return "{SMD5}".base64_encode( mhash( MHASH_MD5, $clearPassword.$salt ).$salt );
} }
else { else {
@ -265,10 +263,12 @@ class LSattr_ldap_password extends LSattr_ldap {
return (strcasecmp(call_user_func_array($encodeFunction, array(&$this -> attribute -> ldapObject, $clearPassword)), $hashedPassword) == 0); return (strcasecmp(call_user_func_array($encodeFunction, array(&$this -> attribute -> ldapObject, $clearPassword)), $hashedPassword) == 0);
// Extract cipher // Extract cipher
$hashedPasswordData = $cypher = null;
if (preg_match('/{([^}]+)}(.*)/',$hashedPassword,$matches)) { if (preg_match('/{([^}]+)}(.*)/',$hashedPassword,$matches)) {
$hashedPasswordData = $matches[2]; $hashedPasswordData = $matches[2];
$cypher = strtolower($matches[1]); $cypher = strtolower($matches[1]);
} else {
$cypher = null;
} }
// Verify password according on cypher // Verify password according on cypher

View file

@ -699,7 +699,7 @@ class LSattribute extends LSlog_staticLoggerClass {
call_user_func_array($e['fct'], array(&$e['params'])); call_user_func_array($e['fct'], array(&$e['params']));
} }
catch(Exception $er) { catch(Exception $er) {
self :: log_exception($er, strval($this)." -> fireEvent($event): exception occured running ".format_callable($e['fct'])); self :: log_exception($er, strval($this)." -> fireEvent($event): exception occured running ".format_callable(e['fct']));
$return = false; $return = false;
} }
} }

View file

@ -41,6 +41,7 @@ class LSauthMethod extends LSlog_staticLoggerClass {
self :: log_debug(get_class($this)." :: __construct(): config file ($conf_file) loaded"); self :: log_debug(get_class($this)." :: __construct(): config file ($conf_file) loaded");
else else
self :: log_debug(get_class($this)." :: __construct(): config file ($conf_file) not found"); self :: log_debug(get_class($this)." :: __construct(): config file ($conf_file) not found");
return true;
} }
/** /**
@ -68,7 +69,7 @@ class LSauthMethod extends LSlog_staticLoggerClass {
self :: log_debug("No user found for provided username '".$this -> authData['username']."'"); self :: log_debug("No user found for provided username '".$this -> authData['username']."'");
return false; return false;
} }
if (count($authobjects) > 1) { if (count($authobjects) > 1) {
self :: log_debug('Multiple users match with provided username: '.implode(', ', array_keys($authobjects))); self :: log_debug('Multiple users match with provided username: '.implode(', ', array_keys($authobjects)));
LSerror :: addErrorCode('LSauth_02'); LSerror :: addErrorCode('LSauth_02');

View file

@ -33,7 +33,8 @@ class LSauthMethod_CAS extends LSauthMethod {
public function __construct() { public function __construct() {
LSauth :: disableLoginForm(); LSauth :: disableLoginForm();
parent :: __construct(); if (!parent :: __construct())
return;
if (LSsession :: includeFile(PHP_CAS_PATH, true)) { if (LSsession :: includeFile(PHP_CAS_PATH, true)) {
if (defined('PHP_CAS_DEBUG_FILE')) { if (defined('PHP_CAS_DEBUG_FILE')) {
@ -66,7 +67,7 @@ class LSauthMethod_CAS extends LSauthMethod {
// Check CAS server SSL validation is now configured // Check CAS server SSL validation is now configured
if (!$cas_server_ssl_validation_configured) { if (!$cas_server_ssl_validation_configured) {
LSerror :: addErrorCode('LSauthMethod_CAS_02'); LSerror :: addErrorCode('LSauthMethod_CAS_02');
return; return false;
} }
if (defined('LSAUTH_CAS_CURL_SSLVERION')) { if (defined('LSAUTH_CAS_CURL_SSLVERION')) {
@ -81,10 +82,12 @@ class LSauthMethod_CAS extends LSauthMethod {
// Set configured flag // Set configured flag
$this -> configured = true; $this -> configured = true;
return true;
} }
else { else {
LSerror :: addErrorCode('LSauthMethod_CAS_01'); LSerror :: addErrorCode('LSauthMethod_CAS_01');
} }
return false;
} }
/** /**

View file

@ -37,6 +37,7 @@ class LSauthMethod_HTTP extends LSauthMethod_basic {
LSauth :: disableLoginForm(); LSauth :: disableLoginForm();
if (!defined('LSAUTHMETHOD_HTTP_LOGOUT_REMOTE_URL')) if (!defined('LSAUTHMETHOD_HTTP_LOGOUT_REMOTE_URL'))
LSauth :: disableLogoutBtn(); LSauth :: disableLogoutBtn();
return True;
} }
/** /**

View file

@ -34,7 +34,8 @@ class LSauthMethod_anonymous extends LSauthMethod {
LSauth :: disableLoginForm(); LSauth :: disableLoginForm();
LSauth :: disableSelfAccess(); LSauth :: disableSelfAccess();
parent :: __construct(); if (!parent :: __construct())
return;
if ( (!defined('LSAUTHMETHOD_ANONYMOUS_DISABLE_LOGOUT')) || (constant('LSAUTHMETHOD_ANONYMOUS_DISABLE_LOGOUT') === True)) { if ( (!defined('LSAUTHMETHOD_ANONYMOUS_DISABLE_LOGOUT')) || (constant('LSAUTHMETHOD_ANONYMOUS_DISABLE_LOGOUT') === True)) {
self :: log_debug('logout : '.constant('LSAUTHMETHOD_ANONYMOUS_DISABLE_LOGOUT')); self :: log_debug('logout : '.constant('LSAUTHMETHOD_ANONYMOUS_DISABLE_LOGOUT'));
@ -45,6 +46,7 @@ class LSauthMethod_anonymous extends LSauthMethod {
LSerror :: addErrorCode('LSauthMethod_anonymous_01'); LSerror :: addErrorCode('LSauthMethod_anonymous_01');
return; return;
} }
return true;
} }
/** /**

View file

@ -55,7 +55,6 @@ class LSform extends LSlog_staticLoggerClass {
var $api_mode = false; var $api_mode = false;
private $submited = false; private $submited = false;
private $submit = null;
/** /**
* Constructeur * Constructeur
@ -529,7 +528,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',$element_name);
return; return;
} }
} }
@ -549,7 +548,7 @@ class LSform extends LSlog_staticLoggerClass {
* *
* @retval LSformElement * @retval LSformElement
*/ */
public function addElement($type,$name,$label,$params,&$attr_html) { public function addElement($type,$name,$label,$params=array(),&$attr_html) {
$elementType='LSformElement_'.$type; $elementType='LSformElement_'.$type;
LSsession :: loadLSclass($elementType); LSsession :: loadLSclass($elementType);
if (!class_exists($elementType)) { if (!class_exists($elementType)) {

View file

@ -36,7 +36,6 @@ class LSformElement extends LSlog_staticLoggerClass {
var $label; var $label;
var $params; var $params;
var $values = array(); var $values = array();
var $form = null;
var $_required = false; var $_required = false;
var $_freeze = false; var $_freeze = false;
var $attr_html; var $attr_html;
@ -365,7 +364,7 @@ class LSformElement extends LSlog_staticLoggerClass {
* *
* @retval boolean True on success, False otherwise * @retval boolean True on success, False otherwise
*/ */
protected function split_autocomplete_attr_values($attr_value, $multiple_value_delimiter, &$attr_values, &$last_attr_value) { protected function split_autocomplete_attr_values($attr_value="", $multiple_value_delimiter="|", &$attr_values, &$last_attr_value) {
$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.");

View file

@ -110,7 +110,7 @@ class LSformElement_image extends LSformElement {
$php_debug_params[] = "$param = '".ini_get($param)."'"; $php_debug_params[] = "$param = '".ini_get($param)."'";
$php_debug_params[] = "HTML form MAX_FILE_SIZE = '".MAX_SEND_FILE_SIZE."'"; $php_debug_params[] = "HTML form MAX_FILE_SIZE = '".MAX_SEND_FILE_SIZE."'";
self :: log_debug('LSformElement_image('.$this->name.')->getPostData(): '.implode(', ', $php_debug_params)); self :: log_debug('LSformElement_image('.$this->name.')->getPostData(): '.implode(', ', $php_debug_params));
$this -> form -> setElementError($this -> attr_html, $this -> getFileUploadErrorMessage()); $this -> form -> setElementError($this -> attr_html, $this -> getFileUploadErrorMessage($_FILES[$this -> name]));
return false; return false;
} }
} }
@ -143,7 +143,7 @@ class LSformElement_image extends LSformElement {
* @retval string The translated file upload error message * @retval string The translated file upload error message
*/ */
private function getFileUploadErrorMessage() { private function getFileUploadErrorMessage() {
if (isset($_FILES[$this -> name]) && isset($_FILES[$this -> name]['error'])) { if (isset($_FILES) && isset($_FILES[$this -> name]) && isset($_FILES[$this -> name]['error'])) {
switch($_FILES[$this -> name]['error']) { switch($_FILES[$this -> name]['error']) {
case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_INI_SIZE:
return _('The uploaded file size exceeds the limit accepted by the server.'); return _('The uploaded file size exceeds the limit accepted by the server.');

View file

@ -71,7 +71,7 @@ class LSformElement_maildir extends LSformElement_text {
'nodo' => _("Click to enable maildir creation/modification on user creation/modification.") 'nodo' => _("Click to enable maildir creation/modification on user creation/modification.")
) )
); );
return parent :: getDisplay(); return parent :: getDisplay($return);
} }
/** /**

View file

@ -50,7 +50,7 @@ class LSformElement_rss extends LSformElement_text {
'display' => _("Display RSS stack.") 'display' => _("Display RSS stack.")
) )
); );
return parent :: getDisplay(); return parent :: getDisplay($return);
} }
} }

View file

@ -192,8 +192,10 @@ class LSformElement_select extends LSformElement {
* *
* @retval void * @retval void
**/ **/
function LSformElement_select_checkIsValidValue($params, $template) { function LSformElement_select_checkIsValidValue($params,$template) {
$ret = LSformElement_select :: _isValidValue($params['value'], $params['possible_values']); extract($params);
$ret = LSformElement_select :: _isValidValue($value, $possible_values);
if ($ret===False) { if ($ret===False) {
$label=''; $label='';

View file

@ -309,7 +309,7 @@ class LSformElement_supannCompositeAttribute extends LSformElement {
break; break;
default: default:
self :: log_error('Unrecognized component type "'.$this -> components[$c]['type'].'"'); self :: error('Unrecognized component type "'.$this -> components[$c]['type'].'"');
} }
} }
self :: log_debug("translateComponentValue($c, $val): ".varDump($retval)); self :: log_debug("translateComponentValue($c, $val): ".varDump($retval));
@ -400,7 +400,7 @@ class LSformElement_supannCompositeAttribute extends LSformElement {
} }
self :: log_debug($this." -> getPostData(): POST data = ".varDump($parseValues)); self :: log_debug($this." -> getPostData(): POST data = ".varDump($parseValues));
if (!$parseValues && $onlyIfPresent) if (!$parseValue && $onlyIfPresent)
return true; return true;
$return[$this -> name] = array(); $return[$this -> name] = array();
@ -572,7 +572,7 @@ class LSformElement_supannCompositeAttribute extends LSformElement {
public function getApiValue($details=false) { public function getApiValue($details=false) {
$values = array(); $values = array();
foreach(ensureIsArray($this -> values) as $value) { foreach(ensureIsArray($this -> values) as $value) {
$decodedValue = $this -> parseCompositeValue($value); $decodedValue = $this -> parseCompositeValue($value, true);
if (is_array($decodedValue)) { if (is_array($decodedValue)) {
$parsedValue = array(); $parsedValue = array();
foreach(array_keys($this -> components) as $c) { foreach(array_keys($this -> components) as $c) {

View file

@ -84,7 +84,7 @@ class LSformElement_supannEmpProfil extends LSformElement_supannCompositeAttribu
'required' => false, 'required' => false,
), ),
); );
parent :: __construct($form, $name, $label, $params, $attr_html); return parent :: __construct($form, $name, $label, $params, $attr_html);
} }
} }

View file

@ -122,7 +122,7 @@ class LSformElement_supannEtuInscription extends LSformElement_supannCompositeAt
'required' => false, 'required' => false,
), ),
); );
parent :: __construct($form, $name, $label, $params, $attr_html); return parent :: __construct($form, $name, $label, $params, $attr_html);
} }
} }

View file

@ -83,7 +83,7 @@ class LSformElement_supannExtProfil extends LSformElement_supannCompositeAttribu
'required' => false, 'required' => false,
), ),
); );
parent :: __construct($form, $name, $label, $params, $attr_html); return parent :: __construct($form, $name, $label, $params, $attr_html);
} }
} }

View file

@ -58,7 +58,7 @@ class LSformElement_supannRessourceEtat extends LSformElement_supannCompositeAtt
'required' => false, 'required' => false,
), ),
); );
parent :: __construct($form, $name, $label, $params, $attr_html); return parent :: __construct($form, $name, $label, $params, $attr_html);
} }
/** /**
@ -91,7 +91,7 @@ class LSformElement_supannRessourceEtat extends LSformElement_supannCompositeAtt
if (!$value['ressource'] || !$value['etat']) if (!$value['ressource'] || !$value['etat'])
return null; return null;
$ret = "{".$value['ressource']."}".$value['etat']; $ret = "{".$value['ressource']."}".$value['etat'];
if (isset($value['sous_etat']) && !is_empty($value['sous_etat'])) if (isset($value['sous_etat']) && !is_empty($matches['sous_etat']))
$ret .= ":".$value['sous_etat']; $ret .= ":".$value['sous_etat'];
return $ret; return $ret;
} }

View file

@ -70,7 +70,7 @@ class LSformElement_supannRessourceEtatDate extends LSformElement_supannComposit
'required' => false, 'required' => false,
), ),
); );
parent :: __construct($form, $name, $label, $params, $attr_html); return parent :: __construct($form, $name, $label, $params, $attr_html);
} }
/** /**

View file

@ -54,7 +54,7 @@ class LSformElement_supannRoleEntite extends LSformElement_supannCompositeAttrib
'required' => false 'required' => false
) )
); );
parent :: __construct($form, $name, $label, $params, $attr_html); return parent :: __construct($form, $name, $label, $params, $attr_html);
} }
} }

View file

@ -178,7 +178,6 @@ class LSformElement_text extends LSformElement {
); );
} }
else { else {
$filters = array();
foreach($value_attributes as $attr) { foreach($value_attributes as $attr) {
$filters[] = Net_LDAP2_Filter::create($attr, 'contains', $pattern); $filters[] = Net_LDAP2_Filter::create($attr, 'contains', $pattern);
} }
@ -218,18 +217,19 @@ class LSformElement_text extends LSformElement {
foreach($value_attributes as $attr) { foreach($value_attributes as $attr) {
if (!isset($object['attrs'][$attr])) continue; if (!isset($object['attrs'][$attr])) continue;
$values = ensureIsArray($object['attrs'][$attr]); $values = ensureIsArray($object['attrs'][$attr]);
foreach($values as $value) { foreach($values as $value)
$ret[$value] = (
$displayNameFormat? if ($displayNameFormat)
getFData( $displayName = getFData(
$displayNameFormat, $displayNameFormat,
array_merge( array_merge(
array('value' => $value, 'dn' => $object['dn']), array('value' => $value, 'dn' => $object['dn']),
$object['attrs'] $object['attrs']
) )
):$value );
); else
} $displayName = $value;
$ret[$value] = $displayName;
} }
} }
} }

View file

@ -50,7 +50,7 @@ class LSformElement_xmpp extends LSformElement_text {
'chat' => _("Chat with this person.") 'chat' => _("Chat with this person.")
) )
); );
return parent :: getDisplay(); return parent :: getDisplay($return);
} }
} }

View file

@ -50,7 +50,7 @@ class LSformRule extends LSlog_staticLoggerClass {
* *
* @return boolean True if value is valid, False otherwise * @return boolean True if value is valid, False otherwise
*/ */
public static function validate_values($rule_name, $values, $options, &$formElement) { public static function validate_values($rule_name, $values, $options=array(), &$formElement) {
// Compute PHP class name of the rule // Compute PHP class name of the rule
$rule_class = "LSformRule_".$rule_name; $rule_class = "LSformRule_".$rule_name;
@ -93,7 +93,7 @@ class LSformRule extends LSlog_staticLoggerClass {
* *
* @return boolean True if value is valid, False otherwise * @return boolean True if value is valid, False otherwise
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
return false; return false;
} }
@ -166,7 +166,6 @@ class LSformRule extends LSlog_staticLoggerClass {
$rule_name = null; $rule_name = null;
$rule_class = null; $rule_class = null;
$rule_name_arg_num = null; $rule_name_arg_num = null;
$rule_name_quote_char = null;
$params = array(); $params = array();
for ($i=0; $i < count($command_args); $i++) { for ($i=0; $i < count($command_args); $i++) {
switch ($command_args[$i]) { switch ($command_args[$i]) {

View file

@ -36,7 +36,7 @@ class LSformRule_LSformElement_select_validValue extends LSformRule {
* *
* @return boolean true if the value is valide, false if not * @return boolean true if the value is valide, false if not
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$ret = $formElement -> isValidValue($value); $ret = $formElement -> isValidValue($value);
if ($ret===False) return False; if ($ret===False) return False;
return True; return True;

View file

@ -42,7 +42,7 @@ class LSformRule_alphanumeric extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
if (LSconfig :: get('params.withAccents', false, 'bool', $options)) { if (LSconfig :: get('params.withAccents', false, 'bool', $options)) {
$regex = '/(*UTF8)^[0-9\p{L}]+$/'; $regex = '/(*UTF8)^[0-9\p{L}]+$/';

View file

@ -46,7 +46,7 @@ class LSformRule_callable extends LSformRule {
* *
* @return boolean true if the value is valid, false otherwise * @return boolean true if the value is valid, false otherwise
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$callable = LSconfig :: get('params.callable', null, null, $options); $callable = LSconfig :: get('params.callable', null, null, $options);
if (is_callable($callable)) if (is_callable($callable))
return call_user_func_array( return call_user_func_array(

View file

@ -35,39 +35,34 @@ class LSformRule_compare extends LSformRule {
); );
// Operators mapping // Operators mapping
static protected $_operators_aliases = array( static protected $_operators = array(
'==' => 'eq', 'eq' => '==',
'!=' => 'neq', 'neq' => '!=',
'>' => 'gt', 'gt' => '>',
'>=' => 'gte', 'gte' => '>=',
'<' => 'lt', 'lt' => '<',
'<=' => 'lte', 'lte' => '<='
);
static protected $_operators_to_compare_function = array(
'eq' => function($a, $b) {return floatval($a) == floatval($b);},
'neq' => function($a, $b) {return floatval($a) != floatval($b);},
'gt' => function($a, $b) {return $a > $b;},
'gte' => function($a, $b) {return $a >= $b;},
'lt' => function($a, $b) {return $a < $b;},
'lte' => function($a, $b) {return $a <= $b;},
); );
/** /**
* Return the compare function associated with the specified operator * Retourne l'operateur de comparaison.
* *
* @access private * @access private
* @param string The operator name * @param string Nom de l'operateur
* *
* @return function The compare function * @return string Operateur à utiliser
*/ */
private static function _findOperatorCompareFunction($operator_name) { private static function _findOperator($operator_name) {
if (empty($operator_name))
$operator_name = 'eq'; if (empty(self :: $operator_name)) {
elseif (isset(self :: $_operators_aliases[$operator_name])) return '==';
$operator_name = self :: $_operators_aliases[$operator_name]; } elseif (isset(self :: $_operators[$operator_name])) {
elseif (!isset(self :: $_operators_to_compare_function[$operator_name])) return self :: $_operators[$operator_name];
$operator_name = 'eq'; } elseif (in_array($operator_name, self :: $_operators)) {
return self :: $_operators_to_compare_function[$operator_name]; return $operator_name;
} else {
return '==';
}
} }
/** /**
@ -80,13 +75,19 @@ class LSformRule_compare extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($values, $options, &$formElement) { public static function validate($values, $options=array(), &$formElement) {
$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;
} }
$compareFn = self :: _findOperatorCompareFunction($operator); $operator = self :: _findOperator($operator);
if ('==' != $operator && '!=' != $operator) {
$compareFn = create_function('$a, $b', 'return floatval($a) ' . $operator . ' floatval($b);');
}
else {
$compareFn = create_function('$a, $b', 'return $a ' . $operator . ' $b;');
}
return $compareFn($values[0], $values[1]); return $compareFn($values[0], $values[1]);
} }

View file

@ -44,7 +44,7 @@ class LSformRule_date extends LSformRule {
* *
* @return boolean True si les données sont valide, False sinon. * @return boolean True si les données sont valide, False sinon.
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$special_values = LSconfig :: get('params.special_values', array(), null, $options); $special_values = LSconfig :: get('params.special_values', array(), null, $options);
if (in_array($value, $special_values)) if (in_array($value, $special_values))
return true; return true;

View file

@ -42,7 +42,7 @@ class LSformRule_differentPassword extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$otherPasswordAttributes = LSconfig :: get('params.otherPasswordAttributes', null, null, $options); $otherPasswordAttributes = LSconfig :: get('params.otherPasswordAttributes', null, null, $options);
if (!is_null($otherPasswordAttributes)) { if (!is_null($otherPasswordAttributes)) {
// Load LSattr_ldap_password // Load LSattr_ldap_password

View file

@ -43,7 +43,7 @@ class LSformRule_email extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
return checkEmail( return checkEmail(
$value, $value,
LSconfig :: get('params.domain', null, null, $options), LSconfig :: get('params.domain', null, null, $options),

View file

@ -44,7 +44,7 @@ class LSformRule_filesize extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
// According to PHP doc, strlen() returns the number of bytes rather // According to PHP doc, strlen() returns the number of bytes rather
// than the number of characters in a string. // than the number of characters in a string.
// See: https://www.php.net/manual/en/function.strlen.php // See: https://www.php.net/manual/en/function.strlen.php

View file

@ -40,7 +40,7 @@ class LSformRule_imagefile extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$file = LSsession :: getTmpFile($value); $file = LSsession :: getTmpFile($value);
$mimetype = mime_content_type($file); $mimetype = mime_content_type($file);

View file

@ -48,7 +48,7 @@ class LSformRule_imagesize extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$file = LSsession :: getTmpFile($value); $file = LSsession :: getTmpFile($value);
list($width, $height, $type, $attr) = getimagesize($file); list($width, $height, $type, $attr) = getimagesize($file);
self :: log_debug("validate(): image size is $width x $height, type=$type, attr='$attr'"); self :: log_debug("validate(): image size is $width x $height, type=$type, attr='$attr'");

View file

@ -45,7 +45,7 @@ class LSformRule_inarray extends LSformRule {
* *
* @return boolean true if the value is valid, false otherwise * @return boolean true if the value is valid, false otherwise
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$possible_values = LSconfig :: get('params.possible_values', null, null, $options); $possible_values = LSconfig :: get('params.possible_values', null, null, $options);
$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)) {

View file

@ -48,7 +48,7 @@ class LSformRule_integer extends LSformRule{
* *
* @return boolean true if the value is valided, false otherwise * @return boolean true if the value is valided, false otherwise
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$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)");

View file

@ -46,7 +46,7 @@ class LSformRule_ldapSearchURI extends LSformRule {
* *
* @return boolean true if the value is valid, false otherwise * @return boolean true if the value is valid, false otherwise
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
self :: log_trace("validate($value): options = ".varDump($options)); self :: log_trace("validate($value): options = ".varDump($options));
$uri_parts = explode('?', $value); $uri_parts = explode('?', $value);

View file

@ -36,7 +36,7 @@ class LSformRule_lettersonly extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$regex = '/^[a-zA-Z]+$/'; $regex = '/^[a-zA-Z]+$/';
LSsession :: loadLSclass('LSformRule_regex'); LSsession :: loadLSclass('LSformRule_regex');
return LSformRule_regex :: validate($value,$regex,$formElement); return LSformRule_regex :: validate($value,$regex,$formElement);

View file

@ -42,7 +42,7 @@ class LSformRule_maxlength extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$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'));

View file

@ -44,7 +44,7 @@ class LSformRule_mimetype extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$file = LSsession :: getTmpFile($value); $file = LSsession :: getTmpFile($value);
$real_mimetype = mime_content_type($file); $real_mimetype = mime_content_type($file);

View file

@ -42,7 +42,7 @@ class LSformRule_minlength extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$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'));

View file

@ -36,7 +36,7 @@ class LSformRule_nonzero extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$regex = '/^-?[1-9][0-9]*/'; $regex = '/^-?[1-9][0-9]*/';
LSsession :: loadLSclass('LSformRule_regex'); LSsession :: loadLSclass('LSformRule_regex');
return LSformRule_regex :: validate($value,$regex,$formElement); return LSformRule_regex :: validate($value,$regex,$formElement);

View file

@ -36,7 +36,7 @@ class LSformRule_nopunctuation extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$regex = '/^[^().\/\*\^\?#!@$%+=,\"\'><~\[\]{}]+$/'; $regex = '/^[^().\/\*\^\?#!@$%+=,\"\'><~\[\]{}]+$/';
LSsession :: loadLSclass('LSformRule_regex'); LSsession :: loadLSclass('LSformRule_regex');
return LSformRule_regex :: validate($value,$regex,$formElement); return LSformRule_regex :: validate($value,$regex,$formElement);

View file

@ -45,7 +45,7 @@ class LSformRule_numberOfValues extends LSformRule {
* *
* @return boolean true if the value is valide, false if not * @return boolean true if the value is valide, false if not
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$max_values = LSconfig :: get('params.max', null, 'int', $options); $max_values = LSconfig :: get('params.max', null, 'int', $options);
$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)) {

View file

@ -36,7 +36,7 @@ class LSformRule_numeric extends LSformRule{
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$regex = '/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/'; $regex = '/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/';
LSsession :: loadLSclass('LSformRule_regex'); LSsession :: loadLSclass('LSformRule_regex');
return LSformRule_regex :: validate($value,$regex,$formElement); return LSformRule_regex :: validate($value,$regex,$formElement);

View file

@ -52,7 +52,7 @@ class LSformRule_password extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$errors = array(); $errors = array();
$maxLength = LSconfig :: get('params.maxLength', null, 'int', $options); $maxLength = LSconfig :: get('params.maxLength', null, 'int', $options);

View file

@ -43,7 +43,7 @@ class LSformRule_rangelength extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$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'));

View file

@ -42,7 +42,7 @@ class LSformRule_regex extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
if (is_array($options)) { if (is_array($options)) {
$regex = LSconfig :: get('params.regex', null, 'string', $options); $regex = LSconfig :: get('params.regex', null, 'string', $options);
if (!is_string($regex)) { if (!is_string($regex)) {

View file

@ -36,7 +36,7 @@ class LSformRule_required extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
return ((string)$value != ''); return ((string)$value != '');
} }

View file

@ -36,7 +36,7 @@ class LSformRule_ssh_pub_key extends LSformRule {
* *
* @return boolean true if the value is valide, false if not * @return boolean true if the value is valide, false if not
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
if (preg_match('/^(ssh-[a-z0-9]+) +([^ ]+) +(.*)$/', $value, $m)) { if (preg_match('/^(ssh-[a-z0-9]+) +([^ ]+) +(.*)$/', $value, $m)) {
$data=@base64_decode($m[2]); $data=@base64_decode($m[2]);
if (is_string($data)) if (is_string($data))

View file

@ -36,7 +36,7 @@ class LSformRule_telephonenumber extends LSformRule {
* *
* @return boolean true si la valeur est valide, false sinon * @return boolean true si la valeur est valide, false sinon
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
$regex = '/^(01|02|03|04|05|06|08|09)[0-9]{8}$/'; $regex = '/^(01|02|03|04|05|06|08|09)[0-9]{8}$/';
LSsession :: loadLSclass('LSformRule_regex'); LSsession :: loadLSclass('LSformRule_regex');
return LSformRule_regex :: validate($value,$regex,$formElement); return LSformRule_regex :: validate($value,$regex,$formElement);

View file

@ -20,6 +20,14 @@
******************************************************************************/ ******************************************************************************/
use ZxcvbnPhp\Zxcvbn;
LSsession :: includeFile(
LSconfig :: get(
'params.zxcvbn_autoload_path', 'Zxcvbn/autoload.php',
'string', $options
), true
);
/** /**
* Rule to validate password using ZXCVBN-PHP lib * Rule to validate password using ZXCVBN-PHP lib
* *
@ -46,14 +54,8 @@ class LSformRule_zxcvbn extends LSformRule {
* *
* @return boolean True if value is valid, False otherwise * @return boolean True if value is valid, False otherwise
*/ */
public static function validate($value, $options, &$formElement) { public static function validate($value, $options=array(), &$formElement) {
LSsession :: includeFile( $zxcvbn = new Zxcvbn();
LSconfig :: get(
'params.zxcvbn_autoload_path', 'Zxcvbn/autoload.php',
'string', $options
), true
);
$zxcvbn = new ZxcvbnPhp\Zxcvbn();
$userData = array(); $userData = array();
$userDataAttrs = LSconfig :: get('params.userDataAttrs', array(), 'array', $options); $userDataAttrs = LSconfig :: get('params.userDataAttrs', array(), 'array', $options);
if ($userDataAttrs) { if ($userDataAttrs) {

View file

@ -290,9 +290,7 @@ class LSio extends LSlog_staticLoggerClass {
$object = new $LSobject(); $object = new $LSobject();
if (!$object -> loadData($dn)) { if (!$object -> loadData($dn)) {
self :: log_debug('import(): Failed to load data of '.$dn); self :: log_debug('import(): Failed to load data of '.$dn);
$globalErrors[] = getFData( $globalErrors[] = getFData(_("Failed to load existing object %{dn} from LDAP server. Can't update object."));
_("Failed to load existing object %{dn} from LDAP server. Can't update object."),
$dn);
} }
else { else {
// Instanciate a modify form (in API mode) // Instanciate a modify form (in API mode)
@ -587,7 +585,7 @@ class LSio extends LSlog_staticLoggerClass {
$ioFormat = $command_args[$i]; $ioFormat = $command_args[$i];
} }
else else
LScli :: usage("Invalid ".$command_args[$i]." parameter."); LScli :: usage("Invalid $arg parameter.");
} }
} }

View file

@ -33,7 +33,6 @@ class LSioFormatCSV extends LSioFormatDriver {
private $enclosure = null; private $enclosure = null;
private $escape = null; private $escape = null;
private $length = null; private $length = null;
private $multiple_value_delimiter = null;
private $rows = null; private $rows = null;
private $headers = null; private $headers = null;

View file

@ -231,360 +231,10 @@ if (php_sapi_name() != "cli") return true;
* *
* @retval boolean True on success, false otherwise * @retval boolean True on success, false otherwise
**/ **/
global $LSlang_cli_logger, $available_onlys, $available_withouts; global $LSlang_cli_logger, $available_onlys, $available_withouts;
function _cli_relative2absolute_path($path) { $available_onlys = array("config", "templates", "addons", "auth_methods", "includes");
if ($path[0] == '/') $available_withouts = array_merge($available_onlys, array("select-list"));
return $path;
global $curdir;
return realpath($curdir)."/".$path;
}
function _cli_absolute2relative_path($path) {
if ($path[0] == '/')
$path = realpath($path);
if (substr($path, 0, strlen(LS_ROOT_DIR)) == LS_ROOT_DIR)
return substr($path, strlen(LS_ROOT_DIR)+1);
return $path;
}
function _cli_interactive_ask($context, $msg) {
global $copyoriginalvalue, $interactive_exit;
if ($interactive_exit) {
if ($copyoriginalvalue)
return $msg;
return true;
}
// Format question
$empty_action = ($copyoriginalvalue?'copy original message':'pass');
$question ="\"$msg\"\n\n => Please enter translated string";
$question .= " (i";
if (!$copyoriginalvalue)
$question .= "/c";
$question .= "/q/? or leave empty to $empty_action): ";
while (true) {
if ($context)
fwrite(STDERR, "\n# $context\n");
fwrite(STDERR, $question);
$in = trim(fgets(STDIN));
switch($in) {
case 'q': // Exit interactive mode
case 'Q':
$interactive_exit = true;
return True;
case 'i': // Ignore
case 'I':
return True;
case 'c':
case 'C': // Copy
if (!$copyoriginalvalue)
return $msg;
case '?': // Help message
fwrite(STDERR, "Available choices:\n");
fwrite(STDERR, " - i: ignore this message\n");
if (!$copyoriginalvalue)
fwrite(STDERR, " - c: copy original message\n");
fwrite(STDERR, " - q: quit interactive mode and ignore all following untranslated messages\n");
fwrite(STDERR, " - ?: Show this message\n");
fwrite(STDERR, "Or leave empty to $empty_action.\n");
break;
case "": // Empty
// On copy orignal value mode, return $msg
if ($copyoriginalvalue)
return $msg;
// Otherwise, leave translation empty
return "";
default:
// Return user input
return $in;
}
}
// Supposed to never happen
return true;
}
function _cli_add_str_to_translate($msg, $context=null) {
global $LSlang_cli_logger, $lang, $data, $translations, $interactive, $interactive_exit, $copyoriginalvalue, $format;
$LSlang_cli_logger -> trace("_cli_add_str_to_translate($msg, $context)");
if ($msg == '')
return;
if (!is_null($lang) && _($msg) != "$msg")
return;
// Message already exists ?
if (array_key_exists($msg, $data)) {
if ($context && !in_array($context, $data[$msg]['contexts']))
$data[$msg]['contexts'][] = $context;
return True;
}
// Handle translation
$translation = "";
if (array_key_exists($msg, $translations)) {
$translation = $translations[$msg];
}
elseif (!is_null($lang) && _($msg) != $msg) {
$translation = _($msg);
}
elseif ($interactive && $format != 'pot') {
$translation = _cli_interactive_ask($context, $msg);
if (!is_string($translation))
return true;
}
$data[$msg] = array (
'translation' => $translation,
'contexts' => ($context?array($context):array()),
);
}
function _cli_add_str_to_translate_from_LSconfig($pattern, $value='value', $excludes=array()) {
global $LSlang_cli_logger;
$LSlang_cli_logger -> trace("_cli_add_str_to_translate_from_LSconfig($pattern, array(".implode(',', $excludes)."))");
$keys = LSconfig :: getMatchingKeys($pattern);
$LSlang_cli_logger -> trace("addFromLSconfig : ".count($keys)." matching key(s)");
foreach ($keys as $key => $value) {
$LSlang_cli_logger -> trace("addFromLSconfig : $key = ".varDump($value));
if ($value == 'key') {
// Get the last key parts as value and all other as key
$key_parts = explode('.', $key);
$value = $key_parts[count($key_parts)-1];
$key = implode('.', array_slice($key_parts, 0, count($key_parts)-1));
}
if (!in_array($value, $excludes) && is_string($value))
_cli_add_str_to_translate($value, $key);
}
}
function _cli_add_possible_values_from_LSconfig($context, $withouts, $level=0) {
global $LSlang_cli_logger;
$LSlang_cli_logger -> trace("_cli_add_possible_values_from_LSconfig($context)");
if (in_array('select-list', $withouts))
return true;
if (!LSconfig :: get("$context.translate_labels", True, "bool"))
return true;
foreach(LSconfig :: get("$context.possible_values", array()) as $pkey => $plabel) {
if (is_array($plabel)) {
// Sub possible values
// Check level
if ($level > 1) {
$LSlang_cli_logger -> warning(
"_cli_add_possible_values_from_LSconfig($context): Level to hight to handle sub possible values of $context.possible_values.$pkey"
);
return true;
}
_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");
_cli_add_possible_values_from_LSconfig("$context.possible_values.$pkey", $withouts, $level+1);
}
else {
switch ($pkey) {
case 'OTHER_OBJECT':
$LSlang_cli_logger -> trace("_cli_add_possible_values_from_LSconfig($context): ignore $context.possible_values.$pkey (OTHER_OBJECT)");
break;
case 'OTHER_ATTRIBUTE':
if (is_array($plabel)) {
if (isset($plabel['json_component_key']))
_cli_add_str_to_translate_from_LSconfig("$context.possible_values.OTHER_ATTRIBUTE.json_component_label");
else
_cli_add_str_to_translate_from_LSconfig("$context.possible_values.OTHER_ATTRIBUTE.*");
}
else {
$LSlang_cli_logger -> warning("_cli_add_possible_values_from_LSconfig($context): invalid $context.possible_values.OTHER_ATTRIBUTE config => Must be an array.");
}
break;
default:
_cli_add_str_to_translate($plabel, "$context.possible_values.$pkey");
break;
}
}
}
}
function _cli_parse_template_file($file) {
global $LSlang_cli_logger;
$LSlang_cli_logger -> debug("Looking for string to translate in '$file' template file");
$count = 0;
foreach(file($file) as $line) {
$count ++;
if (preg_match_all('/\{ *tr +msg=["\']([^\}]+)["\'] *\}/',$line,$matches)) {
foreach($matches[1] as $t) {
$t = preg_replace('/[\'"]\|escape\:.*$/', '', $t);
$LSlang_cli_logger -> trace(" - \"$t\" # Line $count");
_cli_add_str_to_translate($t, _cli_absolute2relative_path($file).":$count");
}
}
}
$LSlang_cli_logger -> trace("_cli_parse_template_file($file) : done.");
}
function _cli_find_and_parse_template_file($dir) {
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if ($file=='.' || $file=='..') continue;
if (is_dir($dir.'/'.$file)) {
_cli_find_and_parse_template_file($dir.'/'.$file);
}
elseif (is_file($dir."/".$file) && preg_match('/\.tpl$/',$file)) {
_cli_parse_template_file($dir.'/'.$file);
}
}
closedir($dh);
}
}
}
function _cli_parse_php_file($file) {
global $LSlang_cli_logger;
$LSlang_cli_logger -> debug("Looking for string to translate in '$file' PHP file");
$count = 0;
$quote='';
$res='';
foreach(file($file) as $line) {
$count++;
$LSlang_cli_logger -> trace("Handle line #$count of '$file' PHP file");
$offset=0;
while ($pos = strpos($line,'__(',$offset)) {
$LSlang_cli_logger -> trace("$file:$count: detect keyword at position #$pos ('$line')");
for ($i=$pos+3;$i<strlen($line);$i++) {
$offset=$i; // Always increase offset to avoid infinity-loop
if (empty($quote)) {
// Quote char not detected : try to detect it
if ($line[$i]=='\\' || $line[$i]==" " || $line[$i]=="\t") {
// Space or escape char : pass
$i++;
}
elseif ($line[$i]=='"' || $line[$i]=="'") {
// Quote detected
$quote=$line[$i];
}
elseif ($line[$i]=='$' || $line[$i]==')') {
// Variable translation not possible or end function call detected
break;
}
else {
// Unknown case : continue
$i++;
}
}
elseif ($quote) {
// Quote char already detected : try to detect end quote char
if ($line[$i]=='\\') {
// Escape char detected : pass this char and the following one
$res.=$line[$i];
$i++;
$res.=$line[$i];
}
elseif ($line[$i]==$quote) {
// End quote char detected : reset quote char detection and break detection
$quote='';
break;
}
else {
// End quote char not detected : append current char to result
$res.=$line[$i];
}
}
}
// Include detected string if not empty and quote char was detected and reseted
if (!empty($res) && empty($quote)) {
_cli_add_str_to_translate($res, _cli_absolute2relative_path($file).":$count");
$res='';
}
}
}
}
function _cli_find_and_parse_php_file($dir, $filename_regex) {
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (preg_match($filename_regex, $file)) {
_cli_parse_php_file($dir.'/'.$file);
}
}
closedir($dh);
}
}
}
function _cli_output_php($fd) {
global $LSlang_cli_logger, $additionalfileformat, $data, $copyoriginalvalue, $keep_unused, $translations;
fwrite($fd, "<?php\n\n");
if (!$additionalfileformat) fwrite($fd, "\$GLOBALS['LSlang'] = array (\n");
foreach($data as $key => $key_data) {
if ($copyoriginalvalue && $key_data['translation'] == "") {
$val = $key;
}
else
$val = $key_data['translation'];
$key=str_replace('"','\\"',$key);
$val=str_replace('"','\\"',$val);
foreach ($key_data['contexts'] as $context)
fwrite($fd, "\n# $context");
if ($additionalfileformat) {
fwrite($fd, "\n\$GLOBALS['LSlang'][\"$key\"] = \"$val\";\n");
}
else {
fwrite($fd, "\n\"$key\" =>\n \"$val\",\n");
}
}
// Handle keep unused mode
if ($keep_unused) {
$unused_msgs = array();
foreach ($translations as $msg => $trans)
if (!array_key_exists($msg, $data))
$unused_msgs[$msg] = $trans;
if ($unused_msgs) {
fwrite($fd, "\n\n");
fwrite($fd, "######################################################################\n");
fwrite($fd, "# Unused translations keeped #\n");
fwrite($fd, "######################################################################\n");
foreach($unused_msgs as $key => $val) {
$key=str_replace('"','\\"',$key);
$val=str_replace('"','\\"',$val);
if ($additionalfileformat) {
fwrite($fd, "\n\$GLOBALS['LSlang'][\"$key\"] = \"$val\";\n");
}
else {
fwrite($fd, "\n\"$key\" =>\n \"$val\",\n");
}
}
}
}
if (!$additionalfileformat) fwrite($fd, "\n);\n");
}
function _cli_clean_for_pot_file($val) {
$val = str_replace('"', '\\"', $val);
return str_replace("\n", "\\n", $val);
}
function _cli_output_pot($fd) {
global $LSlang_cli_logger, $data, $copyoriginalvalue;
foreach($data as $key => $key_data) {
if ($copyoriginalvalue && $key_data['translation'] == "") {
$val = $key;
}
else
$val = $key_data['translation'];
foreach ($key_data['contexts'] as $context)
fwrite($fd, "#: $context\n");
$key = _cli_clean_for_pot_file($key);
$val = _cli_clean_for_pot_file($val);
fwrite($fd, "msgid \"$key\"\nmsgstr \"$val\"\n\n");
}
}
$available_onlys = array("config", "templates", "addons", "auth_methods", "includes");
$available_withouts = array_merge($available_onlys, array("select-list"));
function cli_generate_lang_file($command_args) { function cli_generate_lang_file($command_args) {
// Use global variables to share it with sub-functions // Use global variables to share it with sub-functions
global $LSlang_cli_logger, $available_onlys, $available_withouts, $data, $translations, $interactive, global $LSlang_cli_logger, $available_onlys, $available_withouts, $data, $translations, $interactive,
@ -623,6 +273,21 @@ function cli_generate_lang_file($command_args) {
$curdir = getcwd(); $curdir = getcwd();
chdir(dirname(__FILE__).'/../'); chdir(dirname(__FILE__).'/../');
function relative2absolute_path($path) {
if ($path[0] == '/')
return $path;
global $curdir;
return realpath($curdir)."/".$path;
}
function absolute2relative_path($path) {
if ($path[0] == '/')
$path = realpath($path);
if (substr($path, 0, strlen(LS_ROOT_DIR)) == LS_ROOT_DIR)
return substr($path, strlen(LS_ROOT_DIR)+1);
return $path;
}
for ($i=0; $i < count($command_args); $i++) { for ($i=0; $i < count($command_args); $i++) {
switch ($command_args[$i]) { switch ($command_args[$i]) {
case '--without': case '--without':
@ -644,7 +309,7 @@ function cli_generate_lang_file($command_args) {
$only = strtolower($command_args[$i]); $only = strtolower($command_args[$i]);
if (!in_array($only, $available_onlys)) if (!in_array($only, $available_onlys))
LScli :: usage("Invalid -O/--only parameter. Must be one of the following values : '".implode("','", $available_onlys)."'."); LScli :: usage("Invalid -O/--only parameter. Must be one of the following values : '".implode("','", $available_onlys)."'.");
elseif ($withouts) elseif ($without)
LScli :: usage("You could not use only -O/--only parameter combined with -W/--without parameter."); LScli :: usage("You could not use only -O/--only parameter combined with -W/--without parameter.");
break; break;
@ -712,7 +377,7 @@ function cli_generate_lang_file($command_args) {
break; break;
default: default:
$path = _cli_relative2absolute_path($command_args[$i]); $path = relative2absolute_path($command_args[$i]);
if (is_file($path)) if (is_file($path))
$load_files[] = $path; $load_files[] = $path;
else else
@ -720,7 +385,115 @@ function cli_generate_lang_file($command_args) {
} }
} }
function interactive_ask($context, $msg) {
global $copyoriginalvalue, $interactive_exit;
if ($interactive_exit) {
if ($copyoriginalvalue)
return $msg;
return true;
}
// Format question
$empty_action = ($copyoriginalvalue?'copy original message':'pass');
$question ="\"$msg\"\n\n => Please enter translated string";
$question .= " (i";
if (!$copyoriginalvalue)
$question .= "/c";
$question .= "/q/? or leave empty to $empty_action): ";
while (true) {
if ($context)
fwrite(STDERR, "\n# $context\n");
fwrite(STDERR, $question);
$in = trim(fgets(STDIN));
switch($in) {
case 'q': // Exit interactive mode
case 'Q':
$interactive_exit = true;
return True;
case 'i': // Ignore
case 'I':
return True;
case 'c':
case 'C': // Copy
if (!$copyoriginalvalue)
return $msg;
case '?': // Help message
fwrite(STDERR, "Available choices:\n");
fwrite(STDERR, " - i: ignore this message\n");
if (!$copyoriginalvalue)
fwrite(STDERR, " - c: copy original message\n");
fwrite(STDERR, " - q: quit interactive mode and ignore all following untranslated messages\n");
fwrite(STDERR, " - ?: Show this message\n");
fwrite(STDERR, "Or leave empty to $empty_action.\n");
break;
case "": // Empty
// On copy orignal value mode, return $msg
if ($copyoriginalvalue)
return $msg;
// Otherwise, leave translation empty
return "";
default:
// Return user input
return $in;
}
}
// Supposed to never happen
return true;
}
function add($msg, $context=null) {
global $LSlang_cli_logger, $lang, $data, $translations, $interactive, $interactive_exit, $copyoriginalvalue, $format;
$LSlang_cli_logger -> trace("add($msg, $context)");
if ($msg == '')
return;
if (!is_null($lang) && _($msg) != "$msg")
return;
// Message already exists ?
if (array_key_exists($msg, $data)) {
if ($context && !in_array($context, $data[$msg]['contexts']))
$data[$msg]['contexts'][] = $context;
return True;
}
// Handle translation
$translation = "";
if (array_key_exists($msg, $translations)) {
$translation = $translations[$msg];
}
elseif (!is_null($lang) && _($msg) != $msg) {
$translation = _($msg);
}
elseif ($interactive && $format != 'pot') {
$translation = interactive_ask($context, $msg);
if (!is_string($translation))
return true;
}
$data[$msg] = array (
'translation' => $translation,
'contexts' => ($context?array($context):array()),
);
}
function addFromLSconfig($pattern, $value='value', $excludes=array()) {
global $LSlang_cli_logger;
$LSlang_cli_logger -> trace("addFromLSconfig($pattern, array(".implode(',', $excludes)."))");
$keys = LSconfig :: getMatchingKeys($pattern);
$LSlang_cli_logger -> trace("addFromLSconfig : ".count($keys)." matching key(s)");
foreach ($keys as $key => $value) {
$LSlang_cli_logger -> trace("addFromLSconfig : $key = ".varDump($value));
if ($value == 'key') {
// Get the last key parts as value and all other as key
$key_parts = explode('.', $key);
$value = $key_parts[count($key_parts)-1];
$key = implode('.', array_slice($key_parts, 0, count($key_parts)-1));
}
if (!in_array($value, $excludes) && is_string($value))
add($value, $key);
}
}
// In fix-utf8 mode, load ForceUT8/Encoding lib // In fix-utf8 mode, load ForceUT8/Encoding lib
if ($fix_utf8) if ($fix_utf8)
@ -751,6 +524,51 @@ function cli_generate_lang_file($command_args) {
} }
} }
function addPossibleValuesFromLSconfig($context, $withouts, $level=0) {
global $LSlang_cli_logger;
$LSlang_cli_logger -> trace("addPossibleValuesFromLSconfig($context)");
if (in_array('select-list', $withouts))
return true;
if (!LSconfig :: get("$context.translate_labels", True, "bool"))
return true;
foreach(LSconfig :: get("$context.possible_values", array()) as $pkey => $plabel) {
if (is_array($plabel)) {
// Sub possible values
// Check level
if ($level > 1) {
$LSlang_cli_logger -> warning(
"addPossibleValuesFromLSconfig($context): Level to hight to handle sub possible values of $context.possible_values.$pkey"
);
return true;
}
addFromLSconfig("$context.possible_values.$pkey.label");
$LSlang_cli_logger -> trace("addPossibleValuesFromLSconfig($context): handle sub possible values of $context.possible_values.$pkey");
addPossibleValuesFromLSconfig("$context.possible_values.$pkey", $withouts, $level+1);
}
else {
switch ($pkey) {
case 'OTHER_OBJECT':
$LSlang_cli_logger -> trace("addPossibleValuesFromLSconfig($context): ignore $context.possible_values.$pkey (OTHER_OBJECT)");
break;
case 'OTHER_ATTRIBUTE':
if (is_array($plabel)) {
if (isset($plabel['json_component_key']))
addFromLSconfig("$context.possible_values.OTHER_ATTRIBUTE.json_component_label");
else
addFromLSconfig("$context.possible_values.OTHER_ATTRIBUTE.*");
}
else {
$LSlang_cli_logger -> warning("addPossibleValuesFromLSconfig($context): invalid $context.possible_values.OTHER_ATTRIBUTE config => Must be an array.");
}
break;
default:
add($plabel, "$context.possible_values.$pkey");
break;
}
}
}
}
/* /*
* Manage configuration parameters * Manage configuration parameters
*/ */
@ -760,14 +578,14 @@ function cli_generate_lang_file($command_args) {
$LSlang_cli_logger -> info("Looking for string to translate configuration of LDAP servers"); $LSlang_cli_logger -> info("Looking for string to translate configuration of LDAP servers");
foreach(LSconfig :: keys('ldap_servers') as $ldap_server_id) { foreach(LSconfig :: keys('ldap_servers') as $ldap_server_id) {
$LSlang_cli_logger -> debug("Looking for string to translate configuration of LDAP server #$ldap_server_id"); $LSlang_cli_logger -> debug("Looking for string to translate configuration of LDAP server #$ldap_server_id");
_cli_add_str_to_translate_from_LSconfig("ldap_servers.$ldap_server_id.name"); addFromLSconfig("ldap_servers.$ldap_server_id.name");
_cli_add_str_to_translate_from_LSconfig("ldap_servers.$ldap_server_id.subDnLabel"); addFromLSconfig("ldap_servers.$ldap_server_id.subDnLabel");
_cli_add_str_to_translate_from_LSconfig("ldap_servers.$ldap_server_id.recoverPassword.recoveryHashMail.subject"); addFromLSconfig("ldap_servers.$ldap_server_id.recoverPassword.recoveryHashMail.subject");
_cli_add_str_to_translate_from_LSconfig("ldap_servers.$ldap_server_id.recoverPassword.recoveryHashMail.msg"); addFromLSconfig("ldap_servers.$ldap_server_id.recoverPassword.recoveryHashMail.msg");
_cli_add_str_to_translate_from_LSconfig("ldap_servers.$ldap_server_id.recoverPassword.newPasswordMail.subject"); addFromLSconfig("ldap_servers.$ldap_server_id.recoverPassword.newPasswordMail.subject");
_cli_add_str_to_translate_from_LSconfig("ldap_servers.$ldap_server_id.recoverPassword.newPasswordMail.msg"); addFromLSconfig("ldap_servers.$ldap_server_id.recoverPassword.newPasswordMail.msg");
_cli_add_str_to_translate_from_LSconfig("ldap_servers.$ldap_server_id.subDn.*", 'key', array("LSobject")); addFromLSconfig("ldap_servers.$ldap_server_id.subDn.*", 'key', array("LSobject"));
_cli_add_str_to_translate_from_LSconfig("ldap_servers.$ldap_server_id.LSprofiles.*.label"); addFromLSconfig("ldap_servers.$ldap_server_id.LSprofiles.*.label");
// LSaccess // LSaccess
foreach (LSconfig :: get("ldap_servers.$ldap_server_id.LSaccess", array()) as $LSobject) { foreach (LSconfig :: get("ldap_servers.$ldap_server_id.LSaccess", array()) as $LSobject) {
@ -788,76 +606,76 @@ function cli_generate_lang_file($command_args) {
// LSobject // LSobject
foreach($objects as $obj) { foreach($objects as $obj) {
$LSlang_cli_logger -> info("Looking for string to translate configuration of object type $obj"); $LSlang_cli_logger -> info("Looking for string to translate configuration of object type $obj");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.label"); addFromLSconfig("LSobjects.$obj.label");
// LSrelation // LSrelation
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.LSrelation.*.label"); addFromLSconfig("LSobjects.$obj.LSrelation.*.label");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.LSrelation.*.emptyText"); addFromLSconfig("LSobjects.$obj.LSrelation.*.emptyText");
// Custom Actions // Custom Actions
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.customActions.*.label"); addFromLSconfig("LSobjects.$obj.customActions.*.label");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.customActions.*.helpInfo"); addFromLSconfig("LSobjects.$obj.customActions.*.helpInfo");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.customActions.*.question_format"); addFromLSconfig("LSobjects.$obj.customActions.*.question_format");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.customActions.*.onSuccessMsgFormat"); addFromLSconfig("LSobjects.$obj.customActions.*.onSuccessMsgFormat");
// LSform // LSform
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.LSform.layout.*.label"); addFromLSconfig("LSobjects.$obj.LSform.layout.*.label");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.LSform.dataEntryForm.*.label"); addFromLSconfig("LSobjects.$obj.LSform.dataEntryForm.*.label");
// LSsearch // LSsearch
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.LSsearch.predefinedFilters.*"); addFromLSconfig("LSobjects.$obj.LSsearch.predefinedFilters.*");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.LSsearch.extraDisplayedColumns.*.label"); addFromLSconfig("LSobjects.$obj.LSsearch.extraDisplayedColumns.*.label");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.LSsearch.extraDisplayedColumns.*.LSformat"); addFromLSconfig("LSobjects.$obj.LSsearch.extraDisplayedColumns.*.LSformat");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.LSsearch.extraDisplayedColumns.*.alternativeLSformats.*"); addFromLSconfig("LSobjects.$obj.LSsearch.extraDisplayedColumns.*.alternativeLSformats.*");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.LSsearch.extraDisplayedColumns.*.formaterLSformat"); addFromLSconfig("LSobjects.$obj.LSsearch.extraDisplayedColumns.*.formaterLSformat");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.LSsearch.customActions.*.label"); addFromLSconfig("LSobjects.$obj.LSsearch.customActions.*.label");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.LSsearch.customActions.*.question_format"); addFromLSconfig("LSobjects.$obj.LSsearch.customActions.*.question_format");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.LSsearch.customActions.*.onSuccessMsgFormat"); addFromLSconfig("LSobjects.$obj.LSsearch.customActions.*.onSuccessMsgFormat");
// Attributes // Attributes
foreach(LSconfig :: keys("LSobjects.$obj.attrs") as $attr) { foreach(LSconfig :: keys("LSobjects.$obj.attrs") as $attr) {
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.attrs.$attr.label"); addFromLSconfig("LSobjects.$obj.attrs.$attr.label");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.attrs.$attr.help_info"); addFromLSconfig("LSobjects.$obj.attrs.$attr.help_info");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.attrs.$attr.no_value_label"); addFromLSconfig("LSobjects.$obj.attrs.$attr.no_value_label");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.attrs.$attr.check_data.*.msg"); addFromLSconfig("LSobjects.$obj.attrs.$attr.check_data.*.msg");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.attrs.$attr.validation.*.msg"); addFromLSconfig("LSobjects.$obj.attrs.$attr.validation.*.msg");
// HTML Options // HTML Options
$html_type = LSconfig :: get("LSobjects.$obj.attrs.$attr.html_type"); $html_type = LSconfig :: get("LSobjects.$obj.attrs.$attr.html_type");
switch($html_type) { switch($html_type) {
case 'boolean': case 'boolean':
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.attrs.$attr.html_options.true_label"); addFromLSconfig("LSobjects.$obj.attrs.$attr.html_options.true_label");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.attrs.$attr.html_options.false_label"); addFromLSconfig("LSobjects.$obj.attrs.$attr.html_options.false_label");
break; break;
case 'jsonCompositeAttribute': case 'jsonCompositeAttribute':
$components = LSconfig :: keys("LSobjects.$obj.attrs.$attr.html_options.components"); $components = LSconfig :: keys("LSobjects.$obj.attrs.$attr.html_options.components");
foreach($components as $c) { foreach($components as $c) {
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.attrs.$attr.html_options.components.$c.label"); addFromLSconfig("LSobjects.$obj.attrs.$attr.html_options.components.$c.label");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.attrs.$attr.html_options.components.$c.help_info"); addFromLSconfig("LSobjects.$obj.attrs.$attr.html_options.components.$c.help_info");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.attrs.$attr.html_options.components.$c.check_data.*.msg"); addFromLSconfig("LSobjects.$obj.attrs.$attr.html_options.components.$c.check_data.*.msg");
if (LSconfig :: get("LSobjects.$obj.attrs.$attr.html_options.components.$c.type") == 'select_list') if (LSconfig :: get("LSobjects.$obj.attrs.$attr.html_options.components.$c.type") == 'select_list')
_cli_add_possible_values_from_LSconfig("LSobjects.$obj.attrs.$attr.html_options.components.$c.options", $withouts); addPossibleValuesFromLSconfig("LSobjects.$obj.attrs.$attr.html_options.components.$c.options", $withouts);
} }
break; break;
case 'labeledValue': case 'labeledValue':
if (LSconfig :: get("LSobjects.$obj.attrs.$attr.html_options.translate_labels", True, "bool")) if (LSconfig :: get("LSobjects.$obj.attrs.$attr.html_options.translate_labels", True, "bool"))
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.attrs.$attr.html_options.labels.*"); addFromLSconfig("LSobjects.$obj.attrs.$attr.html_options.labels.*");
break; break;
case 'password': case 'password':
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.attrs.$attr.html_options.mail.subject"); addFromLSconfig("LSobjects.$obj.attrs.$attr.html_options.mail.subject");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.attrs.$attr.html_options.mail.msg"); addFromLSconfig("LSobjects.$obj.attrs.$attr.html_options.mail.msg");
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.attrs.$attr.html_options.confirmChangeQuestion"); addFromLSconfig("LSobjects.$obj.attrs.$attr.html_options.confirmChangeQuestion");
break; break;
case 'select_list': case 'select_list':
case 'select_box': case 'select_box':
_cli_add_possible_values_from_LSconfig("LSobjects.$obj.attrs.$attr.html_options", $withouts); addPossibleValuesFromLSconfig("LSobjects.$obj.attrs.$attr.html_options", $withouts);
break; break;
case 'valueWithUnit': case 'valueWithUnit':
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.attrs.$attr.html_options.units.*"); addFromLSconfig("LSobjects.$obj.attrs.$attr.html_options.units.*");
break; break;
case 'date': case 'date':
_cli_add_str_to_translate_from_LSconfig("LSobjects.$obj.attrs.$attr.html_options.special_values.*"); addFromLSconfig("LSobjects.$obj.attrs.$attr.html_options.special_values.*");
break; break;
} }
} }
@ -868,39 +686,151 @@ function cli_generate_lang_file($command_args) {
* Manage template file * Manage template file
*/ */
if (!in_array('templates', $withouts) && (!$only || $only == 'templates')) { if (!in_array('templates', $withouts) && (!$only || $only == 'templates')) {
function parse_template_file($file) {
global $LSlang_cli_logger;
$LSlang_cli_logger -> debug("Looking for string to translate in '$file' template file");
$count = 0;
foreach(file($file) as $line) {
$count ++;
if (preg_match_all('/\{ *tr +msg=["\']([^\}]+)["\'] *\}/',$line,$matches)) {
foreach($matches[1] as $t) {
$t = preg_replace('/[\'"]\|escape\:.*$/', '', $t);
$LSlang_cli_logger -> trace(" - \"$t\" # Line $count");
add($t, absolute2relative_path($file).":$count");
}
}
}
$LSlang_cli_logger -> trace("parse_template_file($file) : done.");
}
function find_and_parse_template_file($dir) {
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if ($file=='.' || $file=='..') continue;
if (is_dir($dir.'/'.$file)) {
find_and_parse_template_file($dir.'/'.$file);
}
elseif (is_file($dir."/".$file) && preg_match('/\.tpl$/',$file)) {
parse_template_file($dir.'/'.$file);
}
}
closedir($dh);
}
}
}
$LSlang_cli_logger -> info("Looking for string to translate in templates file"); $LSlang_cli_logger -> info("Looking for string to translate in templates file");
if ($include_upstream) _cli_find_and_parse_template_file(LS_ROOT_DIR.'/'.LS_TEMPLATES_DIR); if ($include_upstream) find_and_parse_template_file(LS_ROOT_DIR.'/'.LS_TEMPLATES_DIR);
_cli_find_and_parse_template_file(LS_ROOT_DIR.'/'.LS_LOCAL_DIR.LS_TEMPLATES_DIR); find_and_parse_template_file(LS_ROOT_DIR.'/'.LS_LOCAL_DIR.LS_TEMPLATES_DIR);
} }
/* /*
* Manage custom PHP code/config files * Manage custom PHP code/config files
*/ */
function parse_php_file($file) {
global $LSlang_cli_logger;
$LSlang_cli_logger -> debug("Looking for string to translate in '$file' PHP file");
$count = 0;
$quote='';
$res='';
foreach(file($file) as $line) {
$count++;
$LSlang_cli_logger -> trace("Handle line #$count of '$file' PHP file");
$offset=0;
while ($pos = strpos($line,'__(',$offset)) {
$LSlang_cli_logger -> trace("$file:$count: detect keyword at position #$pos ('$line')");
for ($i=$pos+3;$i<strlen($line);$i++) {
$offset=$i; // Always increase offset to avoid infinity-loop
if (empty($quote)) {
// Quote char not detected : try to detect it
if ($line[$i]=='\\' || $line[$i]==" " || $line[$i]=="\t") {
// Space or escape char : pass
$i++;
}
elseif ($line[$i]=='"' || $line[$i]=="'") {
// Quote detected
$quote=$line[$i];
}
elseif ($line[$i]=='$' || $line[$i]==')') {
// Variable translation not possible or end function call detected
break;
}
else {
// Unknown case : continue
$i++;
}
}
elseif (!empty($quote)) {
// Quote char already detected : try to detect end quote char
if ($line[$i]=='\\') {
// Escape char detected : pass this char and the following one
$res.=$line[$i];
$i++;
$res.=$line[$i];
}
elseif ($line[$i]==$quote) {
// End quote char detected : reset quote char detection and break detection
$quote='';
break;
}
else {
// End quote char not detected : append current char to result
$res.=$line[$i];
}
}
}
// Include detected string if not empty and quote char was detected and reseted
if (!empty($res) && empty($quote)) {
add($res, absolute2relative_path($file).":$count");
$res='';
}
}
}
}
// Manage includes files function find_and_parse_php_file($dir, $filename_regex) {
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (preg_match($filename_regex, $file)) {
parse_php_file($dir.'/'.$file);
}
}
closedir($dh);
}
}
}
/*
* Manage includes files
*/
if (!in_array('includes', $withouts) && (!$only || $only == 'includes')) { if (!in_array('includes', $withouts) && (!$only || $only == 'includes')) {
// Note: Upstream code most only use gettext translation, do not handle it here // Note: Upstream code most only use gettext translation, do not handle it here
if ($include_upstream) _cli_find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_INCLUDE_DIR, '/^(.+)\.php$/'); if ($include_upstream) find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_INCLUDE_DIR, '/^(.+)\.php$/');
_cli_find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_LOCAL_DIR.LS_INCLUDE_DIR, '/^(.+)\.php$/'); find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_LOCAL_DIR.LS_INCLUDE_DIR, '/^(.+)\.php$/');
if ($include_upstream) _cli_find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_CLASS_DIR, '/^class\.(.+)\.php$/'); if ($include_upstream) find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_CLASS_DIR, '/^class\.(.+)\.php$/');
_cli_find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_LOCAL_DIR.LS_CLASS_DIR, '/^class\.(.+)\.php$/'); find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_LOCAL_DIR.LS_CLASS_DIR, '/^class\.(.+)\.php$/');
} }
// Manage addons files /*
* Manage addons files
*/
if (!in_array('addons', $withouts) && (!$only || $only == 'addons')) { if (!in_array('addons', $withouts) && (!$only || $only == 'addons')) {
$LSlang_cli_logger -> info("Looking for string to translate in LSaddons PHP code"); $LSlang_cli_logger -> info("Looking for string to translate in LSaddons PHP code");
if ($include_upstream) _cli_find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_ADDONS_DIR, '/^LSaddons\.(.+)\.php$/'); if ($include_upstream) find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_ADDONS_DIR, '/^LSaddons\.(.+)\.php$/');
_cli_find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_LOCAL_DIR.LS_ADDONS_DIR, '/^LSaddons\.(.+)\.php$/'); find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_LOCAL_DIR.LS_ADDONS_DIR, '/^LSaddons\.(.+)\.php$/');
$LSlang_cli_logger -> info("Looking for string to translate in LSaddons configuration files"); $LSlang_cli_logger -> info("Looking for string to translate in LSaddons configuration files");
if ($include_upstream) _cli_find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_CONF_DIR.'/LSaddons', '/^config\.LSaddons\.(.+)\.php$$/'); if ($include_upstream) find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_CONF_DIR.'/LSaddons', '/^config\.LSaddons\.(.+)\.php$$/');
_cli_find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_LOCAL_DIR.LS_CONF_DIR.'/LSaddons', '/^config\.LSaddons\.(.+)\.php$$/'); find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_LOCAL_DIR.LS_CONF_DIR.'/LSaddons', '/^config\.LSaddons\.(.+)\.php$$/');
} }
// Manage auth methods files /*
* Manage auth methods files
*/
if (!in_array('auth_methods', $withouts) && (!$only || $only == 'auth_methods')) { if (!in_array('auth_methods', $withouts) && (!$only || $only == 'auth_methods')) {
$LSlang_cli_logger -> info("Looking for string to translate in LSauthMethods configuration files"); $LSlang_cli_logger -> info("Looking for string to translate in LSauthMethods configuration files");
if ($include_upstream) _cli_find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_CONF_DIR.'/LSauth', '/^config\.(.+)\.php$$/'); if ($include_upstream) find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_CONF_DIR.'/LSauth', '/^config\.(.+)\.php$$/');
_cli_find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_LOCAL_DIR.LS_CONF_DIR.'/LSauth', '/^config\.(.+)\.php$$/'); find_and_parse_php_file(LS_ROOT_DIR.'/'.LS_LOCAL_DIR.LS_CONF_DIR.'/LSauth', '/^config\.(.+)\.php$$/');
} }
// Sort resulting strings // Sort resulting strings
@ -909,12 +839,82 @@ function cli_generate_lang_file($command_args) {
/* /*
* Handle output file format * Handle output file format
*/ */
function output_php($fd) {
global $LSlang_cli_logger, $additionalfileformat, $data, $copyoriginalvalue, $keep_unused, $translations;
fwrite($fd, "<?php\n\n");
if (!$additionalfileformat) fwrite($fd, "\$GLOBALS['LSlang'] = array (\n");
foreach($data as $key => $key_data) {
if ($copyoriginalvalue && $key_data['translation'] == "") {
$val = $key;
}
else
$val = $key_data['translation'];
$key=str_replace('"','\\"',$key);
$val=str_replace('"','\\"',$val);
foreach ($key_data['contexts'] as $context)
fwrite($fd, "\n# $context");
if ($additionalfileformat) {
fwrite($fd, "\n\$GLOBALS['LSlang'][\"$key\"] = \"$val\";\n");
}
else {
fwrite($fd, "\n\"$key\" =>\n \"$val\",\n");
}
}
// Handle keep unused mode
if ($keep_unused) {
$unused_msgs = array();
foreach ($translations as $msg => $trans)
if (!array_key_exists($msg, $data))
$unused_msgs[$msg] = $trans;
if ($unused_msgs) {
fwrite($fd, "\n\n");
fwrite($fd, "######################################################################\n");
fwrite($fd, "# Unused translations keeped #\n");
fwrite($fd, "######################################################################\n");
foreach($unused_msgs as $key => $val) {
$key=str_replace('"','\\"',$key);
$val=str_replace('"','\\"',$val);
if ($additionalfileformat) {
fwrite($fd, "\n\$GLOBALS['LSlang'][\"$key\"] = \"$val\";\n");
}
else {
fwrite($fd, "\n\"$key\" =>\n \"$val\",\n");
}
}
}
}
if (!$additionalfileformat) fwrite($fd, "\n);\n");
}
function clean_for_pot_file($val) {
$val = str_replace('"', '\\"', $val);
return str_replace("\n", "\\n", $val);
}
function output_pot($fd) {
global $LSlang_cli_logger, $data, $copyoriginalvalue;
foreach($data as $key => $key_data) {
if ($copyoriginalvalue && $key_data['translation'] == "") {
$val = $key;
}
else
$val = $key_data['translation'];
foreach ($key_data['contexts'] as $context)
fwrite($fd, "#: $context\n");
$key = clean_for_pot_file($key);
$val = clean_for_pot_file($val);
fwrite($fd, "msgid \"$key\"\nmsgstr \"$val\"\n\n");
}
}
// Determine where to write result // Determine where to write result
if ($output) { if ($output) {
$output = _cli_relative2absolute_path($output); $output = relative2absolute_path($output);
$LSlang_cli_logger -> info("Write result in output file ($output)"); $LSlang_cli_logger -> info("Write result in output file ($output)");
$fd = null;
try { try {
$LSlang_cli_logger -> debug("Open output file ($output)"); $LSlang_cli_logger -> debug("Open output file ($output)");
$fd = fopen($output, 'w'); $fd = fopen($output, 'w');
@ -935,11 +935,11 @@ function cli_generate_lang_file($command_args) {
$LSlang_cli_logger -> debug("Output format : $format"); $LSlang_cli_logger -> debug("Output format : $format");
switch($format) { switch($format) {
case 'pot': case 'pot':
_cli_output_pot($fd); output_pot($fd);
break; break;
case 'php': case 'php':
default: default:
_cli_output_php($fd); output_php($fd);
break; break;
} }

View file

@ -459,7 +459,7 @@ class LSldap extends LSlog_staticLoggerClass {
} }
} }
else { else {
if (!is_empty($attrVal)) { if (!is_empty($val)) {
$drop = false; $drop = false;
$changed_attrs[$attrName][]=$attrVal; $changed_attrs[$attrName][]=$attrVal;
} }

View file

@ -158,7 +158,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
public function getDisplayName($spe=null, $full=false) { public function getDisplayName($spe=null, $full=false) {
if (is_null($spe)) if (is_null($spe))
$spe = $this -> getDisplayNameFormat(); $spe = $this -> getDisplayNameFormat();
$val = $this -> getDisplayFData($spe); $val = $this -> getFData($spe, $this -> attrs, 'getDisplayValue');
if (LSsession :: haveSubDn() && $full) { if (LSsession :: haveSubDn() && $full) {
$val.=' ('.$this -> subDnName.')'; $val.=' ('.$this -> subDnName.')';
} }
@ -216,13 +216,11 @@ class LSldapObject extends LSlog_staticLoggerClass {
$LSform = new LSform($this, $idForm, null, $api_mode); $LSform = new LSform($this, $idForm, null, $api_mode);
$this -> forms[$idForm] = array($LSform, $load); $this -> forms[$idForm] = array($LSform, $load);
$loadObject = null;
if ($load) { if ($load) {
$type = $this -> getType(); $type = $this -> getType();
$loadObject = new $type(); $loadObject = new $type();
if (!$loadObject -> loadData($load)) { if (!$loadObject -> loadData($load)) {
$load = false; $load=false;
$loadObject = null;
} }
} }
@ -763,19 +761,18 @@ class LSldapObject extends LSlog_staticLoggerClass {
* - [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;
$first = true; $first=true;
$basedn = ""; for($i=1;$i<$infos['count'];$i++)
for($i=1; $i<$infos['count']; $i++)
if($first) { if($first) {
$basedn .= $infos[$i]; $basedn.=$infos[$i];
$first = false; $first=false;
} }
else else
$basedn .= ','.$infos[$i]; $basedn.=','.$infos[$i];
return array($infos[0], $basedn); return array($infos[0],$basedn);
} }
/** /**
@ -2332,7 +2329,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
} }
if ($confirm) { if ($confirm) {
$obj -> _cli_show(); $obj -> _cli_show($raw_values);
// Sure ? // Sure ?
if (!LScli :: confirm("\nAre you sure you want to delete this object?")) if (!LScli :: confirm("\nAre you sure you want to delete this object?"))
return True; return True;
@ -2452,7 +2449,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* @retval boolean True on success, false otherwise * @retval boolean True on success, false otherwise
**/ **/
public static function cli_create($command_args) { public static function cli_create($command_args) {
$objType = $obj = null; $objType = null;
$delimiter = "|"; $delimiter = "|";
$confirm = true; $confirm = true;
$just_try = false; $just_try = false;
@ -2487,7 +2484,6 @@ class LSldapObject extends LSlog_staticLoggerClass {
} }
} }
// @phpstan-ignore-next-line
if (is_null($objType) || empty($attrs_values)) if (is_null($objType) || empty($attrs_values))
LScli :: usage('You must provide LSobject type, DN and at least one change.'); LScli :: usage('You must provide LSobject type, DN and at least one change.');
@ -2616,7 +2612,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* @retval boolean True on success, false otherwise * @retval boolean True on success, false otherwise
**/ **/
public static function cli_modify($command_args) { public static function cli_modify($command_args) {
$objType = $obj = null; $objType = null;
$dn = null; $dn = null;
$delimiter = "|"; $delimiter = "|";
$confirm = true; $confirm = true;
@ -2655,7 +2651,6 @@ class LSldapObject extends LSlog_staticLoggerClass {
} }
} }
// @phpstan-ignore-next-line
if (is_null($objType) || is_null($dn) || empty($changes)) if (is_null($objType) || is_null($dn) || empty($changes))
LScli :: usage('You must provide LSobject type, DN and at least one change.'); LScli :: usage('You must provide LSobject type, DN and at least one change.');

View file

@ -43,7 +43,7 @@ class LSlog_console extends LSlog_handler {
$this -> stdout = fopen('php://stdout', 'w'); $this -> stdout = fopen('php://stdout', 'w');
$this -> stderr = fopen('php://stderr', 'w'); $this -> stderr = fopen('php://stderr', 'w');
if ($this -> enabled) if ($this -> enabled)
self :: log_trace("$this Enabled"); self :: log_trace("$this Enabled", get_class($this));
} }
/** /**

View file

@ -44,7 +44,7 @@ class LSlog_email extends LSlog_handler {
parent :: __construct($config); parent :: __construct($config);
$this -> recipient = self :: getConfig('recipient'); $this -> recipient = self :: getConfig('recipient');
if ($this -> enabled) if ($this -> enabled)
self :: log_trace("$this Enabled"); self :: log_trace("$this Enabled", get_class($this));
} }
/** /**

View file

@ -44,7 +44,7 @@ class LSlog_file extends LSlog_handler {
if (substr($this -> path, 0, 1) != '/') if (substr($this -> path, 0, 1) != '/')
$this -> path = LS_ROOT_DIR."/".$this -> path; $this -> path = LS_ROOT_DIR."/".$this -> path;
if ($this -> enabled) if ($this -> enabled)
self :: log_trace("$this Enabled"); self :: log_trace("$this Enabled", get_class($this));
} }
/** /**

View file

@ -237,7 +237,7 @@ class LSlog_handler extends LSlog_staticLoggerClass {
if (isset(LSsession :: $ldapServer['name'])) if (isset(LSsession :: $ldapServer['name']))
return LSsession :: $ldapServer['name']; return LSsession :: $ldapServer['name'];
else else
return "#".LSsession :: get('ldap_server_id'); return "#".LSsession :: $ldapServerId;
} }
return "Not connected"; return "Not connected";
} }

View file

@ -60,7 +60,7 @@ class LSlog_syslog extends LSlog_handler {
parent :: __construct($config); parent :: __construct($config);
$this -> priority = static :: getConfig('priority'); $this -> priority = static :: getConfig('priority');
if ($this -> enabled) if ($this -> enabled)
self :: log_trace("$this Enabled"); self :: log_trace("$this Enabled", get_class($this));
} }
/** /**

View file

@ -40,7 +40,7 @@ class LSlog_system extends LSlog_handler {
public function __construct($config) { public function __construct($config) {
parent :: __construct($config); parent :: __construct($config);
if ($this -> enabled) if ($this -> enabled)
self :: log_trace("$this Enabled"); self :: log_trace("$this Enabled", get_class($this));
} }
/** /**

View file

@ -37,28 +37,28 @@ class LSmail {
} }
public static function ajax_display(&$data) { public static function ajax_display(&$data) {
$msg = $_REQUEST['msg']; if (isset($_REQUEST['object']['type']) && isset($_REQUEST['object']['dn'])) {
$subject = $_REQUEST['subject']; if (LSsession ::loadLSobject($_REQUEST['object']['type'])) {
if ( $obj = new $_REQUEST['object']['type']();
isset($_REQUEST['object']['type']) $obj -> loadData($_REQUEST['object']['dn']);
&& isset($_REQUEST['object']['dn']) $msg = $obj -> getFData($_REQUEST['msg']);
&& LSsession ::loadLSobject($_REQUEST['object']['type']) $subject = $obj -> getFData($_REQUEST['subject']);
) { }
$obj = new $_REQUEST['object']['type'](); }
$obj -> loadData($_REQUEST['object']['dn']); else {
$msg = $obj -> getFData($msg); $msg = $_REQUEST['msg'];
$subject = $obj -> getFData($subject); $subject = $_REQUEST['subject'];
} }
LStemplate :: assign('LSmail_msg', $msg); LStemplate :: assign('LSmail_msg',$msg);
LStemplate :: assign('LSmail_subject', $subject); LStemplate :: assign('LSmail_subject',$subject);
LStemplate :: assign('LSmail_options', $_REQUEST['options']); LStemplate :: assign('LSmail_options',$_REQUEST['options']);
if (is_array($_REQUEST['mails'])) { if (is_array($_REQUEST['mails'])) {
LStemplate :: assign('LSmail_mails', $_REQUEST['mails']); LStemplate :: assign('LSmail_mails',$_REQUEST['mails']);
} }
else if(empty($_REQUEST['mails'])) { else if(empty($_REQUEST['mails'])) {
LStemplate :: assign('LSmail_mails', array($_REQUEST['mails'])); LStemplate :: assign('LSmail_mails',array($_REQUEST['mails']));
} }
$data = array( $data = array(

View file

@ -135,7 +135,7 @@ class LSsearch extends LSlog_staticLoggerClass {
foreach($this -> config['predefinedFilters'] as $filter => $label) { foreach($this -> config['predefinedFilters'] as $filter => $label) {
if(!LSldap::isValidFilter($filter)) { if(!LSldap::isValidFilter($filter)) {
LSerror::addErrorCode('LSsearch_15',array('label' => $label, 'filter' => $filter, 'type' => $this -> LSobject)); LSerror::addErrorCode('LSsearch_15',array('label' => $label, 'filter' => $filter, 'type' => $this -> LSobject));
unset($this -> config['predefinedFilters'][$filter]); unset($this -> config['predefinedFilters'][$key]);
} }
} }
} }
@ -719,7 +719,7 @@ class LSsearch extends LSlog_staticLoggerClass {
return; return;
} }
} }
if($filters) { if(!empty($filters)) {
$filter=LSldap::combineFilters('or',$filters); $filter=LSldap::combineFilters('or',$filters);
if ($filter) { if ($filter) {
return $filter; return $filter;
@ -1049,7 +1049,7 @@ class LSsearch extends LSlog_staticLoggerClass {
} }
if (!$searchParams) if (!$searchParams)
return false; return false;
if ($searchParams['filter'] instanceof Net_LDAP2_Filter) { if ($searchParams['filter'] instanceof Net_LDAP_Filter) {
$searchParams['filter'] = $searchParams['filter'] -> asString(); $searchParams['filter'] = $searchParams['filter'] -> asString();
} }
$to_hash = print_r($searchParams, true); $to_hash = print_r($searchParams, true);

View file

@ -42,19 +42,16 @@ class LSsearchEntry extends LSlog_staticLoggerClass {
private $params = array(); private $params = array();
// The attributes list // The attributes list
private $attrs_list = array(); private $attrs_list=array();
// The attributes values // The attributes values
private $attrs = array(); private $attrs=array();
// The index of the entry in the result of the search
private $id = null;
// Cache // Cache
private $cache = array(); private $cache=array();
// Other values // Other values
private $other_values = array(); private $other_values=array();
/** /**
* Constructor * Constructor

View file

@ -140,8 +140,6 @@ class LSsession {
return self :: getEmailSender(); return self :: getEmailSender();
case 'api_mode': case 'api_mode':
return boolval(self :: $api_mode); return boolval(self :: $api_mode);
case 'ldap_server_id':
return boolval(self :: $ldapServerId);
} }
return null; return null;
} }
@ -373,7 +371,7 @@ class LSsession {
'libs_dir' => LS_ROOT_DIR. '/'. LS_LIB_DIR, 'libs_dir' => LS_ROOT_DIR. '/'. LS_LIB_DIR,
'compile_dir' => LS_TMP_DIR_PATH, 'compile_dir' => LS_TMP_DIR_PATH,
'debug' => LSdebug, 'debug' => LSdebug,
'debug_smarty' => isset($_REQUEST['LStemplate_debug']), 'debug_smarty' => (isset($_REQUEST) && isset($_REQUEST['LStemplate_debug'])),
) )
)) ))
return False; return False;
@ -865,7 +863,7 @@ class LSsession {
if (self :: $ldapServerId) { if (self :: $ldapServerId) {
LStemplate :: assign('ldapServerId',self :: $ldapServerId); LStemplate :: assign('ldapServerId',self :: $ldapServerId);
} }
if (isset($recoveryPasswordInfos)) { if (isset($_GET['LSsession_recoverPassword'])) {
self :: displayRecoverPasswordForm($recoveryPasswordInfos); self :: displayRecoverPasswordForm($recoveryPasswordInfos);
} }
elseif(LSauth :: displayLoginForm()) { elseif(LSauth :: displayLoginForm()) {
@ -1838,7 +1836,7 @@ class LSsession {
} }
if (LSerror :: errorsDefined()) { if (LSerror :: errorsDefined()) {
$data['errors'] = LSerror :: getErrors(); $data['errors'] = LSerror :: getErrors(self :: $api_mode);
} }
if (!self :: $api_mode && LSdebugDefined()) { if (!self :: $api_mode && LSdebugDefined()) {
@ -2416,7 +2414,7 @@ class LSsession {
* @param string $authorized The authorized maximum right * @param string $authorized The authorized maximum right
* @return boolean * @return boolean
*/ */
public static function checkRight($requested, $authorized) { public function checkRight($requested, $authorized) {
if ($requested == $authorized) if ($requested == $authorized)
return true; return true;
if ($requested == 'r' && $authorized == 'w') if ($requested == 'r' && $authorized == 'w')
@ -3163,7 +3161,7 @@ class LSsession {
'LSsession_21', 'LSsession_21',
array( array(
'func' => $func -> getName(), 'func' => $func -> getName(),
'addon' => $LSaddon, 'addon' => $addon,
'view' => $viewId, 'view' => $viewId,
) )
); );
@ -3174,7 +3172,7 @@ class LSsession {
'LSsession_23', 'LSsession_23',
array( array(
'func' => $viewFunction, 'func' => $viewFunction,
'addon' => $LSaddon, 'addon' => $addon,
'view' => $viewId, 'view' => $viewId,
) )
); );

View file

@ -652,15 +652,18 @@ class LStemplate extends LSlog_staticLoggerClass {
} }
function LStemplate_smarty_getFData($params) { function LStemplate_smarty_getFData($params) {
echo getFData($params['format'], $params['data'], $meth=NULL); extract($params);
echo getFData($format,$data,$meth=NULL);
} }
function LStemplate_smarty_tr($params) { function LStemplate_smarty_tr($params) {
echo __($params['msg']); extract($params);
echo __($msg);
} }
function LStemplate_smarty_img($params) { function LStemplate_smarty_img($params) {
echo "image/".$params['name']; extract($params);
echo "image/$name";
} }
function LStemplate_smarty_css($params) { function LStemplate_smarty_css($params) {

View file

@ -131,7 +131,7 @@ class LSurl extends LSlog_staticLoggerClass {
// Reset last redirect // Reset last redirect
if (isset($_SESSION['last_redirect'])) if (isset($_SESSION['last_redirect']))
unset($_SESSION['last_redirect']); unset($_SESSION['last_redirect']);
self :: log_debug("URL : result :\n".varDump($request)); self :: log_debug("URL : result :\n".varDump($request, 1));
return $request; return $request;
} }
} }

View file

@ -24,7 +24,7 @@
ini_set( 'magic_quotes_gpc', 'off' ); ini_set( 'magic_quotes_gpc', 'off' );
ini_set( 'magic_quotes_sybase', 'off' ); ini_set( 'magic_quotes_sybase', 'off' );
ini_set( 'magic_quotes_runtime', 'off' ); ini_set( 'magic_quotes_runtime', 'off' );
if (isset($_REQUEST['LSdebug']) || (isset($_SERVER['HTTP_HOST']) && preg_match('/^127\.[0-9]+\.[0-9]+\.[0-9]+$/', $_SERVER['HTTP_HOST']))) if ((isset($_REQUEST) && isset($_REQUEST['LSdebug'])) || (isset($_SERVER['HTTP_HOST']) && preg_match('/^127\.[0-9]+\.[0-9]+\.[0-9]+$/', $_SERVER['HTTP_HOST'])))
error_reporting(E_ALL); error_reporting(E_ALL);
else else
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED); error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);

View file

@ -788,7 +788,7 @@ function dateTime2LdapDate($datetime, $timezone=null, $format=null) {
$datetime -> setTimezone(timezone_open(is_null($timezone)?'UTC':$timezone)); $datetime -> setTimezone(timezone_open(is_null($timezone)?'UTC':$timezone));
} }
if (is_null($format)) if (is_null($format))
$format = ($timezone == 'naive'?'YmdHis':'YmdHisO'); $format = ($naive?'YmdHis':'YmdHisO');
$datetime_string = $datetime -> format($format); $datetime_string = $datetime -> format($format);
// Replace +0000 or -0000 end by Z // Replace +0000 or -0000 end by Z

View file

@ -262,8 +262,6 @@ LSurl :: add_handler('#^global_search\.php#', 'handle_old_global_search_php', fa
* @retval void * @retval void
**/ **/
function handle_static_file($request) { function handle_static_file($request) {
$path = null;
$mime_type = null;
switch ($request -> type) { switch ($request -> type) {
case 'image': case 'image':
$path = LStemplate :: getImagePath($request -> file); $path = LStemplate :: getImagePath($request -> file);
@ -278,7 +276,7 @@ function handle_static_file($request) {
$mime_type = 'text/javascript'; $mime_type = 'text/javascript';
break; break;
} }
if ($path && is_file($path)) { if ($path && is_file($path)) {
dumpFile($path, $mime_type); dumpFile($path, $mime_type);
} }
LSurl :: error_404($request); LSurl :: error_404($request);
@ -1777,7 +1775,7 @@ function handle_api_LSobject_import($request) {
$data['updateIfExists'], $data['updateIfExists'],
$data['justTry'] $data['justTry']
); );
LSlog :: debug("LSio::importFromPostData(): result = ".varDump($data)); LSlog :: debug("LSio::importFromPostData(): result = ".varDump($result));
} }
LSsession :: displayAjaxReturn($data); LSsession :: displayAjaxReturn($data);
@ -1948,7 +1946,7 @@ function handle_api_LSobject_remove($request) {
$data['success'] = true; $data['success'] = true;
} }
else { else {
LSerror :: addErrorCode('LSldapObject_15', $data['name']); LSerror :: addErrorCode('LSldapObject_15', $objectname);
} }
LSsession :: displayAjaxReturn($data); LSsession :: displayAjaxReturn($data);
} }
@ -1974,7 +1972,7 @@ function handle_api_LSobject_relation($request) {
// Handle relation URL parameter // Handle relation URL parameter
$relationName = $request -> relation; $relationName = $request -> relation;
if (!is_array($object -> getConfig("LSrelation.$relationName"))) { if (!is_array($object -> getConfig("LSrelation.$relationName"))) {
LSlog :: error("LSobject $LSobject have no relation '$relationName'."); LSlog :: log_error("LSobject $LSobject have no relation '$relationName'.");
LSsession :: displayAjaxReturn(); LSsession :: displayAjaxReturn();
return false; return false;
} }