Clean errors detected by PHPstan (level 1)

This commit is contained in:
Benjamin Renard 2022-12-31 04:09:56 +01:00
parent 38fa02619d
commit e71823b644
29 changed files with 107 additions and 93 deletions

View file

@ -1,5 +1,5 @@
parameters:
level: 0
level: 1
paths:
- src
excludePaths:
@ -7,10 +7,20 @@ parameters:
- 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 (Net_LDAP2_Filter|Net_LDAP2_Entry|PEAR_Error) not found\\.#"
- "#(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\\.#"

View file

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

View file

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

View file

@ -201,6 +201,7 @@ function ppolicy_extraDisplayColumn_password_expiration($entry) {
* @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) {
$csv = null;
if ($as_csv) {
$csv = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');
@ -224,6 +225,7 @@ function ppolicy_export_search_info($LSsearch, $as_csv=true, $return=false) {
return false;
}
$data = array();
if ($as_csv) {
$headers = array($LSsearch->label_objectName, 'DN');
foreach($attrs as $attr) {
@ -236,9 +238,6 @@ function ppolicy_export_search_info($LSsearch, $as_csv=true, $return=false) {
return false;
}
}
else {
$data = array();
}
foreach ($LSsearch -> getSearchEntries() as $e) {
$row = array(
@ -250,7 +249,7 @@ function ppolicy_export_search_info($LSsearch, $as_csv=true, $return=false) {
if ($as_csv) {
$values = ensureIsArray($e -> get($attr));
if ($values) {
$row[] = ($as_json?$values:implode('|', $values));
$row[] = implode('|', $values);
}
else {
$no_value_label = LSconfig::get(

View file

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

View file

@ -146,6 +146,7 @@ class LSattr_ldap_password extends LSattr_ldap {
break;
case 'sha256':
case 'sha512':
$mhash_type = null;
switch($encode) {
case 'sha256':
$mhash_type = MHASH_SHA256;
@ -163,6 +164,7 @@ class LSattr_ldap_password extends LSattr_ldap {
case 'ssha':
case 'ssha256':
case 'ssha512':
$mhash_type = null;
switch($encode) {
case 'ssha':
$mhash_type = MHASH_SHA1;
@ -263,12 +265,10 @@ class LSattr_ldap_password extends LSattr_ldap {
return (strcasecmp(call_user_func_array($encodeFunction, array(&$this -> attribute -> ldapObject, $clearPassword)), $hashedPassword) == 0);
// Extract cipher
$hashedPasswordData = $cypher = null;
if (preg_match('/{([^}]+)}(.*)/',$hashedPassword,$matches)) {
$hashedPasswordData = $matches[2];
$cypher = strtolower($matches[1]);
} else {
$cypher = null;
}
// 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']));
}
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;
}
}

View file

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

View file

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

View file

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

View file

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

View file

@ -166,6 +166,7 @@ class LSformRule extends LSlog_staticLoggerClass {
$rule_name = null;
$rule_class = null;
$rule_name_arg_num = null;
$rule_name_quote_char = null;
$params = array();
for ($i=0; $i < count($command_args); $i++) {
switch ($command_args[$i]) {

View file

@ -20,14 +20,6 @@
******************************************************************************/
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
*
@ -55,7 +47,13 @@ class LSformRule_zxcvbn extends LSformRule {
* @return boolean True if value is valid, False otherwise
*/
public static function validate($value, $options, &$formElement) {
$zxcvbn = new Zxcvbn();
LSsession :: includeFile(
LSconfig :: get(
'params.zxcvbn_autoload_path', 'Zxcvbn/autoload.php',
'string', $options
), true
);
$zxcvbn = new ZxcvbnPhp\Zxcvbn();
$userData = array();
$userDataAttrs = LSconfig :: get('params.userDataAttrs', array(), 'array', $options);
if ($userDataAttrs) {

View file

@ -470,7 +470,7 @@ function _cli_parse_php_file($file) {
$i++;
}
}
elseif (!empty($quote)) {
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
@ -644,7 +644,7 @@ function cli_generate_lang_file($command_args) {
$only = strtolower($command_args[$i]);
if (!in_array($only, $available_onlys))
LScli :: usage("Invalid -O/--only parameter. Must be one of the following values : '".implode("','", $available_onlys)."'.");
elseif ($without)
elseif ($withouts)
LScli :: usage("You could not use only -O/--only parameter combined with -W/--without parameter.");
break;
@ -914,6 +914,7 @@ function cli_generate_lang_file($command_args) {
if ($output) {
$output = _cli_relative2absolute_path($output);
$LSlang_cli_logger -> info("Write result in output file ($output)");
$fd = null;
try {
$LSlang_cli_logger -> debug("Open output file ($output)");
$fd = fopen($output, 'w');

View file

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

View file

@ -158,7 +158,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
public function getDisplayName($spe=null, $full=false) {
if (is_null($spe))
$spe = $this -> getDisplayNameFormat();
$val = $this -> getFData($spe, $this -> attrs, 'getDisplayValue');
$val = $this -> getDisplayFData($spe);
if (LSsession :: haveSubDn() && $full) {
$val.=' ('.$this -> subDnName.')';
}
@ -216,11 +216,13 @@ class LSldapObject extends LSlog_staticLoggerClass {
$LSform = new LSform($this, $idForm, null, $api_mode);
$this -> forms[$idForm] = array($LSform, $load);
$loadObject = null;
if ($load) {
$type = $this -> getType();
$loadObject = new $type();
if (!$loadObject -> loadData($load)) {
$load = false;
$loadObject = null;
}
}
@ -765,6 +767,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
if(!$infos)
return;
$first = true;
$basedn = "";
for($i=1; $i<$infos['count']; $i++)
if($first) {
$basedn .= $infos[$i];
@ -2449,7 +2452,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* @retval boolean True on success, false otherwise
**/
public static function cli_create($command_args) {
$objType = null;
$objType = $obj = null;
$delimiter = "|";
$confirm = true;
$just_try = false;
@ -2484,6 +2487,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
}
}
// @phpstan-ignore-next-line
if (is_null($objType) || empty($attrs_values))
LScli :: usage('You must provide LSobject type, DN and at least one change.');
@ -2612,7 +2616,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
* @retval boolean True on success, false otherwise
**/
public static function cli_modify($command_args) {
$objType = null;
$objType = $obj = null;
$dn = null;
$delimiter = "|";
$confirm = true;
@ -2651,6 +2655,7 @@ class LSldapObject extends LSlog_staticLoggerClass {
}
}
// @phpstan-ignore-next-line
if (is_null($objType) || is_null($dn) || empty($changes))
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 -> stderr = fopen('php://stderr', 'w');
if ($this -> enabled)
self :: log_trace("$this Enabled", get_class($this));
self :: log_trace("$this Enabled");
}
/**

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -719,7 +719,7 @@ class LSsearch extends LSlog_staticLoggerClass {
return;
}
}
if(!empty($filters)) {
if($filters) {
$filter=LSldap::combineFilters('or',$filters);
if ($filter) {
return $filter;

View file

@ -47,6 +47,9 @@ class LSsearchEntry extends LSlog_staticLoggerClass {
// The attributes values
private $attrs = array();
// The index of the entry in the result of the search
private $id = null;
// Cache
private $cache = array();

View file

@ -373,7 +373,7 @@ class LSsession {
'libs_dir' => LS_ROOT_DIR. '/'. LS_LIB_DIR,
'compile_dir' => LS_TMP_DIR_PATH,
'debug' => LSdebug,
'debug_smarty' => (isset($_REQUEST) && isset($_REQUEST['LStemplate_debug'])),
'debug_smarty' => isset($_REQUEST['LStemplate_debug']),
)
))
return False;
@ -865,7 +865,7 @@ class LSsession {
if (self :: $ldapServerId) {
LStemplate :: assign('ldapServerId',self :: $ldapServerId);
}
if (isset($_GET['LSsession_recoverPassword'])) {
if (isset($recoveryPasswordInfos)) {
self :: displayRecoverPasswordForm($recoveryPasswordInfos);
}
elseif(LSauth :: displayLoginForm()) {
@ -1838,7 +1838,7 @@ class LSsession {
}
if (LSerror :: errorsDefined()) {
$data['errors'] = LSerror :: getErrors(self :: $api_mode);
$data['errors'] = LSerror :: getErrors();
}
if (!self :: $api_mode && LSdebugDefined()) {

View file

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

View file

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

View file

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

View file

@ -262,6 +262,8 @@ LSurl :: add_handler('#^global_search\.php#', 'handle_old_global_search_php', fa
* @retval void
**/
function handle_static_file($request) {
$path = null;
$mime_type = null;
switch ($request -> type) {
case 'image':
$path = LStemplate :: getImagePath($request -> file);