From b06823a811efc054c92aa5ec3446588d1732e814 Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 10:13:28 +0100 Subject: [PATCH 01/36] PHPdoc $user argument to fetch is nullable --- htdocs/contact/class/contact.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index 080cc4d5f95..ac7c96194cb 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -975,7 +975,7 @@ class Contact extends CommonObject * Load object contact. * * @param int $id Id of contact - * @param User $user Load also alerts of this user (subscribing to alerts) that want alerts about this contact + * @param ?User $user Load also alerts of this user (subscribing to alerts) that want alerts about this contact * @param string $ref_ext External reference, not given by Dolibarr * @param string $email Email * @param int $loadalsoroles Load also roles. Try to always 0 here and load roles with a separate call of fetchRoles(). From c76baf1e102263181ff74cda42399717757a5b64 Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 10:41:11 +0100 Subject: [PATCH 02/36] Fix typing, inits, ignore some phan's, fix caching reuse --- htdocs/core/lib/functions.lib.php | 54 ++++++++++++++++++------------- 1 file changed, 31 insertions(+), 23 deletions(-) diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 531818db4a4..b01c5eec55e 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -54,6 +54,7 @@ if (!function_exists('utf8_encode')) { * * @param mixed $elements PHP Object to json encode * @return string Json encoded string + * @phan-suppress PhanRedefineFunctionInternal */ function utf8_encode($elements) { @@ -67,6 +68,7 @@ if (!function_exists('utf8_decode')) { * * @param mixed $elements PHP Object to json encode * @return string Json encoded string + * @phan-suppress PhanRedefineFunctionInternal */ function utf8_decode($elements) { @@ -80,6 +82,7 @@ if (!function_exists('str_starts_with')) { * @param string $haystack haystack * @param string $needle needle * @return boolean + * @phan-suppress PhanRedefineFunctionInternal */ function str_starts_with($haystack, $needle) { @@ -93,6 +96,7 @@ if (!function_exists('str_ends_with')) { * @param string $haystack haystack * @param string $needle needle * @return boolean + * @phan-suppress PhanRedefineFunctionInternal */ function str_ends_with($haystack, $needle) { @@ -106,6 +110,7 @@ if (!function_exists('str_contains')) { * @param string $haystack haystack * @param string $needle needle * @return boolean + * @phan-suppress PhanRedefineFunctionInternal */ function str_contains($haystack, $needle) { @@ -456,7 +461,7 @@ function num2Alpha($n) * ) * * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable - * @return array Check function documentation + * @return array{browsername:string,browserversion:string,browseros:string,browserua:string,layout:string,phone:string,tablet:bool} Check function documentation */ function getBrowserInfo($user_agent) { @@ -12117,7 +12122,7 @@ function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $u * 'action', 'facture', 'project', 'project_task' or * 'myobject@mymodule' or * 'myobject_mysubobject' (where mymodule = myobject, like 'project_task') - * @return array array('module'=>, 'classpath'=>, 'element'=>, 'subelement'=>, 'classfile'=>, 'classname'=>, 'dir_output'=>) + * @return array{module:string,element:string,table_element:string,subelement:string,classpath:string,classfile:string,classname:string,dir_output:string} array('module'=>, 'classpath'=>, 'element'=>, 'subelement'=>, 'classfile'=>, 'classname'=>, 'dir_output'=>) * @see fetchObjectByElement(), getMultiDirOutput() */ function getElementProperties($elementType) @@ -12479,6 +12484,7 @@ function fetchObjectByElement($element_id, $element_type, $element_ref = '', $us if (class_exists($element_prop['classname'])) { $className = $element_prop['classname']; $objecttmp = new $className($db); + '@phan-var-force CommonObject $objecttmp'; if ($element_id > 0 || !empty($element_ref)) { $ret = $objecttmp->fetch($element_id, $element_ref); @@ -12869,7 +12875,7 @@ function forgeSQLFromUniversalSearchCriteria($filter, &$errorstr = '', $noand = * This is used to output the search criteria in an UFS (Universal Filter Syntax) input component. * * @param string $sqlfilters Universal SQL filter string. Must have been trimmed before. - * @return array Array of AND + * @return string[] Array of AND */ function dolForgeExplodeAnd($sqlfilters) { @@ -12995,7 +13001,7 @@ function dolCheckFilters($sqlfilters, &$error = '', &$parenthesislevel = 0) * Function to forge a SQL criteria from a Dolibarr filter syntax string. * This method is called by forgeSQLFromUniversalSearchCriteria() * - * @param array $matches Array of found string by regex search. Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.nature:is:NULL" + * @param string[] $matches Array of found string by regex search. Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.nature:is:NULL" * @return string Forged criteria. Example: "" or "()" */ function dolForgeDummyCriteriaCallback($matches) @@ -13016,7 +13022,7 @@ function dolForgeDummyCriteriaCallback($matches) * Function to forge a SQL criteria from a Dolibarr filter syntax string. * This method is called by forgeSQLFromUniversalSearchCriteria() * - * @param array $matches Array of found string by regex search. + * @param string[] $matches Array of found string by regex search. * Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.date_creation:<:'2016-01-01 12:30:00'" or "t.nature:is:NULL" * @return string Forged criteria. Example: "t.field LIKE 'abc%'" */ @@ -13097,7 +13103,7 @@ function dolForgeCriteriaCallback($matches) * Get timeline icon * * @param ActionComm $actionstatic actioncomm - * @param array $histo histo + * @param array $histo histo * @param int $key key * @return string String with timeline icon * @deprecated Use actioncomm->getPictoType() instead @@ -13164,7 +13170,7 @@ function getTimelineIcon($actionstatic, &$histo, $key) * getActionCommEcmList * * @param ActionComm $object Object ActionComm - * @return array Array of documents in index table + * @return array Array of documents in index table */ function getActionCommEcmList($object) { @@ -13191,23 +13197,22 @@ function getActionCommEcmList($object) } - /** - * Show html area with actions in messaging format. - * Note: Global parameter $param must be defined. + * Show html area with actions in messaging format. + * Note: Global parameter $param must be defined. * - * @param Conf $conf Object conf - * @param Translate $langs Object langs - * @param DoliDB $db Object db - * @param mixed $filterobj Filter on object Adherent|Societe|Project|Product|CommandeFournisseur|Dolresource|Ticket|... to list events linked to an object - * @param Contact|null $objcon Filter on object contact to filter events on a contact - * @param int $noprint Return string but does not output it - * @param string $actioncode Filter on actioncode - * @param string $donetodo Filter on event 'done' or 'todo' or ''=nofilter (all). - * @param array $filters Filter on other fields - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @return string|void Return html part or void if noprint is 1 + * @param Conf $conf Object conf + * @param Translate $langs Object langs + * @param DoliDB $db Object db + * @param ?CommonObject $filterobj Filter on object Adherent|Societe|Project|Product|CommandeFournisseur|Dolresource|Ticket|... to list events linked to an object + * @param ?Contact $objcon Filter on object contact to filter events on a contact + * @param int $noprint Return string but does not output it + * @param string $actioncode Filter on actioncode + * @param string $donetodo Filter on event 'done' or 'todo' or ''=nofilter (all). + * @param array $filters Filter on other fields + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @return string|void Return html part or void if noprint is 1 */ function show_actions_messaging($conf, $langs, $db, $filterobj, $objcon = null, $noprint = 0, $actioncode = '', $donetodo = 'done', $filters = array(), $sortfield = 'a.datep,a.id', $sortorder = 'DESC') { @@ -13237,6 +13242,9 @@ function show_actions_messaging($conf, $langs, $db, $filterobj, $objcon = null, } $sortfield_new = implode(',', $sortfield_new_list); + $sql = null; + $sql2 = null; + if (isModEnabled('agenda')) { // Search histo on actioncomm if (is_object($objcon) && $objcon->id > 0) { @@ -13433,7 +13441,6 @@ function show_actions_messaging($conf, $langs, $db, $filterobj, $objcon = null, while ($i < $imaxinloop) { $obj = $db->fetch_object($resql); - '@phan-var-force array{apicto:string,contact_id:string,dp:string,dp2:string,firstname:string,label:string,message:string,msg_from:string,ref:string,type:string,user_lastname:string} $obj'; if ($obj->type == 'action') { $contactaction = new ActionComm($db); $contactaction->id = $obj->id; @@ -13839,6 +13846,7 @@ function show_actions_messaging($conf, $langs, $db, $filterobj, $objcon = null, $conf->cache['contact'][$histo[$key]['contact_id']] = $contact; } else { $contact = $conf->cache['contact'][$histo[$key]['contact_id']]; + $result = ($contact instanceof Contact) ? $contact->id : 0; } if ($result > 0) { From e400e03cfa1f2c235d1955cd74e013e6d0b88a24 Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 11:07:23 +0100 Subject: [PATCH 03/36] Fix User arg from 0 to null --- htdocs/webservices/server_contact.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/webservices/server_contact.php b/htdocs/webservices/server_contact.php index 0089b625dfe..4e33e88521c 100644 --- a/htdocs/webservices/server_contact.php +++ b/htdocs/webservices/server_contact.php @@ -291,7 +291,7 @@ function getContact($authentication, $id, $ref_ext) $fuser->getrights(); $contact = new Contact($db); - $result = $contact->fetch($id, 0, $ref_ext); + $result = $contact->fetch($id, null, $ref_ext); if ($result > 0) { // Only internal user who have contact read permission // Or for external user who have contact read permission, with restrict on socid @@ -655,7 +655,7 @@ function updateContact($authentication, $contact) include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; $object = new Contact($db); - $result = $object->fetch($contact['id'], 0, $contact['ref_ext']); + $result = $object->fetch($contact['id'], null, $contact['ref_ext']); if (!empty($object->id)) { $objectfound = true; From 974ecf82fe2f037c5cfcbed27ce07b4d3c702b2e Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 11:09:40 +0100 Subject: [PATCH 04/36] Fix get_class on potential null --- htdocs/core/lib/functions.lib.php | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index b01c5eec55e..4e1a060151a 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -13280,11 +13280,8 @@ function show_actions_messaging($conf, $langs, $db, $filterobj, $objcon = null, $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id"; - if (get_class($filterobj) !== 'User') { - $force_filter_contact = false; - } else { - $force_filter_contact = true; - } + $force_filter_contact = $filterobj instanceof User; + if (is_object($objcon) && $objcon->id > 0) { $force_filter_contact = true; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm"; From ba702cf25f364d03f116177362dba783dc95d179 Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 13:03:46 +0100 Subject: [PATCH 05/36] PHPdoc for $css, $theme, $modules, $module_parts, $cache --- htdocs/core/class/conf.class.php | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php index ca1817e27a3..37677a086b0 100644 --- a/htdocs/core/class/conf.class.php +++ b/htdocs/core/class/conf.class.php @@ -4,6 +4,7 @@ * Copyright (C) 2004-2020 Laurent Destailleur * Copyright (C) 2005-2017 Regis Houssin * Copyright (C) 2006 Jean Heimburger + * Copyright (C) 2024 MDW * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -70,19 +71,32 @@ class Conf extends stdClass //! Used to store current currency (ISO code like 'USD', 'EUR', ...). To get the currency symbol: $langs->getCurrencySymbol($this->currency) public $currency; - //! Used to store current css (from theme) + /** + * @var string + */ public $theme; // Contains current theme ("eldy", "auguria", ...) + //! Used to store current css (from theme) + /** + * @var string + */ public $css; // Contains full path of css page ("/theme/eldy/style.css.php", ...) public $email_from; //! Used to store current menu handler public $standard_menu; - // List of activated modules + /** + * @var array List of activated modules + */ public $modules; + /** + * @var array> List of activated modules + */ public $modules_parts; - // An array to store cache results ->cache['nameofcache']=... + /** + * @var array An array to store cache results ->cache['nameofcache']=... + */ public $cache; /** From 7c660d33927aaa7532bed40df7e0b648b4de3123 Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 13:25:51 +0100 Subject: [PATCH 06/36] PHPdoc improvement: dol_print_error_email, price --- htdocs/core/lib/functions.lib.php | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 4e1a060151a..36f44d7a502 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -5696,11 +5696,11 @@ function dol_print_error($db = null, $error = '', $errors = null) /** * Show a public email and error code to contact if technical error * - * @param string $prefixcode Prefix of public error code - * @param string $errormessage Complete error message - * @param array $errormessages Array of error messages - * @param string $morecss More css - * @param string $email Email + * @param string $prefixcode Prefix of public error code + * @param string $errormessage Complete error message + * @param string[] $errormessages Array of error messages + * @param string $morecss More css + * @param string $email Email * @return void */ function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '') @@ -6270,7 +6270,7 @@ function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0, * * @param string|float $amount Amount value to format * @param int<0,1> $form Type of formatting: 1=HTML, 0=no formatting (no by default) - * @param Translate|string $outlangs Object langs for output. '' use default lang. 'none' use international separators. + * @param Translate|string|null $outlangs Object langs for output. '' use default lang. 'none' use international separators. * @param int $trunc 1=Truncate if there is more decimals than MAIN_MAX_DECIMALS_SHOWN (default), 0=Does not truncate. Deprecated because amount are rounded (to unit or total amount accuracy) before being inserted into database or after a computation, so this parameter should be useless. * @param int $rounding MINIMUM number of decimal to show: 0=no change, -1=we use min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT) * @param int|string $forcerounding MAXIMUM number of decimal to forcerounding decimal: -1=no change, 'MU' or 'MT' or a numeric to round to MU or MT or to a given number of decimal @@ -6303,7 +6303,7 @@ function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $ $thousand = ' '; // If $outlangs not forced, we use use language - if (!is_object($outlangs)) { + if (!($outlangs instanceof Translate)) { $outlangs = $langs; } @@ -6543,17 +6543,17 @@ function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) { - $dimension = $dimension * 1000000; + $dimension *= 1000000; $unit = $unit - 6; } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) { - $dimension = $dimension * 1000; - $unit = $unit - 3; + $dimension *= 1000; + $unit -= 3; } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) { - $dimension = $dimension / 1000000; - $unit = $unit + 6; + $dimension /= 1000000; + $unit += 6; } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) { - $dimension = $dimension / 1000; - $unit = $unit + 3; + $dimension /= 1000; + $unit += 3; } // Special case when we want output unit into pound or ounce /* TODO From cfe66e2f603f67341b56ae095af7d7ad31d6583c Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 17:44:12 +0100 Subject: [PATCH 07/36] Improve typing, init var, suppress notification --- htdocs/core/lib/functions.lib.php | 36 ++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 36f44d7a502..7b5bed8423f 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -688,8 +688,8 @@ function GETPOSTISARRAY($paramname, $method = 0) * 'restricthtml'=check html content is restricted to some tags only * 'custom'= custom filter specify $filter and $options) * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get) - * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails) - * @param mixed $options Options to pass to filter_var when $check is set to 'custom' + * @param ?int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails) + * @param mixed $options Options to pass to filter_var when $check is set to 'custom' * @param int $noreplace Force disable of replacement of __xxx__ strings. * @return string|array Value found (string or array), or '' if check fails */ @@ -718,6 +718,8 @@ function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null return 'BadThirdParameterForGETPOST'; } + $relativepathstring = ''; // For static analysis - looks possibly undefined if not set. + if (empty($method) || $method == 3 || $method == 4) { $relativepathstring = (empty($_SERVER["PHP_SELF"]) ? '' : $_SERVER["PHP_SELF"]); // Clean $relativepathstring @@ -759,6 +761,7 @@ function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) { // Search default value from $object->field global $object; + '@phan-var-force CommonObject $object'; // Suppose it's a CommonObject for analysis, but other objects have the $fields field as well if (is_object($object) && isset($object->fields[$paramname]['default'])) { $out = $object->fields[$paramname]['default']; } @@ -1191,6 +1194,7 @@ if (!function_exists('dol_getprefix')) { * * @param string $mode '' (prefix for session name) or 'email' (prefix for email id) * @return string A calculated prefix + * @phan-suppress PhanRedefineFunction - Also defined in webportal.main.inc.php */ function dol_getprefix($mode = '') { @@ -1967,13 +1971,14 @@ function dol_ucwords($string, $encoding = "UTF-8") * * @param string $message Line to log. ''=Show nothing * @param int $level Log level - * On Windows LOG_ERR=4, LOG_WARNING=5, LOG_NOTICE=LOG_INFO=6, LOG_DEBUG=6 si define_syslog_variables ou PHP 5.3+, 7 si dolibarr + * On Windows LOG_ERR=4, LOG_WARNING=5, LOG_NOTICE=LOG_INFO=6, LOG_DEBUG=6 if define_syslog_variables ou PHP 5.3+, 7 if dolibarr * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_NOTICE=5, LOG_INFO=6, LOG_DEBUG=7 * @param int $ident 1=Increase ident of 1 (after log), -1=Decrease ident of 1 (before log) * @param string $suffixinfilename When output is a file, append this suffix into default log filename. Example '_stripe', '_mail' * @param string $restricttologhandler Force output of log only to this log handler * @param array|null $logcontext If defined, an array with extra information (can be used by some log handlers) * @return void + * @phan-suppress PhanPluginUnknownArrayFunctionParamType $logcontext is not defined in detail */ function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null) { @@ -2194,7 +2199,7 @@ function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $di /** * Show tab header of a card * - * @param array $links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped. + * @param array,string>> $links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped. * @param string $active Active tab name (document', 'info', 'ldap', ....) * @param string $title Title * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no sepaaration under tab (to start a tab just after), -3=Add tab header but no footer separation @@ -2215,7 +2220,7 @@ function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0 /** * Show tabs of a record * - * @param array $links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped. + * @param array,string>> $links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped. * @param string $active Active tab name * @param string $title Title * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no separation under tab (to start a tab just after), -3=-2+'noborderbottom' @@ -2467,6 +2472,7 @@ function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldi $maxvisiblephotos = 1; $showimage = 1; $entity = (empty($object->entity) ? $conf->entity : $object->entity); + // @phan-suppress-next-line PhanUndeclaredMethod $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1); if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('barcode', 'lire_advance')) { $showbarcode = 0; @@ -2497,6 +2503,7 @@ function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldi if ($object->element == 'product') { /** @var Product $object */ + '@phan-var-force Product $object'; $width = 80; $cssclass = 'photowithmargin photoref'; $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]); @@ -2505,7 +2512,7 @@ function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldi $maxvisiblephotos = 1; } if ($showimage) { - $morehtmlleft .= '
'.$object->show_photos('product', $conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, 0, $width, 0, '').'
'; + $morehtmlleft .= '
'.$object->show_photos('product', $conf->product->multidir_output[$entity], 1, $maxvisiblephotos, 0, 0, 0, 0, $width, 0, '').'
'; } else { if (getDolGlobalString('PRODUCT_NODISPLAYIFNOPHOTO')) { $nophoto = ''; @@ -2517,6 +2524,7 @@ function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldi } } elseif ($object->element == 'category') { /** @var Categorie $object */ + '@phan-var-force Categorie $object'; $width = 80; $cssclass = 'photowithmargin photoref'; $showimage = $object->isAnyPhotoAvailable($conf->categorie->multidir_output[$entity]); @@ -2537,6 +2545,7 @@ function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldi } } elseif ($object->element == 'bom') { /** @var Bom $object */ + '@phan-var-force Bom $object'; $width = 80; $cssclass = 'photowithmargin photoref'; $showimage = $object->is_photo_available($conf->bom->multidir_output[$entity]); @@ -2559,6 +2568,7 @@ function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldi $width = 80; $cssclass = 'photoref'; /** @var Ticket $object */ + '@phan-var-force Ticket $object'; $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref); $maxvisiblephotos = getDolGlobalInt('TICKET_MAX_VISIBLE_PHOTO', 2); if ($conf->browser->layout == 'phone') { @@ -3218,7 +3228,7 @@ function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = * @param int $timestamp Timestamp * @param boolean $fast Fast mode. deprecated. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone. - * @return array Array of information + * @return array{seconds:int<0,59>,minutes:int<0,59>,hours:int<0,23>,mday:int<1,31>,wday:int<0,6>,mon:int<1,12>,year:int<0,9999>,yday:int<0,366>,0:int} Array of information * 'seconds' => $secs, * 'minutes' => $min, * 'hours' => $hour, @@ -7345,7 +7355,7 @@ function yn($yesno, $case = 1, $color = 0) * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future) * @param int $alpha 0=Keep number only to forge path, 1=Use alpha part after the - (By default, use 0). (deprecated, global option will be used in future) * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end - * @param Object $object Object to use to get ref to forge the path. + * @param ?CommonObject $object Object to use to get ref to forge the path. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object. * @return string Dir to use ending. Example '' or '1/' or '1/2/' * @see getMultiDirOuput() @@ -13103,7 +13113,7 @@ function dolForgeCriteriaCallback($matches) * Get timeline icon * * @param ActionComm $actionstatic actioncomm - * @param array $histo histo + * @param array $histo histo * @param int $key key * @return string String with timeline icon * @deprecated Use actioncomm->getPictoType() instead @@ -13603,20 +13613,20 @@ function show_actions_messaging($conf, $langs, $db, $filterobj, $objcon = null, if ($donetodo) { $tmp = ''; - if (get_class($filterobj) == 'Societe') { + if ($filterobj instanceof Societe) { $tmp .= ''; } - if (get_class($filterobj) == 'User') { + if ($filterobj instanceof User) { $tmp .= ''; } $tmp .= ($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : ''); $tmp .= ($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : ''); $tmp .= ($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : ''); //$out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort"); - if (get_class($filterobj) == 'Societe') { + if ($filterobj instanceof Societe) { $tmp .= ''; } - if (get_class($filterobj) == 'User') { + if ($filterobj instanceof User) { $tmp .= ''; } $out .= getTitleFieldOfList($tmp); From 3b80d100ff49cd0501b5b20e965159e90ae6fd77 Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 21:23:38 +0100 Subject: [PATCH 08/36] Cast return from DolEditor::Create(1) for static analysis --- htdocs/core/class/extrafields.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index 56fad852290..8e5befafd0a 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -1102,7 +1102,7 @@ class ExtraFields if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%'); - $out = $doleditor->Create(1); + $out = (string) $doleditor->Create(1); } else { $out = ''; } @@ -1110,7 +1110,7 @@ class ExtraFields if (!preg_match('/search_/', $keyprefix)) { // If keyprefix is search_ or search_options_, we must just use a simple text field require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, isModEnabled('fckeditor') && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%'); - $out = $doleditor->Create(1); + $out = (string) $doleditor->Create(1); } else { $out = ''; } From 41644c03f1ea6a28b51c8a9335d073b0e888f34f Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 21:35:31 +0100 Subject: [PATCH 09/36] Accept null for formquestion in formconfirm() --- htdocs/core/class/html.form.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index e7c86ed271a..edeec79facf 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -5224,7 +5224,7 @@ class Form * @param string $title Title * @param string $question Question * @param string $action Action - * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>'autofocus' or 'style=...')) + * @param array|string|null $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>'autofocus' or 'style=...')) * 'type' can be 'text', 'password', 'checkbox', 'radio', 'date', 'datetime', 'select', 'multiselect', 'morecss', * 'other', 'onecolumn' or 'hidden'... * @param int|string $selectedchoice '' or 'no', or 'yes' or '1', 1, '0' or 0 From 61bc1986f3161e94642d5b45c10039918e56bbe2 Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 21:46:27 +0100 Subject: [PATCH 10/36] Adjust sprintf to real type --- htdocs/core/datepicker.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/htdocs/core/datepicker.php b/htdocs/core/datepicker.php index 4c7c9a0ccc6..788289de2e3 100644 --- a/htdocs/core/datepicker.php +++ b/htdocs/core/datepicker.php @@ -3,6 +3,7 @@ * Copyright (C) 2005-2010 Laurent Destailleur * Copyright (C) 2005-2007 Regis Houssin * Copyright (C) 2014 Juanjo Menent + * Copyright (C) 2024 MDW * * This file is a modified version of datepicker.php from phpBSM to fix some * bugs, to add new features and to dramatically increase speed. @@ -267,7 +268,7 @@ function displayBox($selectedDate, $month, $year) echo "trans("FormatDateShortJavaInput")."')\""; - echo ">".sprintf("%02s", $mydate["mday"]).""; + echo ">".sprintf("%02d", $mydate["mday"]).""; $cols++; if (($mydate["wday"] + 1) % 7 == $startday) { @@ -298,7 +299,7 @@ function displayBox($selectedDate, $month, $year) if ($selDate) { $tempDate = dol_getdate($selDate); print $langs->trans("Month".$selectMonth)." "; - print sprintf("%02s", $tempDate["mday"]); + print sprintf("%02d", $tempDate["mday"]); print ", ".$selectYear; } else { print "Click a Date"; From 88c2d7e34e7a1981c12a897212f2980a798df060 Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 22:07:59 +0100 Subject: [PATCH 11/36] Add spelling for shippin --- dev/tools/codespell/codespell-dict.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/dev/tools/codespell/codespell-dict.txt b/dev/tools/codespell/codespell-dict.txt index ad8c0ecf617..1cd7ec6bfb2 100644 --- a/dev/tools/codespell/codespell-dict.txt +++ b/dev/tools/codespell/codespell-dict.txt @@ -21,6 +21,7 @@ thoose->those mot de passe->password not de passe->password nothtml->nohtml +shippin->shipping tableau de bord->state board tagret->target thridparty->thirdparty From a02b44923485172ec058eb0209789fc8edc11ec3 Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 22:08:37 +0100 Subject: [PATCH 12/36] Adapt to real typings --- htdocs/accountancy/bookkeeping/export.php | 30 ++++++++++++----------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/htdocs/accountancy/bookkeeping/export.php b/htdocs/accountancy/bookkeeping/export.php index 72aee30478d..c2206e9d3a9 100644 --- a/htdocs/accountancy/bookkeeping/export.php +++ b/htdocs/accountancy/bookkeeping/export.php @@ -6,6 +6,7 @@ * Copyright (C) 2016-2017 Laurent Destailleur * Copyright (C) 2018-2021 Frédéric France * Copyright (C) 2022 Progiseize + * Copyright (C) 2024 MDW * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -165,7 +166,7 @@ if (!in_array($action, array('export_file', 'delmouv', 'delmouvconfirm')) && !GE $query .= " where date_start < '".$db->idate(dol_now())."' and date_end > '".$db->idate(dol_now())."' limit 1"; $res = $db->query($query); - if ($res->num_rows > 0) { + if ($db->num_rows($res) > 0) { $fiscalYear = $db->fetch_object($res); $search_date_start = strtotime($fiscalYear->date_start); $search_date_end = strtotime($fiscalYear->date_end); @@ -321,17 +322,17 @@ if (empty($reshook)) { if (!empty($search_date_start)) { $filter['t.doc_date>='] = $search_date_start; $tmp = dol_getdate($search_date_start); - $param .= '&search_date_startmonth='.urlencode($tmp['mon']).'&search_date_startday='.urlencode($tmp['mday']).'&search_date_startyear='.urlencode($tmp['year']); + $param .= '&search_date_startmonth='.((int) $tmp['mon']).'&search_date_startday='.((int) $tmp['mday']).'&search_date_startyear='.((int) $tmp['year']); } if (!empty($search_date_end)) { $filter['t.doc_date<='] = $search_date_end; $tmp = dol_getdate($search_date_end); - $param .= '&search_date_endmonth='.urlencode($tmp['mon']).'&search_date_endday='.urlencode($tmp['mday']).'&search_date_endyear='.urlencode($tmp['year']); + $param .= '&search_date_endmonth='.((int) $tmp['mon']).'&search_date_endday='.((int) $tmp['mday']).'&search_date_endyear='.((int) $tmp['year']); } if (!empty($search_doc_date)) { $filter['t.doc_date'] = $search_doc_date; $tmp = dol_getdate($search_doc_date); - $param .= '&doc_datemonth='.urlencode($tmp['mon']).'&doc_dateday='.urlencode($tmp['mday']).'&doc_dateyear='.urlencode($tmp['year']); + $param .= '&doc_datemonth='.((int) $tmp['mon']).'&doc_dateday='.((int) $tmp['mday']).'&doc_dateyear='.((int) $tmp['year']); } if (!empty($search_doc_type)) { $filter['t.doc_type'] = $search_doc_type; @@ -400,42 +401,42 @@ if (empty($reshook)) { if (!empty($search_date_creation_start)) { $filter['t.date_creation>='] = $search_date_creation_start; $tmp = dol_getdate($search_date_creation_start); - $param .= '&search_date_creation_startmonth='.urlencode($tmp['mon']).'&search_date_creation_startday='.urlencode($tmp['mday']).'&search_date_creation_startyear='.urlencode($tmp['year']); + $param .= '&search_date_creation_startmonth='.((int) $tmp['mon']).'&search_date_creation_startday='.((int) $tmp['mday']).'&search_date_creation_startyear='.((int) $tmp['year']); } if (!empty($search_date_creation_end)) { $filter['t.date_creation<='] = $search_date_creation_end; $tmp = dol_getdate($search_date_creation_end); - $param .= '&search_date_creation_endmonth='.urlencode($tmp['mon']).'&search_date_creation_endday='.urlencode($tmp['mday']).'&search_date_creation_endyear='.urlencode($tmp['year']); + $param .= '&search_date_creation_endmonth='.((int) $tmp['mon']).'&search_date_creation_endday='.((int) $tmp['mday']).'&search_date_creation_endyear='.((int) $tmp['year']); } if (!empty($search_date_modification_start)) { $filter['t.tms>='] = $search_date_modification_start; $tmp = dol_getdate($search_date_modification_start); - $param .= '&search_date_modification_startmonth='.urlencode($tmp['mon']).'&search_date_modification_startday='.urlencode($tmp['mday']).'&search_date_modification_startyear='.urlencode($tmp['year']); + $param .= '&search_date_modification_startmonth='.((int) $tmp['mon']).'&search_date_modification_startday='.((int) $tmp['mday']).'&search_date_modification_startyear='.((int) $tmp['year']); } if (!empty($search_date_modification_end)) { $filter['t.tms<='] = $search_date_modification_end; $tmp = dol_getdate($search_date_modification_end); - $param .= '&search_date_modification_endmonth='.urlencode($tmp['mon']).'&search_date_modification_endday='.urlencode($tmp['mday']).'&search_date_modification_endyear='.urlencode($tmp['year']); + $param .= '&search_date_modification_endmonth='.((int) $tmp['mon']).'&search_date_modification_endday='.((int) $tmp['mday']).'&search_date_modification_endyear='.((int) $tmp['year']); } if (!empty($search_date_export_start)) { $filter['t.date_export>='] = $search_date_export_start; $tmp = dol_getdate($search_date_export_start); - $param .= '&search_date_export_startmonth='.urlencode($tmp['mon']).'&search_date_export_startday='.urlencode($tmp['mday']).'&search_date_export_startyear='.urlencode($tmp['year']); + $param .= '&search_date_export_startmonth='.((int) $tmp['mon']).'&search_date_export_startday='.((int) $tmp['mday']).'&search_date_export_startyear='.((int) $tmp['year']); } if (!empty($search_date_export_end)) { $filter['t.date_export<='] = $search_date_export_end; $tmp = dol_getdate($search_date_export_end); - $param .= '&search_date_export_endmonth='.urlencode($tmp['mon']).'&search_date_export_endday='.urlencode($tmp['mday']).'&search_date_export_endyear='.urlencode($tmp['year']); + $param .= '&search_date_export_endmonth='.((int) $tmp['mon']).'&search_date_export_endday='.((int) $tmp['mday']).'&search_date_export_endyear='.((int) $tmp['year']); } if (!empty($search_date_validation_start)) { $filter['t.date_validated>='] = $search_date_validation_start; $tmp = dol_getdate($search_date_validation_start); - $param .= '&search_date_validation_startmonth='.urlencode($tmp['mon']).'&search_date_validation_startday='.urlencode($tmp['mday']).'&search_date_validation_startyear='.urlencode($tmp['year']); + $param .= '&search_date_validation_startmonth='.((int) $tmp['mon']).'&search_date_validation_startday='.((int) $tmp['mday']).'&search_date_validation_startyear='.((int) $tmp['year']); } if (!empty($search_date_validation_end)) { $filter['t.date_validated<='] = $search_date_validation_end; $tmp = dol_getdate($search_date_validation_end); - $param .= '&search_date_validation_endmonth='.urlencode($tmp['mon']).'&search_date_validation_endday='.urlencode($tmp['mday']).'&search_date_validation_endyear='.urlencode($tmp['year']); + $param .= '&search_date_validation_endmonth='.((int) $tmp['mon']).'&search_date_validation_endday='.((int) $tmp['mday']).'&search_date_validation_endyear='.((int) $tmp['year']); } if (!empty($search_debit)) { $filter['t.debit'] = $search_debit; @@ -1263,6 +1264,7 @@ while ($i < min($num, $limit)) { // Document ref if (!empty($arrayfields['t.doc_ref']['checked'])) { $documentlink = ''; + $objectstatic = null; if ($line->doc_type == 'customer_invoice') { $langs->loadLangs(array('bills')); @@ -1273,7 +1275,7 @@ while ($i < min($num, $limit)) { if ($objectstatic->id > 0) { $filename = dol_sanitizeFileName($line->doc_ref); - $filedir = $conf->facture->dir_output.'/'.dol_sanitizeFileName($line->doc_ref); + $filedir = $conf->invoice->dir_output.'/'.dol_sanitizeFileName($line->doc_ref); $urlsource = $_SERVER['PHP_SELF'].'?id='.$objectstatic->id; $documentlink = $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); } @@ -1315,7 +1317,7 @@ while ($i < min($num, $limit)) { $labeltoshow = ''; $labeltoshowalt = ''; - if ($line->doc_type == 'customer_invoice' || $line->doc_type == 'supplier_invoice' || $line->doc_type == 'expense_report') { + if (($objectstatic instanceof CommonObject) && in_array($line->doc_type, array('customer_invoice', 'supplier_invoice', 'expense_report'))) { if ($objectstatic->id > 0) { $labeltoshow .= $objectstatic->getNomUrl(1, '', 0, 0, '', 0, -1, 1); $labeltoshow .= $documentlink; From 68209d83430aa1afbebe2b5662b12b587afcc8b5 Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 22:08:49 +0100 Subject: [PATCH 13/36] Adapt to real typings --- htdocs/accountancy/bookkeeping/list.php | 26 +++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php index a9931ab2ccb..cd2d8eec015 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -6,6 +6,7 @@ * Copyright (C) 2016-2017 Laurent Destailleur * Copyright (C) 2018-2021 Frédéric France * Copyright (C) 2022 Progiseize + * Copyright (C) 2024 MDW * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -160,7 +161,7 @@ if (!in_array($action, array('delmouv', 'delmouvconfirm')) && !GETPOSTISSET('beg $query .= " where date_start < '".$db->idate(dol_now())."' and date_end > '".$db->idate(dol_now())."' limit 1"; $res = $db->query($query); - if ($res->num_rows > 0) { + if ($db->num_rows($res) > 0) { $fiscalYear = $db->fetch_object($res); $search_date_start = strtotime($fiscalYear->date_start); $search_date_end = strtotime($fiscalYear->date_end); @@ -309,17 +310,17 @@ if (empty($reshook)) { if (!empty($search_date_start)) { $filter['t.doc_date>='] = $search_date_start; $tmp = dol_getdate($search_date_start); - $param .= '&search_date_startmonth='.urlencode($tmp['mon']).'&search_date_startday='.urlencode($tmp['mday']).'&search_date_startyear='.urlencode($tmp['year']); + $param .= '&search_date_startmonth='.((int) $tmp['mon']).'&search_date_startday='.((int) $tmp['mday']).'&search_date_startyear='.((int) $tmp['year']); } if (!empty($search_date_end)) { $filter['t.doc_date<='] = $search_date_end; $tmp = dol_getdate($search_date_end); - $param .= '&search_date_endmonth='.urlencode($tmp['mon']).'&search_date_endday='.urlencode($tmp['mday']).'&search_date_endyear='.urlencode($tmp['year']); + $param .= '&search_date_endmonth='.((int) $tmp['mon']).'&search_date_endday='.((int) $tmp['mday']).'&search_date_endyear='.((int) $tmp['year']); } if (!empty($search_doc_date)) { $filter['t.doc_date'] = $search_doc_date; $tmp = dol_getdate($search_doc_date); - $param .= '&doc_datemonth='.urlencode($tmp['mon']).'&doc_dateday='.urlencode($tmp['mday']).'&doc_dateyear='.urlencode($tmp['year']); + $param .= '&doc_datemonth='.((int) $tmp['mon']).'&doc_dateday='.((int) $tmp['mday']).'&doc_dateyear='.((int) $tmp['year']); } if (!empty($search_doc_type)) { $filter['t.doc_type'] = $search_doc_type; @@ -388,42 +389,42 @@ if (empty($reshook)) { if (!empty($search_date_creation_start)) { $filter['t.date_creation>='] = $search_date_creation_start; $tmp = dol_getdate($search_date_creation_start); - $param .= '&search_date_creation_startmonth='.urlencode($tmp['mon']).'&search_date_creation_startday='.urlencode($tmp['mday']).'&search_date_creation_startyear='.urlencode($tmp['year']); + $param .= '&search_date_creation_startmonth='.((int) $tmp['mon']).'&search_date_creation_startday='.((int) $tmp['mday']).'&search_date_creation_startyear='.((int) $tmp['year']); } if (!empty($search_date_creation_end)) { $filter['t.date_creation<='] = $search_date_creation_end; $tmp = dol_getdate($search_date_creation_end); - $param .= '&search_date_creation_endmonth='.urlencode($tmp['mon']).'&search_date_creation_endday='.urlencode($tmp['mday']).'&search_date_creation_endyear='.urlencode($tmp['year']); + $param .= '&search_date_creation_endmonth='.((int) $tmp['mon']).'&search_date_creation_endday='.((int) $tmp['mday']).'&search_date_creation_endyear='.((int) $tmp['year']); } if (!empty($search_date_modification_start)) { $filter['t.tms>='] = $search_date_modification_start; $tmp = dol_getdate($search_date_modification_start); - $param .= '&search_date_modification_startmonth='.urlencode($tmp['mon']).'&search_date_modification_startday='.urlencode($tmp['mday']).'&search_date_modification_startyear='.urlencode($tmp['year']); + $param .= '&search_date_modification_startmonth='.((int) $tmp['mon']).'&search_date_modification_startday='.((int) $tmp['mday']).'&search_date_modification_startyear='.((int) $tmp['year']); } if (!empty($search_date_modification_end)) { $filter['t.tms<='] = $search_date_modification_end; $tmp = dol_getdate($search_date_modification_end); - $param .= '&search_date_modification_endmonth='.urlencode($tmp['mon']).'&search_date_modification_endday='.urlencode($tmp['mday']).'&search_date_modification_endyear='.urlencode($tmp['year']); + $param .= '&search_date_modification_endmonth='.((int) $tmp['mon']).'&search_date_modification_endday='.((int) $tmp['mday']).'&search_date_modification_endyear='.((int) $tmp['year']); } if (!empty($search_date_export_start)) { $filter['t.date_export>='] = $search_date_export_start; $tmp = dol_getdate($search_date_export_start); - $param .= '&search_date_export_startmonth='.urlencode($tmp['mon']).'&search_date_export_startday='.urlencode($tmp['mday']).'&search_date_export_startyear='.urlencode($tmp['year']); + $param .= '&search_date_export_startmonth='.((int) $tmp['mon']).'&search_date_export_startday='.((int) $tmp['mday']).'&search_date_export_startyear='.((int) $tmp['year']); } if (!empty($search_date_export_end)) { $filter['t.date_export<='] = $search_date_export_end; $tmp = dol_getdate($search_date_export_end); - $param .= '&search_date_export_endmonth='.urlencode($tmp['mon']).'&search_date_export_endday='.urlencode($tmp['mday']).'&search_date_export_endyear='.urlencode($tmp['year']); + $param .= '&search_date_export_endmonth='.((int) $tmp['mon']).'&search_date_export_endday='.((int) $tmp['mday']).'&search_date_export_endyear='.((int) $tmp['year']); } if (!empty($search_date_validation_start)) { $filter['t.date_validated>='] = $search_date_validation_start; $tmp = dol_getdate($search_date_validation_start); - $param .= '&search_date_validation_startmonth='.urlencode($tmp['mon']).'&search_date_validation_startday='.urlencode($tmp['mday']).'&search_date_validation_startyear='.urlencode($tmp['year']); + $param .= '&search_date_validation_startmonth='.((int) $tmp['mon']).'&search_date_validation_startday='.((int) $tmp['mday']).'&search_date_validation_startyear='.((int) $tmp['year']); } if (!empty($search_date_validation_end)) { $filter['t.date_validated<='] = $search_date_validation_end; $tmp = dol_getdate($search_date_validation_end); - $param .= '&search_date_validation_endmonth='.urlencode($tmp['mon']).'&search_date_validation_endday='.urlencode($tmp['mday']).'&search_date_validation_endyear='.urlencode($tmp['year']); + $param .= '&search_date_validation_endmonth='.((int) $tmp['mon']).'&search_date_validation_endday='.((int) $tmp['mday']).'&search_date_validation_endyear='.((int) $tmp['year']); } if (!empty($search_debit)) { $filter['t.debit'] = $search_debit; @@ -468,6 +469,7 @@ if (empty($reshook)) { } $nbok = 0; + $result = 0; if (!$error) { foreach ($toselect as $toselectid) { $result = $object->fetch($toselectid); From 6798c5ccffb2521cec0668183b526f96f8260b7d Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 22:09:17 +0100 Subject: [PATCH 14/36] Ignore PhanRedefineFunctionInternal --- htdocs/admin/receiptprinter.php | 1 + 1 file changed, 1 insertion(+) diff --git a/htdocs/admin/receiptprinter.php b/htdocs/admin/receiptprinter.php index 6b7c5f686ed..7f7fd08ed2e 100644 --- a/htdocs/admin/receiptprinter.php +++ b/htdocs/admin/receiptprinter.php @@ -64,6 +64,7 @@ if (!function_exists('gzdecode')) { * * @param string $data data to deflate * @return string data deflated + * @phan-suppress PhanRedefineFunctionInternal */ function gzdecode($data) { From bbc185f6d1400383527a8ff57b2ec0b5894316eb Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 22:09:50 +0100 Subject: [PATCH 15/36] Adapt to real typings --- htdocs/admin/tools/listevents.php | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/htdocs/admin/tools/listevents.php b/htdocs/admin/tools/listevents.php index 902239fca39..5b2d106e295 100644 --- a/htdocs/admin/tools/listevents.php +++ b/htdocs/admin/tools/listevents.php @@ -3,6 +3,7 @@ * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2015 Bahfir Abbes * Copyright (C) 2018 Frédéric France + * Copyright (C) 2024 MDW * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -299,22 +300,22 @@ if ($result) { $param .= '&search_prefix_session='.urlencode($search_prefix_session); } if ($date_startmonth) { - $param .= "&date_startmonth=".urlencode($date_startmonth); + $param .= "&date_startmonth=".((int) $date_startmonth); } if ($date_startday) { - $param .= "&date_startday=".urlencode($date_startday); + $param .= "&date_startday=".((int) $date_startday); } if ($date_startyear) { - $param .= "&date_startyear=".urlencode($date_startyear); + $param .= "&date_startyear=".((int) $date_startyear); } if ($date_endmonth) { - $param .= "&date_endmonth=".urlencode($date_endmonth); + $param .= "&date_endmonth=".((int) $date_endmonth); } if ($date_endday) { - $param .= "&date_endday=".urlencode($date_endday); + $param .= "&date_endday=".((int) $date_endday); } if ($date_endyear) { - $param .= "&date_endyear=".urlencode($date_endyear); + $param .= "&date_endyear=".((int) $date_endyear); } $center = ''; From 1404b9c290810d252149913b0297bdec2bda2f26 Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 22:10:07 +0100 Subject: [PATCH 16/36] Adapt to real typings --- htdocs/blockedlog/admin/blockedlog_list.php | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/htdocs/blockedlog/admin/blockedlog_list.php b/htdocs/blockedlog/admin/blockedlog_list.php index 2604e35f362..b321745f90d 100644 --- a/htdocs/blockedlog/admin/blockedlog_list.php +++ b/htdocs/blockedlog/admin/blockedlog_list.php @@ -2,6 +2,7 @@ /* Copyright (C) 2017 ATM Consulting * Copyright (C) 2017-2018 Laurent Destailleur * Copyright (C) 2018 Frédéric France + * Copyright (C) 2024 MDW * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -349,25 +350,25 @@ if ($search_fk_user > 0) { $param .= '&search_fk_user='.urlencode($search_fk_user); } if ($search_startyear > 0) { - $param .= '&search_startyear='.urlencode($search_startyear); + $param .= '&search_startyear='.((int) $search_startyear); } if ($search_startmonth > 0) { - $param .= '&search_startmonth='.urlencode($search_startmonth); + $param .= '&search_startmonth='.((int) $search_startmonth); } if ($search_startday > 0) { - $param .= '&search_startday='.urlencode($search_startday); + $param .= '&search_startday='.((int) $search_startday); } if ($search_endyear > 0) { - $param .= '&search_endyear='.urlencode((string) ($search_endyear)); + $param .= '&search_endyear='.((int) $search_endyear); } if ($search_endmonth > 0) { - $param .= '&search_endmonth='.urlencode((string) ($search_endmonth)); + $param .= '&search_endmonth='.((int) $search_endmonth); } if ($search_endday > 0) { - $param .= '&search_endday='.urlencode((string) ($search_endday)); + $param .= '&search_endday='.((int) $search_endday); } if ($search_showonlyerrors > 0) { - $param .= '&search_showonlyerrors='.urlencode((string) ($search_showonlyerrors)); + $param .= '&search_showonlyerrors='.((int) $search_showonlyerrors); } if ($optioncss != '') { $param .= '&optioncss='.urlencode($optioncss); From 79b5add75a0327dc548a6cce97732431d118959a Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 22:10:37 +0100 Subject: [PATCH 17/36] Improve PHPdoc for array return value --- htdocs/blockedlog/class/blockedlog.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php index 476e1b3d82f..79f267f32ac 100644 --- a/htdocs/blockedlog/class/blockedlog.class.php +++ b/htdocs/blockedlog/class/blockedlog.class.php @@ -1096,7 +1096,7 @@ class BlockedLog * @param string $search_ref search ref * @param string $search_amount search amount * @param string $search_code search code - * @return array|int Array of object log or <0 if error + * @return BlockedLog[]|int<-2,-1> Array of object log or <0 if error */ public function getLog($element, $fk_object, $limit = 0, $sortfield = '', $sortorder = '', $search_fk_user = -1, $search_start = -1, $search_end = -1, $search_ref = '', $search_amount = '', $search_code = '') { From 30f1701c6f2293fa6295a61c6844552daa54bf46 Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 22:11:13 +0100 Subject: [PATCH 18/36] Improve typings, adapt --- htdocs/comm/action/peruser.php | 36 +++++++++++++++++----------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/htdocs/comm/action/peruser.php b/htdocs/comm/action/peruser.php index 97098383652..3daeca53c6e 100644 --- a/htdocs/comm/action/peruser.php +++ b/htdocs/comm/action/peruser.php @@ -99,10 +99,10 @@ if (!$user->hasRight('agenda', 'allactions', 'read') || $filter == 'mine') { // $mode = 'show_peruser'; $resourceid = GETPOSTINT("search_resourceid") ? GETPOSTINT("search_resourceid") : GETPOSTINT("resourceid"); -$year = GETPOSTINT("year") ? GETPOSTINT("year") : date("Y"); -$month = GETPOSTINT("month") ? GETPOSTINT("month") : date("m"); -$week = GETPOSTINT("week") ? GETPOSTINT("week") : date("W"); -$day = GETPOSTINT("day") ? GETPOSTINT("day") : date("d"); +$year = GETPOSTINT("year") ? GETPOSTINT("year") : idate("Y"); +$month = GETPOSTINT("month") ? GETPOSTINT("month") : idate("m"); +$week = GETPOSTINT("week") ? GETPOSTINT("week") : idate("W"); +$day = GETPOSTINT("day") ? GETPOSTINT("day") : idate("d"); $pid = GETPOSTISSET("search_projectid") ? GETPOSTINT("search_projectid", 3) : GETPOSTINT("projectid", 3); $status = GETPOSTISSET("search_status") ? GETPOST("search_status", 'aZ09') : GETPOST("status", 'aZ09'); // status may be 0, 50, 100, 'todo', 'na' or -1 $type = GETPOSTISSET("search_type") ? GETPOST("search_type", 'alpha') : GETPOST("type", 'alpha'); @@ -170,12 +170,12 @@ if (GETPOST('viewcal', 'alpha') && $mode != 'show_day' && $mode != 'show_week' & } // View by month if (GETPOST('viewweek', 'alpha') || $mode == 'show_week') { $mode = 'show_week'; - $week = ($week ? $week : date("W")); - $day = ($day ? $day : date("d")); + $week = ($week ? $week : idate("W")); + $day = ($day ? $day : idate("d")); } // View by week if (GETPOST('viewday', 'alpha') || $mode == 'show_day') { $mode = 'show_day'; - $day = ($day ? $day : date("d")); + $day = ($day ? $day : idate("d")); } // View by day $object = new ActionComm($db); @@ -257,7 +257,7 @@ $next_year = $next['year']; $next_month = $next['month']; $next_day = $next['day']; -$max_day_in_month = date("t", dol_mktime(0, 0, 0, $month, 1, $year)); +$max_day_in_month = idate("t", dol_mktime(0, 0, 0, $month, 1, $year)); $tmpday = $first_day; //print 'xx'.$prev_year.'-'.$prev_month.'-'.$prev_day; @@ -313,16 +313,16 @@ if ($mode != 'show_peruser') { $param .= '&mode='.urlencode($mode); } if ($begin_h != '') { - $param .= '&begin_h='.urlencode($begin_h); + $param .= '&begin_h='.((int) $begin_h); } if ($end_h != '') { - $param .= '&end_h='.urlencode($end_h); + $param .= '&end_h='.((int) $end_h); } if ($begin_d != '') { - $param .= '&begin_d='.urlencode($begin_d); + $param .= '&begin_d='.((int) $begin_d); } if ($end_d != '') { - $param .= '&end_d='.urlencode($end_d); + $param .= '&end_d='.((int) $end_d); } if ($search_categ_cus != 0) { $param .= '&search_categ_cus='.urlencode((string) ($search_categ_cus)); @@ -358,7 +358,7 @@ $lastdaytoshow = dol_time_plus_duree($firstdaytoshow, $nb_weeks_to_show, 'd'); //print dol_print_date($firstdaytoshow, 'dayhour', 'gmt'); //print dol_print_date($lastdaytoshow,'dayhour', 'gmt'); -$max_day_in_month = date("t", dol_mktime(0, 0, 0, $month, 1, $year, 'gmt')); +$max_day_in_month = idate("t", dol_mktime(0, 0, 0, $month, 1, $year, 'gmt')); $tmpday = $first_day; $picto = 'calendarweek'; @@ -482,18 +482,18 @@ $newcardbutton = ''; if ($user->hasRight('agenda', 'myactions', 'create') || $user->hasRight('agenda', 'allactions', 'create')) { $tmpforcreatebutton = dol_getdate(dol_now(), true); - $newparam .= '&month='.urlencode(str_pad($month, 2, "0", STR_PAD_LEFT)).'&year='.urlencode($tmpforcreatebutton['year']); + $newparam .= '&month='.urlencode(str_pad((string) $month, 2, "0", STR_PAD_LEFT)).'&year='.((int) $tmpforcreatebutton['year']); if ($begin_h !== '') { - $newparam .= '&begin_h='.urlencode($begin_h); + $newparam .= '&begin_h='.((int) $begin_h); } if ($end_h !== '') { - $newparam .= '&end_h='.urlencode($end_h); + $newparam .= '&end_h='.((int) $end_h); } if ($begin_d !== '') { - $newparam .= '&begin_d='.urlencode($begin_d); + $newparam .= '&begin_d='.((int) $begin_d); } if ($end_d !== '') { - $newparam .= '&end_d='.urlencode($end_d); + $newparam .= '&end_d='.((int) $end_d); } $urltocreateaction = DOL_URL_ROOT.'/comm/action/card.php?action=create'; From d17c010e59e631259be0d3271ca583cc20b1999c Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 22:11:43 +0100 Subject: [PATCH 19/36] Improve PHPdoc typings --- htdocs/core/class/conf.class.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php index 37677a086b0..25361f71368 100644 --- a/htdocs/core/class/conf.class.php +++ b/htdocs/core/class/conf.class.php @@ -110,13 +110,17 @@ class Conf extends stdClass public $logbuffer = array(); /** - * @var LogHandlerInterface[] + * @var LogHandler[] */ public $loghandlers = array(); - //! Used to store running instance for multi-company (default 1) + /** + * @var int Used to store running instance for multi-company (default 1) + */ public $entity = 1; - //! Used to store list of entities to use for each element + /** + * @var int[] Used to store list of entities to use for each element + */ public $entities = array(); public $dol_hide_topmenu; // Set if we force param dol_hide_topmenu into login url From 767eeb605df1306bc8e41568139fb9b555b759c1 Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 22:14:31 +0100 Subject: [PATCH 20/36] Style (phpcbf not agreeing with php-cs-fixer) --- htdocs/core/class/html.form.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index edeec79facf..e14b020b144 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -5225,8 +5225,8 @@ class Form * @param string $question Question * @param string $action Action * @param array|string|null $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>'autofocus' or 'style=...')) - * 'type' can be 'text', 'password', 'checkbox', 'radio', 'date', 'datetime', 'select', 'multiselect', 'morecss', - * 'other', 'onecolumn' or 'hidden'... + * 'type' can be 'text', 'password', 'checkbox', 'radio', 'date', 'datetime', 'select', 'multiselect', 'morecss', + * 'other', 'onecolumn' or 'hidden'... * @param int|string $selectedchoice '' or 'no', or 'yes' or '1', 1, '0' or 0 * @param int|string $useajax 0=No, 1=Yes use Ajax to show the popup, 2=Yes and also submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx * @param int|string $height Force height of box (0 = auto) From 37515f11541b924f13fe4a7152ade3ab2043a395 Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 22:15:43 +0100 Subject: [PATCH 21/36] Adjust to real typings --- htdocs/core/lib/admin.lib.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/lib/admin.lib.php b/htdocs/core/lib/admin.lib.php index cfc9045aae1..3e50cda3947 100644 --- a/htdocs/core/lib/admin.lib.php +++ b/htdocs/core/lib/admin.lib.php @@ -396,7 +396,7 @@ function run_sql($sqlfile, $silent = 1, $entity = 0, $usesavepoint = 1, $handler $sql = preg_replace('/__DATABASE__/i', $db->escape($database), $sql); } - $newsql = preg_replace('/__ENTITY__/i', (!empty($entity) ? $entity : $conf->entity), $sql); + $newsql = preg_replace('/__ENTITY__/i', (!empty($entity) ? $entity : (string) $conf->entity), $sql); // Add log of request if (!$silent) { From e2b02953084f302e6e46126880da47f6f1d4f787 Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 22:15:57 +0100 Subject: [PATCH 22/36] Adjust to real typings --- htdocs/core/lib/date.lib.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/core/lib/date.lib.php b/htdocs/core/lib/date.lib.php index 8b7ea390b71..b3d71145ab2 100644 --- a/htdocs/core/lib/date.lib.php +++ b/htdocs/core/lib/date.lib.php @@ -688,8 +688,8 @@ function dol_get_first_day_week($day, $month, $year, $gm = false) //print 'start_week='.$start_week.' tmparray[wday]='.$tmparray['wday'].' day offset='.$days.' seconds offset='.$seconds.'
'; //Get first day of week - $tmpdaytms = (int) date($tmparray[0]) - $seconds; // $tmparray[0] is day of parameters - $tmpday = (int) date("d", $tmpdaytms); + $tmpdaytms = (int) date((string) $tmparray['0']) - $seconds; // $tmparray[0] is day of parameters + $tmpday = idate("d", $tmpdaytms); //Check first day of week is in same month than current day or not if ($tmpday > $day) { From 1ee639bb8124ab0ad144d78a22f7aa124af972da Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 22:16:25 +0100 Subject: [PATCH 23/36] Adjust to real typings --- htdocs/core/modules/DolibarrModules.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/modules/DolibarrModules.class.php b/htdocs/core/modules/DolibarrModules.class.php index 6aabd6443ef..801cbe72869 100644 --- a/htdocs/core/modules/DolibarrModules.class.php +++ b/htdocs/core/modules/DolibarrModules.class.php @@ -500,7 +500,7 @@ class DolibarrModules // Can not be abstract, because we need to instantiate it $ignoreerror = $val['ignoreerror']; } // Add current entity id - $sql = str_replace('__ENTITY__', $conf->entity, $sql); + $sql = str_replace('__ENTITY__', (string) $conf->entity, $sql); dol_syslog(get_class($this)."::_init ignoreerror=".$ignoreerror, LOG_DEBUG); $result = $this->db->query($sql, $ignoreerror); From 006a8c34e6edd14cc1234ee45ceb8fdc831fe7aa Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 22:16:44 +0100 Subject: [PATCH 24/36] Adjust to real typings --- htdocs/core/multicompany_page.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/htdocs/core/multicompany_page.php b/htdocs/core/multicompany_page.php index 9286e3efaaa..a047ef74968 100644 --- a/htdocs/core/multicompany_page.php +++ b/htdocs/core/multicompany_page.php @@ -1,5 +1,6 @@ + * Copyright (C) 2024 MDW * * This file is a modified version of datepicker.php from phpBSM to fix some * bugs, to add new features and to dramatically increase speed. @@ -91,9 +92,8 @@ print ''."\n"; print '
'; //print '
'; -if (!isset($bookmarkList)) { - $bookmarkList = ''; -} + +$bookmarkList = ''; if (!isModEnabled('multicompany')) { $langs->load("admin"); $bookmarkList .= '
'.$langs->trans("WarningModuleNotActive", $langs->transnoentitiesnoconv("MultiCompany")).''; @@ -109,6 +109,8 @@ if (!isModEnabled('multicompany')) { if (is_object($mc)) { $listofentities = $mc->getEntitiesList($user->login, false, true); + } else { + $listofentities = array(); } $multicompanyList .= '
    '; From fd66fd6a38cfc4dc35320eb37641c50ae64ee610 Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 25 Mar 2024 22:49:18 +0100 Subject: [PATCH 25/36] Adjust to real typing --- htdocs/ticket/list.php | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/htdocs/ticket/list.php b/htdocs/ticket/list.php index 2b1a28cbdb0..b6433a6eac8 100644 --- a/htdocs/ticket/list.php +++ b/htdocs/ticket/list.php @@ -681,39 +681,39 @@ if ($contractid > 0) { } if ($search_date_start) { $tmparray = dol_getdate($search_date_start); - $param .= '&search_date_startday='.urlencode($tmparray['mday']); - $param .= '&search_date_startmonth='.urlencode($tmparray['mon']); - $param .= '&search_date_startyear='.urlencode($tmparray['year']); + $param .= '&search_date_startday='.((int) $tmparray['mday']); + $param .= '&search_date_startmonth='.((int) $tmparray['mon']); + $param .= '&search_date_startyear='.((int) $tmparray['year']); } if ($search_date_end) { $tmparray = dol_getdate($search_date_end); - $param .= '&search_date_endday='.urlencode($tmparray['mday']); - $param .= '&search_date_endmonth='.urlencode($tmparray['mon']); - $param .= '&search_date_endyear='.urlencode($tmparray['year']); + $param .= '&search_date_endday='.((int) $tmparray['mday']); + $param .= '&search_date_endmonth='.((int) $tmparray['mon']); + $param .= '&search_date_endyear='.((int) $tmparray['year']); } if ($search_dateread_start) { $tmparray = dol_getdate($search_dateread_start); - $param .= '&search_dateread_startday='.urlencode($tmparray['mday']); - $param .= '&search_dateread_startmonth='.urlencode($tmparray['mon']); - $param .= '&search_dateread_startyear='.urlencode($tmparray['year']); + $param .= '&search_dateread_startday='.((int) $tmparray['mday']); + $param .= '&search_dateread_startmonth='.((int) $tmparray['mon']); + $param .= '&search_dateread_startyear='.((int) $tmparray['year']); } if ($search_dateread_end) { $tmparray = dol_getdate($search_dateread_end); - $param .= '&search_dateread_endday='.urlencode($tmparray['mday']); - $param .= '&search_dateread_endmonth='.urlencode($tmparray['mon']); - $param .= '&search_dateread_endyear='.urlencode($tmparray['year']); + $param .= '&search_dateread_endday='.((int) $tmparray['mday']); + $param .= '&search_dateread_endmonth='.((int) $tmparray['mon']); + $param .= '&search_dateread_endyear='.((int) $tmparray['year']); } if ($search_dateclose_start) { $tmparray = dol_getdate($search_dateclose_start); - $param .= '&search_dateclose_startday='.urlencode($tmparray['mday']); - $param .= '&search_dateclose_startmonth='.urlencode($tmparray['mon']); - $param .= '&search_dateclose_startyear='.urlencode($tmparray['year']); + $param .= '&search_dateclose_startday='.((int) $tmparray['mday']); + $param .= '&search_dateclose_startmonth='.((int) $tmparray['mon']); + $param .= '&search_dateclose_startyear='.((int) $tmparray['year']); } if ($search_dateclose_end) { $tmparray = dol_getdate($search_dateclose_end); - $param .= '&search_date_endday='.urlencode($tmparray['mday']); - $param .= '&search_date_endmonth='.urlencode($tmparray['mon']); - $param .= '&search_date_endyear='.urlencode($tmparray['year']); + $param .= '&search_date_endday='.((int) $tmparray['mday']); + $param .= '&search_date_endmonth='.((int) $tmparray['mon']); + $param .= '&search_date_endyear='.((int) $tmparray['year']); } // List of mass actions available $arrayofmassactions = array( From d765e847a7417cca69b07ab24b6fa7f7e295dc07 Mon Sep 17 00:00:00 2001 From: MDW Date: Tue, 26 Mar 2024 00:40:41 +0100 Subject: [PATCH 26/36] Allow empty array for dol_print_date() return --- htdocs/core/lib/functions.lib.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 7b5bed8423f..b258dc47d5d 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -3228,7 +3228,7 @@ function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = * @param int $timestamp Timestamp * @param boolean $fast Fast mode. deprecated. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone. - * @return array{seconds:int<0,59>,minutes:int<0,59>,hours:int<0,23>,mday:int<1,31>,wday:int<0,6>,mon:int<1,12>,year:int<0,9999>,yday:int<0,366>,0:int} Array of information + * @return array{}|array{seconds:int<0,59>,minutes:int<0,59>,hours:int<0,23>,mday:int<1,31>,wday:int<0,6>,mon:int<1,12>,year:int<0,9999>,yday:int<0,366>,0:int} Array of information * 'seconds' => $secs, * 'minutes' => $min, * 'hours' => $hour, From a703ea1092ee0dd456b066483de825a0efa1c0bd Mon Sep 17 00:00:00 2001 From: MDW Date: Tue, 26 Mar 2024 00:57:32 +0100 Subject: [PATCH 27/36] Add checks on dol_(mktime|now|print_date) + avoid duplicate phan conf --- dev/tools/phan/config.php | 3 + dev/tools/phan/config_extended.php | 376 +---------------------------- dev/tools/phan/config_fixer.php | 239 ++---------------- 3 files changed, 27 insertions(+), 591 deletions(-) diff --git a/dev/tools/phan/config.php b/dev/tools/phan/config.php index 38dcbb2bff1..c70f6dd5058 100644 --- a/dev/tools/phan/config.php +++ b/dev/tools/phan/config.php @@ -351,6 +351,9 @@ return [ '/^isModEnable[d]$/' => [0, $deprecatedModuleNameRegex, "DeprecatedModuleName"], '/^sanitizeVal$/' => [1, $sanitizeRegex,"UnknownSanitizeType"], '/^\\\\ExtraFields::addExtraField$/' => [2, $extraFieldTypeRegex,"UnknownExtrafieldTypeBack"], + '/^dol_now$/' => [0, '{^(?:auto|gmt|tz(?:server|ref|user(?:rel)?))$}',"InvalidDolNowArgument"], // '', 0, 1 match bool and int values + '/^dol_mktime$/' => [6, '{^(?:|0|1|auto|gmt|tz(?:server|ref|user(?:rel)?|,[+a-zA-Z-/]+))$}',"InvalidDolMktimeArgument"], // '', 0, 1 match bool and int values + '/^dol_print_date$/' => [2, '{^(?:|0|1|auto|gmt|tz(?:server|user(?:rel)?))$}',"InvalidDolMktimeArgument"], ], 'plugins' => [ __DIR__.'/plugins/NoVarDumpPlugin.php', diff --git a/dev/tools/phan/config_extended.php b/dev/tools/phan/config_extended.php index 535f52f70b2..991ba4d3668 100644 --- a/dev/tools/phan/config_extended.php +++ b/dev/tools/phan/config_extended.php @@ -1,324 +1,12 @@ */ -define('DOL_PROJECT_ROOT', __DIR__.'/../../..'); -define('DOL_DOCUMENT_ROOT', DOL_PROJECT_ROOT.'/htdocs'); -define('PHAN_DIR', __DIR__); -$sanitizeRegex - = '/^(array:)?(?:'.implode( - '|', - array( - // Documented: - 'none', - 'array', - 'int', - 'intcomma', - 'alpha', - 'alphawithlgt', - 'alphanohtml', - 'MS', - 'aZ', - 'aZ09', - 'aZ09arobase', - 'aZ09comma', - 'san_alpha', - 'restricthtml', - 'nohtml', - 'custom', - // Not documented: - 'email', - 'restricthtmlallowclass', - 'restricthtmlallowunvalid', - 'restricthtmlnolink', - //'ascii', - //'categ_id', - //'chaine', - //'html', - //'boolean', - //'double', - //'float', - //'string', - ) - ).')*$/'; +// Load default configuration (with many exclusions) +// +$config = include __DIR__.DIRECTORY_SEPARATOR."config.php"; -/** - * Map deprecated module names to new module names - */ -$DEPRECATED_MODULE_MAPPING = array( - 'actioncomm' => 'agenda', - 'adherent' => 'member', - 'adherent_type' => 'member_type', - 'banque' => 'bank', - 'categorie' => 'category', - 'commande' => 'order', - 'contrat' => 'contract', - 'entrepot' => 'stock', - 'expedition' => 'shipping', - 'facture' => 'invoice', - 'ficheinter' => 'intervention', - 'product_fournisseur_price' => 'productsupplierprice', - 'product_price' => 'productprice', - 'projet' => 'project', - 'propale' => 'propal', - 'socpeople' => 'contact', -); - -/** - * Map module names to the 'class' name (the class is: mod) - * Value is null when the module is not internal to the default - * Dolibarr setup. - */ -$VALID_MODULE_MAPPING = array( - 'accounting' => 'Accounting', - 'agenda' => 'Agenda', - 'ai' => 'Ai', - 'anothermodule' => null, - 'api' => 'Api', - 'asset' => 'Asset', - 'bank' => 'Banque', - 'barcode' => 'Barcode', - 'blockedlog' => 'BlockedLog', - 'bom' => 'Bom', - 'bookcal' => 'BookCal', - 'bookmark' => 'Bookmark', - 'cashdesk' => null, // TODO: fill in proper class - 'category' => 'Categorie', - 'clicktodial' => 'ClickToDial', - 'collab' => 'Collab', - 'comptabilite' => 'Comptabilite', - 'contact' => null, // TODO: fill in proper class - 'contract' => 'Contrat', - 'cron' => 'Cron', - 'datapolicy' => 'DataPolicy', - 'dav' => 'Dav', - 'debugbar' => 'DebugBar', - 'shipping' => 'Expedition', - 'deplacement' => 'Deplacement', - "documentgeneration" => 'DocumentGeneration', - 'don' => 'Don', - 'dynamicprices' => 'DynamicPrices', - 'ecm' => 'ECM', - 'ecotax' => null, // TODO: External module ? - 'emailcollector' => 'EmailCollector', - 'eventorganization' => 'EventOrganization', - 'expensereport' => 'ExpenseReport', - 'export' => 'Export', - 'externalrss' => 'ExternalRss', - 'externalsite' => 'ExternalSite', - 'fckeditor' => 'Fckeditor', - 'fournisseur' => 'Fournisseur', - 'ftp' => 'FTP', - 'geoipmaxmind' => 'GeoIPMaxmind', - 'google' => null, // External ? - 'gravatar' => 'Gravatar', - 'holiday' => 'Holiday', - 'hrm' => 'HRM', - 'import' => 'Import', - 'incoterm' => 'Incoterm', - 'intervention' => 'Ficheinter', - 'intracommreport' => 'Intracommreport', - 'invoice' => 'Facture', - 'knowledgemanagement' => 'KnowledgeManagement', - 'label' => 'Label', - 'ldap' => 'Ldap', - 'loan' => 'Loan', - 'mailing' => 'Mailing', - 'mailman' => null, // Same module as mailmanspip -> MailmanSpip ?? - 'mailmanspip' => 'MailmanSpip', - 'margin' => 'Margin', - 'member' => 'Adherent', - 'memcached' => null, // TODO: External module? - 'modulebuilder' => 'ModuleBuilder', - 'mrp' => 'Mrp', - 'multicompany' => null, // Not provided by default, no module tests - 'multicurrency' => 'MultiCurrency', - 'mymodule' => null, // modMyModule - Name used in module builder (avoid false positives) - 'notification' => 'Notification', - 'numberwords' => null, // Not provided by default, no module tests - 'oauth' => 'Oauth', - 'openstreetmap' => null, // External module? - 'opensurvey' => 'OpenSurvey', - 'order' => 'Commande', - 'partnership' => 'Partnership', - 'paybox' => 'Paybox', - 'paymentbybanktransfer' => 'PaymentByBankTransfer', - 'paypal' => 'Paypal', - 'paypalplus' => null, - 'prelevement' => 'Prelevement', - 'printing' => 'Printing', - 'product' => 'Product', - 'productbatch' => 'ProductBatch', - 'productprice' => null, - 'productsupplierprice' => null, - 'project' => 'Projet', - 'propal' => 'Propale', - 'receiptprinter' => 'ReceiptPrinter', - 'reception' => 'Reception', - 'recruitment' => 'Recruitment', - 'resource' => 'Resource', - 'salaries' => 'Salaries', - 'service' => 'Service', - 'socialnetworks' => 'SocialNetworks', - 'societe' => 'Societe', - 'stock' => 'Stock', - 'stocktransfer' => 'StockTransfer', - 'stripe' => 'Stripe', - 'supplier_invoice' => null, // Special case, uses invoice - 'supplier_order' => null, // Special case, uses invoice - 'supplier_proposal' => 'SupplierProposal', - 'syslog' => 'Syslog', - 'takepos' => 'TakePos', - 'tax' => 'Tax', - 'theme_datacolor' => 'array{0:array{0:int,1:int,2:int},1:array{0:int,1:int,2:int},2:array{0:int,1:int,2:int},3:array{0:int,1:int,2:int}}', - 'ticket' => 'Ticket', - 'user' => 'User', - 'variants' => 'Variants', - 'webhook' => 'Webhook', - 'webportal' => 'WebPortal', - 'webservices' => 'WebServices', - 'webservicesclient' => 'WebServicesClient', - 'website' => 'Website', - 'workflow' => 'Workflow', - 'workstation' => 'Workstation', - 'zapier' => 'Zapier', -); - -$moduleNameRegex = '/^(?:'.implode('|', array_merge(array_keys($DEPRECATED_MODULE_MAPPING), array_keys($VALID_MODULE_MAPPING))).')$/'; - -$deprecatedModuleNameRegex = '/^(?!(?:'.implode('|', array_keys($DEPRECATED_MODULE_MAPPING)).')$).*/'; - -/** - * This configuration will be read and overlaid on top of the - * default configuration. Command line arguments will be applied - * after this file is read. - */ -return [ - // 'processes' => 6, - 'backward_compatibility_checks' => false, - 'simplify_ast' => true, - 'analyzed_file_extensions' => ['php','inc'], - 'globals_type_map' => [ - 'action' => 'string', - 'actioncode' => 'string', - 'badgeStatus0' => 'string', - 'badgeStatus1' => 'string', - 'badgeStatus11' => 'string', - 'badgeStatus3' => 'string', - 'badgeStatus4' => 'string', - 'badgeStatus6' => 'string', - 'badgeStatus8' => 'string', - 'badgeStatus9' => 'string', - 'classname' => 'string', - 'conf' => '\Conf', - 'conffile' => 'string', - 'conffiletoshow' => 'string', - 'conffiletoshowshort' => 'string', - 'db' => '\DoliDB', - 'disableedit' => 'int<0,1>', - 'disablemove' => 'int<0,1>', - 'disableremove' => 'int<0,1>', - 'dolibarr_main_authentication' => 'string', - 'dolibarr_main_data_root' => 'string', - 'dolibarr_main_data_root' => 'string', - 'dolibarr_main_db_encrypted_pass' => 'string', - 'dolibarr_main_db_host' => 'string', - 'dolibarr_main_db_pass' => 'string', - 'dolibarr_main_demo' => 'string', - 'dolibarr_main_document_root' => 'string', - 'dolibarr_main_url_root' => 'string', - 'errormsg' => 'string', - 'extrafields' => '\ExtraFields', - 'filter' => 'string', - 'filtert' => 'int', - 'forceall' => 'int<0,1>', - 'form' => '\Form', - 'hookmanager' => '\HookManager', - 'inputalsopricewithtax' => 'int<0,1>', - 'langs' => '\Translate', - 'leftmenu' => 'string', - 'mainmenu' => 'string', - 'menumanager' => '\MenuManager', - 'mysoc' => '\Societe', - 'nblines' => '\int', - 'obj' => '\CommonObject', // Deprecated - 'object_rights' => 'int|stdClass', - 'objectoffield' => '\CommonObject', - 'senderissupplier' => 'int<0,2>', - 'user' => '\User', - 'website' => 'string', // See discussion https://github.com/Dolibarr/dolibarr/pull/28891#issuecomment-2002268334 // Disable because Phan infers Website type - 'websitepage' => '\WebSitePage', - 'websitepagefile' => 'string', - // 'object' => '\CommonObject', // Deprecated, not enabled because conflicts with $object assignments - ], - - // Supported values: `'5.6'`, `'7.0'`, `'7.1'`, `'7.2'`, `'7.3'`, `'7.4'`, `null`. - // If this is set to `null`, - // then Phan assumes the PHP version which is closest to the minor version - // of the php executable used to execute Phan. - //"target_php_version" => null, - "target_php_version" => '8.2', - //"target_php_version" => '7.3', - //"target_php_version" => '5.6', - - // A list of directories that should be parsed for class and - // method information. After excluding the directories - // defined in exclude_analysis_directory_list, the remaining - // files will be statically analyzed for errors. - // - // Thus, both first-party and third-party code being used by - // your application should be included in this list. - 'directory_list' => [ - 'htdocs', - PHAN_DIR . '/stubs/', - ], - - // A directory list that defines files that will be excluded - // from static analysis, but whose class and method - // information should be included. - // - // Generally, you'll want to include the directories for - // third-party code (such as "vendor/") in this list. - // - // n.b.: If you'd like to parse but not analyze 3rd - // party code, directories containing that code - // should be added to the `directory_list` as - // to `exclude_analysis_directory_list`. - "exclude_analysis_directory_list" => [ - 'htdocs/includes/', - 'htdocs/install/doctemplates/websites/', - 'htdocs/core/class/lessc.class.php', // External library - PHAN_DIR . '/stubs/', - ], - //'exclude_file_regex' => '@^vendor/.*/(tests?|Tests?)/@', - 'exclude_file_regex' => '@^(' // @phpstan-ignore-line - .'dummy' // @phpstan-ignore-line - .'|htdocs/.*/canvas/.*/tpl/.*.tpl.php' // @phpstan-ignore-line - .'|htdocs/modulebuilder/template/.*' // @phpstan-ignore-line - // Included as stub (old version + incompatible typing hints) - .'|htdocs/includes/restler/.*' // @phpstan-ignore-line - // Included as stub (did not seem properly analysed by phan without it) - .'|htdocs/includes/stripe/.*' // @phpstan-ignore-line - .'|htdocs/conf/conf.php' // @phpstan-ignore-line - .')@', // @phpstan-ignore-line - - // A list of plugin files to execute. - // Plugins which are bundled with Phan can be added here by providing their name - // (e.g. 'AlwaysReturnPlugin') - // - // Documentation about available bundled plugins can be found - // at https://github.com/phan/phan/tree/master/.phan/plugins - // - // Alternately, you can pass in the full path to a PHP file - // with the plugin's implementation (e.g. 'vendor/phan/phan/.phan/plugins/AlwaysReturnPlugin.php') - 'ParamMatchRegexPlugin' => [ - '/^GETPOST$/' => [1, $sanitizeRegex, 'GetPostUnknownSanitizeType'], - '/^isModEnabled$/' => [0, $moduleNameRegex, 'UnknownModuleName'], - // Note: trick to have different key for same regex: - '/^isModEnable[d]$/' => [0, $deprecatedModuleNameRegex, "DeprecatedModuleName"], - '/^sanitizeVal$/' => [1, $sanitizeRegex,"UnknownSanitizeType"], - ], - 'plugins' => [ +$config['plugins'] = [ __DIR__.'/plugins/NoVarDumpPlugin.php', __DIR__.'/plugins/ParamMatchRegexPlugin.php', 'DeprecateAliasPlugin', @@ -367,11 +55,11 @@ return [ 'UseReturnValuePlugin', 'EmptyStatementListPlugin', 'LoopVariableReusePlugin', - ], + ]; - // Add any issue types (such as 'PhanUndeclaredMethod') - // here to inhibit them from being reported - 'suppress_issue_types' => [ +// Add any issue types (such as 'PhanUndeclaredMethod') +// here to inhibit them from being reported +$config['suppress_issue_types'] = [ 'PhanCompatibleNegativeStringOffset', // return false positive 'PhanPluginWhitespaceTab', // Dolibarr used tabs @@ -394,50 +82,6 @@ return [ 'PhanPluginDuplicateConditionalNullCoalescing', // Not essential - 990+ occurrences 'PhanPluginRedundantAssignmentInGlobalScope', // Not essential, a lot of false warning 'PhanPluginDuplicateCatchStatementBody', // Requires PHP7.1 - 50+ occurrences - ], - // You can put relative paths to internal stubs in this config option. - // Phan will continue using its detailed type annotations, - // but load the constants, classes, functions, and classes (and their Reflection types) - // from these stub files (doubling as valid php files). - // Use a different extension from php (and preferably a separate folder) - // to avoid accidentally parsing these as PHP (includes projects depending on this). - // The 'mkstubs' script can be used to generate your own stubs (compatible with php 7.0+ right now) - // Note: The array key must be the same as the extension name reported by `php -m`, - // so that phan can skip loading the stubs if the extension is actually available. - 'autoload_internal_extension_signatures' => [ - // Stubs may be available at https://github.com/JetBrains/phpstorm-stubs/tree/master - - // Xdebug stubs are bundled with Phan 0.10.1+/0.8.9+ for usage, - // because Phan disables xdebug by default. - //'xdebug' => 'vendor/phan/phan/.phan/internal_stubs/xdebug.phan_php', - //'memcached' => PHAN_DIR . '/your_internal_stubs_folder_name/memcached.phan_php', - //'PDO' => PHAN_DIR . '/stubs/PDO.phan_php', - 'brotli' => PHAN_DIR . '/stubs/brotli.phan_php', - 'curl' => PHAN_DIR . '/stubs/curl.phan_php', - 'calendar' => PHAN_DIR . '/stubs/calendar.phan_php', - 'fileinfo' => PHAN_DIR . '/stubs/fileinfo.phan_php', - 'ftp' => PHAN_DIR . '/stubs/ftp.phan_php', - 'gd' => PHAN_DIR . '/stubs/gd.phan_php', - 'geoip' => PHAN_DIR . '/stubs/geoip.phan_php', - 'imap' => PHAN_DIR . '/stubs/imap.phan_php', - 'imagick' => PHAN_DIR . '/stubs/imagick.phan_php', - 'intl' => PHAN_DIR . '/stubs/intl.phan_php', - 'ldap' => PHAN_DIR . '/stubs/ldap.phan_php', - 'mcrypt' => PHAN_DIR . '/stubs/mcrypt.phan_php', - 'memcache' => PHAN_DIR . '/stubs/memcache.phan_php', - 'memcached' => PHAN_DIR . '/stubs/memcached.phan_php', - 'mysqli' => PHAN_DIR . '/stubs/mysqli.phan_php', - 'pdo_cubrid' => PHAN_DIR . '/stubs/pdo_cubrid.phan_php', - 'pdo_mysql' => PHAN_DIR . '/stubs/pdo_mysql.phan_php', - 'pdo_pgsql' => PHAN_DIR . '/stubs/pdo_pgsql.phan_php', - 'pdo_sqlite' => PHAN_DIR . '/stubs/pdo_sqlite.phan_php', - 'pgsql' => PHAN_DIR . '/stubs/pgsql.phan_php', - 'session' => PHAN_DIR . '/stubs/session.phan_php', - 'simplexml' => PHAN_DIR . '/stubs/SimpleXML.phan_php', - 'soap' => PHAN_DIR . '/stubs/soap.phan_php', - 'sockets' => PHAN_DIR . '/stubs/sockets.phan_php', - 'tidy' => PHAN_DIR . '/stubs/tidy.phan_php', - 'zip' => PHAN_DIR . '/stubs/zip.phan_php', - ], - ]; + +return $config; diff --git a/dev/tools/phan/config_fixer.php b/dev/tools/phan/config_fixer.php index 5df01eb7ae6..79a3d589d38 100644 --- a/dev/tools/phan/config_fixer.php +++ b/dev/tools/phan/config_fixer.php @@ -3,101 +3,22 @@ * Copyright (C) 2024 Frédéric France */ -// Uncomment require_once to enable corresponding fixer + +// Load default configuration (with many exclusions) +// +$config = include __DIR__.DIRECTORY_SEPARATOR."config.php"; + //require_once __DIR__.'/plugins/DeprecatedModuleNameFixer.php'; //require_once __DIR__.'/plugins/PriceFormFixer.php'; //require_once __DIR__.'/plugins/UrlEncodeStringifyFixer.php'; require_once __DIR__.'/plugins/SelectDateFixer.php'; -define('DOL_PROJECT_ROOT', __DIR__.'/../../..'); -define('DOL_DOCUMENT_ROOT', DOL_PROJECT_ROOT.'/htdocs'); -define('PHAN_DIR', __DIR__); - -$DEPRECATED_MODULE_MAPPING = array( - 'actioncomm' => 'agenda', - 'adherent' => 'member', - 'adherent_type' => 'member_type', - 'banque' => 'bank', - 'categorie' => 'category', - 'commande' => 'order', - 'contrat' => 'contract', - 'entrepot' => 'stock', - 'expedition' => 'shipping', - 'facture' => 'invoice', - 'ficheinter' => 'intervention', - 'product_fournisseur_price' => 'productsupplierprice', - 'product_price' => 'productprice', - 'projet' => 'project', - 'propale' => 'propal', - 'socpeople' => 'contact', -); - -$deprecatedModuleNameRegex = '/^(?!(?:'.implode('|', array_keys($DEPRECATED_MODULE_MAPPING)).')$).*/'; +//$deprecatedModuleNameRegex = '/^(?!(?:'.implode('|', array_keys($DEPRECATED_MODULE_MAPPING)).')$).*/'; require_once __DIR__.'/plugins/DeprecatedModuleNameFixer.php'; -/** - * This configuration will be read and overlaid on top of the - * default configuration. Command line arguments will be applied - * after this file is read. - */ -return [ - // 'processes' => 6, - 'backward_compatibility_checks' => false, - 'simplify_ast' => true, - 'analyzed_file_extensions' => ['php','inc'], - 'globals_type_map' => [ - 'conf' => '\Conf', - 'db' => '\DoliDB', - 'extrafields' => '\ExtraFields', - 'hookmanager' => '\HookManager', - 'langs' => '\Translate', - 'mysoc' => '\Societe', - 'nblines' => '\int', - 'user' => '\User', - ], - - // Supported values: `'5.6'`, `'7.0'`, `'7.1'`, `'7.2'`, `'7.3'`, `'7.4'`, `null`. - // If this is set to `null`, - // then Phan assumes the PHP version which is closest to the minor version - // of the php executable used to execute Phan. - //"target_php_version" => null, - "target_php_version" => '8.2', - //"target_php_version" => '7.3', - //"target_php_version" => '5.6', - - // A list of directories that should be parsed for class and - // method information. After excluding the directories - // defined in exclude_analysis_directory_list, the remaining - // files will be statically analyzed for errors. - // - // Thus, both first-party and third-party code being used by - // your application should be included in this list. - 'directory_list' => [ - 'htdocs', - PHAN_DIR . '/stubs/', - ], - - // A directory list that defines files that will be excluded - // from static analysis, but whose class and method - // information should be included. - // - // Generally, you'll want to include the directories for - // third-party code (such as "vendor/") in this list. - // - // n.b.: If you'd like to parse but not analyze 3rd - // party code, directories containing that code - // should be added to the `directory_list` as - // to `exclude_analysis_directory_list`. - "exclude_analysis_directory_list" => [ - 'htdocs/includes/', - 'htdocs/install/doctemplates/websites/', - 'htdocs/core/class/lessc.class.php', // External library - PHAN_DIR . '/stubs/', - ], - //'exclude_file_regex' => '@^vendor/.*/(tests?|Tests?)/@', - 'exclude_file_regex' => '@^(' // @phpstan-ignore-line +$config['exclude_file_regex'] = '@^(' // @phpstan-ignore-line .'dummy' // @phpstan-ignore-line .'|htdocs/.*/canvas/.*/tpl/.*.tpl.php' // @phpstan-ignore-line .'|htdocs/modulebuilder/template/.*' // @phpstan-ignore-line @@ -108,144 +29,12 @@ return [ .'|htdocs/conf/conf.php' // @phpstan-ignore-line //.'|htdocs/[^c][^o][^r][^e][^/].*' // For testing @phpstan-ignore-line //.'|htdocs/[^h].*' // For testing on restricted set @phpstan-ignore-line - .')@', // @phpstan-ignore-line + .')@'; // @phpstan-ignore-line - // A list of plugin files to execute. - // Plugins which are bundled with Phan can be added here by providing their name - // (e.g. 'AlwaysReturnPlugin') - // - // Documentation about available bundled plugins can be found - // at https://github.com/phan/phan/tree/master/.phan/plugins - // - // Alternately, you can pass in the full path to a PHP file - // with the plugin's implementation (e.g. 'vendor/phan/phan/.phan/plugins/AlwaysReturnPlugin.php') - 'ParamMatchRegexPlugin' => [ - '/^isModEnabled$/' => [0, $deprecatedModuleNameRegex, "DeprecatedModuleName"], - ], - 'plugins' => [ - __DIR__.'/plugins/ParamMatchRegexPlugin.php', - 'DeprecateAliasPlugin', - // __DIR__.'/plugins/NoVarDumpPlugin.php', - //__DIR__.'/plugins/GetPostFixerPlugin.php', - //'PHPDocToRealTypesPlugin', +// $config['plugins'][] = __DIR__.'/plugins/ParamMatchRegexPlugin.php'; +$config['plugins'][] = 'DeprecateAliasPlugin'; +$config['plugins'][] = 'DeprecateAliasPlugin'; +// $config['plugins'][] = __DIR__.'/plugins/GetPostFixerPlugin.php'; +// $config['plugins'][] = 'PHPDocToRealTypesPlugin'; - /* - //'EmptyMethodAndFunctionPlugin', - 'InvalidVariableIssetPlugin', - //'MoreSpecificElementTypePlugin', - 'NoAssertPlugin', - 'NotFullyQualifiedUsagePlugin', - 'PHPDocRedundantPlugin', - 'PHPUnitNotDeadCodePlugin', - //'PossiblyStaticMethodPlugin', - 'PreferNamespaceUsePlugin', - 'PrintfCheckerPlugin', - 'RedundantAssignmentPlugin', - - 'ConstantVariablePlugin', // Warns about values that are actually constant - //'HasPHPDocPlugin', // Requires PHPDoc - 'InlineHTMLPlugin', // html in PHP file, or at end of file - 'NonBoolBranchPlugin', // Requires test on bool, nont on ints - 'NonBoolInLogicalArithPlugin', - 'NumericalComparisonPlugin', - 'PHPDocToRealTypesPlugin', - 'PHPDocInWrongCommentPlugin', // Missing /** (/* was used) - //'ShortArrayPlugin', // Checks that [] is used - //'StrictLiteralComparisonPlugin', - 'UnknownClassElementAccessPlugin', - 'UnknownElementTypePlugin', - 'WhitespacePlugin', - //'RemoveDebugStatementPlugin', // Reports echo, print, ... - //'StrictComparisonPlugin', // Expects === - 'SuspiciousParamOrderPlugin', - 'UnsafeCodePlugin', - //'UnusedSuppressionPlugin', - - 'AlwaysReturnPlugin', - //'DollarDollarPlugin', - 'DuplicateArrayKeyPlugin', - 'DuplicateExpressionPlugin', - 'PregRegexCheckerPlugin', - 'PrintfCheckerPlugin', - 'SleepCheckerPlugin', - // Checks for syntactically unreachable statements in - // the global scope or function bodies. - 'UnreachableCodePlugin', - 'UseReturnValuePlugin', - 'EmptyStatementListPlugin', - 'LoopVariableReusePlugin', - */ - ], - - // Add any issue types (such as 'PhanUndeclaredMethod') - // here to inhibit them from being reported - 'suppress_issue_types' => [ - 'PhanCompatibleNegativeStringOffset', // return false positive - - 'PhanPluginWhitespaceTab', // Dolibarr used tabs - 'PhanPluginCanUsePHP71Void', // Dolibarr is maintaining 7.0 compatibility - 'PhanPluginShortArray', // Dolibarr uses array() - 'PhanPluginShortArrayList', // Dolibarr uses array() - // The following may require that --quick is not used - // Fixers From PHPDocToRealTypesPlugin: - 'PhanPluginCanUseParamType', // Fixer - Report/Add types in the function definition (function abc(string $var) (adds string) - 'PhanPluginCanUseReturnType', // Fixer - Report/Add return types in the function definition (function abc(string $var) (adds string) - 'PhanPluginCanUseNullableParamType', // Fixer - Report/Add nullable parameter types in the function definition - 'PhanPluginCanUseNullableReturnType', // Fixer - Report/Add nullable return types in the function definition - - 'PhanPluginNonBoolBranch', // Not essential - 31240+ occurrences - 'PhanPluginNumericalComparison', // Not essential - 19870+ occurrences - 'PhanTypeMismatchArgument', // Not essential - 12300+ occurrences - 'PhanPluginNonBoolInLogicalArith', // Not essential - 11040+ occurrences - 'PhanPluginConstantVariableScalar', // Not essential - 5180+ occurrences - 'PhanPluginDuplicateAdjacentStatement', - 'PhanPluginDuplicateConditionalTernaryDuplication', // 2750+ occurrences - 'PhanPluginDuplicateConditionalNullCoalescing', // Not essential - 990+ occurrences - 'PhanPluginRedundantAssignmentInGlobalScope', // Not essential, a lot of false warning - ], - // You can put relative paths to internal stubs in this config option. - // Phan will continue using its detailed type annotations, - // but load the constants, classes, functions, and classes (and their Reflection types) - // from these stub files (doubling as valid php files). - // Use a different extension from php (and preferably a separate folder) - // to avoid accidentally parsing these as PHP (includes projects depending on this). - // The 'mkstubs' script can be used to generate your own stubs (compatible with php 7.0+ right now) - // Note: The array key must be the same as the extension name reported by `php -m`, - // so that phan can skip loading the stubs if the extension is actually available. - 'autoload_internal_extension_signatures' => [ - // Stubs may be available at https://github.com/JetBrains/phpstorm-stubs/tree/master - - // Xdebug stubs are bundled with Phan 0.10.1+/0.8.9+ for usage, - // because Phan disables xdebug by default. - //'xdebug' => 'vendor/phan/phan/.phan/internal_stubs/xdebug.phan_php', - //'memcached' => PHAN_DIR . '/your_internal_stubs_folder_name/memcached.phan_php', - //'PDO' => PHAN_DIR . '/stubs/PDO.phan_php', - 'brotli' => PHAN_DIR . '/stubs/brotli.phan_php', - 'curl' => PHAN_DIR . '/stubs/curl.phan_php', - 'calendar' => PHAN_DIR . '/stubs/calendar.phan_php', - 'fileinfo' => PHAN_DIR . '/stubs/fileinfo.phan_php', - 'ftp' => PHAN_DIR . '/stubs/ftp.phan_php', - 'gd' => PHAN_DIR . '/stubs/gd.phan_php', - 'geoip' => PHAN_DIR . '/stubs/geoip.phan_php', - 'imap' => PHAN_DIR . '/stubs/imap.phan_php', - 'imagick' => PHAN_DIR . '/stubs/imagick.phan_php', - 'intl' => PHAN_DIR . '/stubs/intl.phan_php', - 'ldap' => PHAN_DIR . '/stubs/ldap.phan_php', - 'mcrypt' => PHAN_DIR . '/stubs/mcrypt.phan_php', - 'memcache' => PHAN_DIR . '/stubs/memcache.phan_php', - 'memcached' => PHAN_DIR . '/stubs/memcached.phan_php', - 'mysqli' => PHAN_DIR . '/stubs/mysqli.phan_php', - 'pdo_cubrid' => PHAN_DIR . '/stubs/pdo_cubrid.phan_php', - 'pdo_mysql' => PHAN_DIR . '/stubs/pdo_mysql.phan_php', - 'pdo_pgsql' => PHAN_DIR . '/stubs/pdo_pgsql.phan_php', - 'pdo_sqlite' => PHAN_DIR . '/stubs/pdo_sqlite.phan_php', - 'pgsql' => PHAN_DIR . '/stubs/pgsql.phan_php', - 'session' => PHAN_DIR . '/stubs/session.phan_php', - 'simplexml' => PHAN_DIR . '/stubs/SimpleXML.phan_php', - 'soap' => PHAN_DIR . '/stubs/soap.phan_php', - 'tidy' => PHAN_DIR . '/stubs/tidy.phan_php', - 'sockets' => PHAN_DIR . '/stubs/sockets.phan_php', - 'zip' => PHAN_DIR . '/stubs/zip.phan_php', - ], - - ]; +return $config; From a30bf48e1676afd86199e62b73a108f161be064f Mon Sep 17 00:00:00 2001 From: MDW Date: Tue, 26 Mar 2024 01:14:55 +0100 Subject: [PATCH 28/36] Improve phpdoc typing --- htdocs/core/lib/functions.lib.php | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index b258dc47d5d..49fffa7be7c 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -642,8 +642,8 @@ function GETPOSTISSET($paramname) * Return true if the parameter $paramname is submit from a POST OR GET as an array. * Can be used before GETPOST to know if the $check param of GETPOST need to check an array or a string * - * @param string $paramname Name or parameter to test - * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get) + * @param string $paramname Name or parameter to test + * @param int<0,3> $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get) * @return bool True if we have just submit a POST or GET request with the parameter provided (even if param is empty) */ function GETPOSTISARRAY($paramname, $method = 0) @@ -1011,9 +1011,9 @@ function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder'] * Note: The property $user->default_values is loaded by main.php when loading the user. * - * @param string $paramname Name of the $_GET or $_POST parameter - * @param int $method Type of method (0 = $_GET then $_POST, 1 = only $_GET, 2 = only $_POST, 3 = $_POST then $_GET) - * @return int Value converted into integer + * @param string $paramname Name of the $_GET or $_POST parameter + * @param int<0,3> $method Type of method (0 = $_GET then $_POST, 1 = only $_GET, 2 = only $_POST, 3 = $_POST then $_GET) + * @return int Value converted into integer */ function GETPOSTINT($paramname, $method = 0) { @@ -1663,10 +1663,10 @@ function dol_string_nounprintableascii($str, $removetabcrlf = 1) /** * Returns text escaped for inclusion into javascript code * - * @param string $stringtoescape String to escape - * @param int $mode 0=Escape also ' and " into ', 1=Escape ' but not " for usage into 'string', 2=Escape " but not ' for usage into "string", 3=Escape ' and " with \ - * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n. - * @return string Escaped string. Both ' and " are escaped into ' if they are escaped. + * @param string $stringtoescape String to escape + * @param int<0,3> $mode 0=Escape also ' and " into ', 1=Escape ' but not " for usage into 'string', 2=Escape " but not ' for usage into "string", 3=Escape ' and " with \ + * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n. + * @return string Escaped string. Both ' and " are escaped into ' if they are escaped. */ function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0) { @@ -2420,7 +2420,7 @@ function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab /** * Show tab footer of a card * - * @param int $notab -1 or 0=Add tab footer, 1=no tab footer + * @param int<-1,1> $notab -1 or 0=Add tab footer, 1=no tab footer * @return void * @deprecated Use print dol_get_fiche_end() instead */ @@ -2432,7 +2432,7 @@ function dol_fiche_end($notab = 0) /** * Return tab footer of a card * - * @param int $notab -1 or 0=Add tab footer, 1=no tab footer + * @param int<-1,1> $notab -1 or 0=Add tab footer, 1=no tab footer * @return string */ function dol_get_fiche_end($notab = 0) From 6e5841b13dc76288735bab684242989235af7275 Mon Sep 17 00:00:00 2001 From: MDW Date: Tue, 26 Mar 2024 01:21:07 +0100 Subject: [PATCH 29/36] Add checks on checkVal, price2num and GETPOSTFLOAT arguments --- dev/tools/phan/config.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/dev/tools/phan/config.php b/dev/tools/phan/config.php index c70f6dd5058..92760bd48d5 100644 --- a/dev/tools/phan/config.php +++ b/dev/tools/phan/config.php @@ -350,10 +350,13 @@ return [ // Note: trick to have different key for same regex: '/^isModEnable[d]$/' => [0, $deprecatedModuleNameRegex, "DeprecatedModuleName"], '/^sanitizeVal$/' => [1, $sanitizeRegex,"UnknownSanitizeType"], + '/^checkVal$/' => [1, $sanitizeRegex,"UnknownCheckValSanitizeType"], '/^\\\\ExtraFields::addExtraField$/' => [2, $extraFieldTypeRegex,"UnknownExtrafieldTypeBack"], '/^dol_now$/' => [0, '{^(?:auto|gmt|tz(?:server|ref|user(?:rel)?))$}',"InvalidDolNowArgument"], // '', 0, 1 match bool and int values '/^dol_mktime$/' => [6, '{^(?:|0|1|auto|gmt|tz(?:server|ref|user(?:rel)?|,[+a-zA-Z-/]+))$}',"InvalidDolMktimeArgument"], // '', 0, 1 match bool and int values '/^dol_print_date$/' => [2, '{^(?:|0|1|auto|gmt|tz(?:server|user(?:rel)?))$}',"InvalidDolMktimeArgument"], + '/^GETPOSTFLOAT$/' => [1, '{^(?:|M[UTS]|C[UT]|\d+)$}',"InvalidGetPostFloatRounding"], + '/^price2num$/' => [1, '{^(?:|M[UTS]|C[UT]|\d+)$}',"InvalidPrice2NumRounding"], ], 'plugins' => [ __DIR__.'/plugins/NoVarDumpPlugin.php', From 1c9c665b0b208c5613c1718166971fe4aa873670 Mon Sep 17 00:00:00 2001 From: MDW Date: Tue, 26 Mar 2024 01:42:24 +0100 Subject: [PATCH 30/36] Update baseline (improved) --- dev/tools/phan/baseline.txt | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/dev/tools/phan/baseline.txt b/dev/tools/phan/baseline.txt index 46d02c0404f..6fa9139c750 100644 --- a/dev/tools/phan/baseline.txt +++ b/dev/tools/phan/baseline.txt @@ -9,24 +9,21 @@ */ return [ // # Issue statistics: - // PhanParamSignatureMismatch : 25+ occurrences + // PhanParamSignatureMismatch : 20+ occurrences // PhanPluginSuspiciousParamPosition : 15+ occurrences // PhanUndeclaredConstant : 15+ occurrences // PhanPluginDuplicateExpressionBinaryOp : 10+ occurrences - // PhanTypeMismatchReturn : 8 occurrences - // PhanRedefineFunctionInternal : 6 occurrences - // PhanTypeArraySuspiciousNull : 6 occurrences + // PhanTypeMismatchReturn : 5 occurrences // PhanParamTooMany : 4 occurrences - // PhanTypeMismatchReturnNullable : 3 occurrences // PhanAccessMethodProtected : 1 occurrence // PhanAccessPropertyStaticAsNonStatic : 1 occurrence // PhanNoopStringLiteral : 1 occurrence + // PhanTypeArraySuspiciousNull : 1 occurrence // Currently, file_suppressions and directory_suppressions are the only supported suppressions 'file_suppressions' => [ 'htdocs/adherents/admin/member.php' => ['PhanParamTooMany'], 'htdocs/adherents/type.php' => ['PhanPluginDuplicateExpressionBinaryOp'], - 'htdocs/admin/receiptprinter.php' => ['PhanRedefineFunctionInternal'], 'htdocs/api/class/api_documents.class.php' => ['PhanPluginDuplicateExpressionBinaryOp'], 'htdocs/barcode/printsheet.php' => ['PhanPluginDuplicateExpressionBinaryOp'], 'htdocs/categories/class/api_categories.class.php' => ['PhanAccessMethodProtected'], @@ -36,23 +33,15 @@ return [ 'htdocs/compta/cashcontrol/cashcontrol_card.php' => ['PhanPluginDuplicateExpressionBinaryOp'], 'htdocs/compta/prelevement/class/bonprelevement.class.php' => ['PhanParamTooMany'], 'htdocs/compta/prelevement/create.php' => ['PhanPluginSuspiciousParamPosition'], - 'htdocs/core/class/commondocgenerator.class.php' => ['PhanTypeArraySuspiciousNull'], - 'htdocs/core/class/commonobject.class.php' => ['PhanTypeMismatchReturnNullable'], - 'htdocs/core/class/extrafields.class.php' => ['PhanTypeMismatchReturnNullable'], 'htdocs/core/class/html.form.class.php' => ['PhanPluginSuspiciousParamPosition'], 'htdocs/core/db/mysqli.class.php' => ['PhanParamSignatureMismatch'], 'htdocs/core/db/pgsql.class.php' => ['PhanParamSignatureMismatch'], - 'htdocs/core/db/sqlite3.class.php' => ['PhanParamSignatureMismatch', 'PhanTypeMismatchReturnNullable'], + 'htdocs/core/db/sqlite3.class.php' => ['PhanParamSignatureMismatch'], 'htdocs/core/get_info.php' => ['PhanPluginSuspiciousParamPosition'], 'htdocs/core/lib/files.lib.php' => ['PhanPluginDuplicateExpressionBinaryOp'], - 'htdocs/core/lib/functions.lib.php' => ['PhanParamTooMany', 'PhanRedefineFunctionInternal'], 'htdocs/core/lib/price.lib.php' => ['PhanPluginSuspiciousParamPosition'], 'htdocs/core/modules/movement/doc/pdf_standard.modules.php' => ['PhanPluginDuplicateExpressionBinaryOp'], - 'htdocs/core/modules/mrp/doc/pdf_vinci.modules.php' => ['PhanTypeArraySuspiciousNull', 'PhanTypeInvalidRightOperandOfAdd'], - 'htdocs/core/modules/syslog/mod_syslog_file.php' => ['PhanParamSignatureMismatch'], - 'htdocs/core/modules/syslog/mod_syslog_syslog.php' => ['PhanParamSignatureMismatch'], 'htdocs/don/class/don.class.php' => ['PhanParamTooMany'], - 'htdocs/expedition/class/api_shipments.class.php' => ['PhanTypeMismatchReturn'], 'htdocs/expensereport/class/api_expensereports.class.php' => ['PhanTypeMismatchReturn'], 'htdocs/fourn/class/fournisseur.commande.class.php' => ['PhanTypeMismatchReturn'], 'htdocs/fourn/class/fournisseur.facture.class.php' => ['PhanTypeMismatchReturn'], From 24e48998cec40b7151271afe7fdac1623a1367d9 Mon Sep 17 00:00:00 2001 From: MDW Date: Tue, 26 Mar 2024 11:32:50 +0100 Subject: [PATCH 31/36] Add nempty to spelling --- dev/tools/codespell/codespell-dict.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/dev/tools/codespell/codespell-dict.txt b/dev/tools/codespell/codespell-dict.txt index 1cd7ec6bfb2..32bfa0aa414 100644 --- a/dev/tools/codespell/codespell-dict.txt +++ b/dev/tools/codespell/codespell-dict.txt @@ -18,6 +18,7 @@ dollibarr->dolibarr extrafeild->extrafield thoose->those # fiche->card +nempty->an empty, empty, not empty, mot de passe->password not de passe->password nothtml->nohtml From 25faef6da81fddc205542317d1e92a38f8eb95d8 Mon Sep 17 00:00:00 2001 From: MDW Date: Tue, 26 Mar 2024 11:34:32 +0100 Subject: [PATCH 32/36] Improve typing for arg $showempty --- htdocs/core/class/html.form.class.php | 124 +++++++++++++------------- 1 file changed, 62 insertions(+), 62 deletions(-) diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index e14b020b144..97082b64db2 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -926,7 +926,7 @@ class Form * @param integer $maxlength Max length for labels (0=no limit) * @param string $morecss More css class * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key - * @param int|string $showempty Show empty choice + * @param int<0,1>|string $showempty Show empty choice * @param int $disablefavorites 1=Disable favorites, * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...) * @param array $exclude_country_code Array of country code (iso2) to exclude @@ -1148,7 +1148,7 @@ class Form * * @param string $selected Preselected type * @param string $htmlname Name of field in html form - * @param int $showempty Add an empty field + * @param int<0,1> $showempty Add an empty field * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select) * @param integer $forceall 1=Force to show products and services in combo list, whatever are activated modules, 0=No force, 2=Force to show only Products, 3=Force to show only services, -1=Force none (and set hidden field to 'service') * @return void @@ -1303,7 +1303,7 @@ class Form * @param string $selected Preselected type * @param string $htmlname Name of field in form * @param string $filter Optional filters criteras. WARNING: To avoid SQL injection, only few chars [.a-z0-9 =<>()] are allowed here. Example: ((s.client:IN:1,3) AND (s.status:=:1)). Do not use a filter coming from input of users. - * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty') + * @param string|int<1,1> $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty') * @param int $showtype Show third party type in combolist (customer, prospect or supplier) * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification) * @param array $events Ajax event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) @@ -1381,8 +1381,8 @@ class Form * @param string $filter Optional filters criteras. WARNING: To avoid SQL injection, only few chars [.a-z0-9 =<>] are allowed here, example: 's.rowid <> x' * If you need parenthesis, use the Universal Filter Syntax, example: '(s.client:in:1,3)' * Do not use a filter coming from input of users. - * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty') - * @param int $showtype Show third party type in combolist (customer, prospect or supplier) + * @param string|int<0,1> $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty') + * @param int<0,1> $showtype Show third party type in combolist (customer, prospect or supplier) * @param int $forcecombo Force to use standard HTML select component without beautification * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) * @param string $filterkey Filter on key value @@ -1720,7 +1720,7 @@ class Form * @param int $socid Id of third party or 0 for all * @param string $selected Id of preselected contact * @param string $htmlname Name of HTML field ('none' for a not editable field) - * @param int $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list + * @param int<0,3> $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list * @param string $exclude List of contacts id to exclude * @param string $limitto Disable answers that are not id in this array list * @param integer $showfunction Add function into label @@ -1750,7 +1750,7 @@ class Form * @param int $socid Id of third party or 0 for all or -1 for empty list * @param array|int $selected Array of ID of preselected contact id * @param string $htmlname Name of HTML field ('none' for a not editable field) - * @param int|string $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list + * @param int<0,3>|string $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list * @param string $exclude List of contacts id to exclude * @param string $limitto Disable answers that are not id in this array list * @param integer $showfunction Add function into label @@ -2458,7 +2458,7 @@ class Form * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after) * @param array $ajaxoptions Options for ajax_autocompleter * @param int $socid Thirdparty Id (to get also price dedicated to this customer) - * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. + * @param string|int<0,1> $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. * @param int $forcecombo Force to use combo box * @param string $morecss Add more css on select * @param int $hidepriceinlabel 1=Hide prices in label @@ -2623,7 +2623,7 @@ class Form * @param int $limit Limit on number of returned lines * @param int $status Sell status -1=Return all bom, 0=Draft BOM, 1=Validated BOM * @param int $type type of the BOM (-1=Return all BOM, 0=Return disassemble BOM, 1=Return manufacturing BOM) - * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. + * @param string|int<0,1> $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. * @param string $morecss Add more css on select * @param string $nooutput No print, return the output into a string * @param int $forcecombo Force to use combo box @@ -2709,7 +2709,7 @@ class Form * @param int $finished Filter on finished field: 2=No filter * @param int $outputmode 0=HTML select string, 1=Array * @param int $socid Thirdparty Id (to get also price dedicated to this customer) - * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. + * @param string|int<0,1> $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. * @param int $forcecombo Force to use combo box * @param string $morecss Add more css on select * @param int $hidepriceinlabel 1=Hide prices in label @@ -4838,13 +4838,13 @@ class Form } /** - * Creates HTML units selector (code => label) + * Creates HTML units selector (code => label) * - * @param string $selected Preselected Unit ID - * @param string $htmlname Select name - * @param int $showempty Add a nempty line - * @param string $unit_type Restrict to one given unit type - * @return string HTML select + * @param string $selected Preselected Unit ID + * @param string $htmlname Select name + * @param int<0,1> $showempty Add an empty line + * @param string $unit_type Restrict to one given unit type + * @return string HTML select */ public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '') { @@ -6205,9 +6205,9 @@ class Form * @param string $selected Id preselected * @param string $htmlname Name of HTML select * @param string $filter Optional filters criteras. WARNING: To avoid SQL injection, only few chars [.a-z0-9 =<>()] are allowed here (example: 's.rowid <> x', 's.client IN (1,3)'). Do not use a filter coming from input of users. - * @param int $showempty Add an empty field - * @param int $showtype Show third party type in combolist (customer, prospect or supplier) - * @param int $forcecombo Force to use combo box + * @param string|int<0,1> $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty') + * @param int<0,1> $showtype Show third party type in combolist (customer, prospect or supplier) + * @param int<0,1> $forcecombo Force to use combo box * @param array $events Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled'))) * @param int $nooutput No print output. Return it only. * @param array $excludeids Exclude IDs from the select combo @@ -7355,21 +7355,21 @@ class Form /** * Return list of tickets in Ajax if Ajax activated or go to selectTicketsList * - * @param string $selected Preselected tickets - * @param string $htmlname Name of HTML select field (must be unique in page). - * @param string $filtertype To add a filter - * @param int $limit Limit on number of returned lines - * @param int $status Ticket status - * @param string $selected_input_value Value of preselected input text (for use with ajax) - * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after) - * @param array $ajaxoptions Options for ajax_autocompleter - * @param int $socid Thirdparty Id (to get also price dedicated to this customer) - * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. - * @param int $forcecombo Force to use combo box - * @param string $morecss Add more css on select - * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...]) - * @param int $nooutput No print, return the output into a string - * @return string + * @param string $selected Preselected tickets + * @param string $htmlname Name of HTML select field (must be unique in page). + * @param string $filtertype To add a filter + * @param int $limit Limit on number of returned lines + * @param int $status Ticket status + * @param string $selected_input_value Value of preselected input text (for use with ajax) + * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after) + * @param array $ajaxoptions Options for ajax_autocompleter + * @param int $socid Thirdparty Id (to get also price dedicated to this customer) + * @param string|int<0,1> $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. + * @param int<0,1> $forcecombo Force to use combo box + * @param string $morecss Add more css on select + * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...]) + * @param int $nooutput No print, return the output into a string + * @return string */ public function selectTickets($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 0, $status = 1, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $selected_combinations = null, $nooutput = 0) { @@ -7422,20 +7422,20 @@ class Form /** - * Return list of tickets. + * Return list of tickets. * Called by selectTickets. * - * @param string $selected Preselected ticket - * @param string $htmlname Name of select html - * @param string $filtertype Filter on ticket type - * @param int $limit Limit on number of returned lines - * @param string $filterkey Filter on ticket ref or subject - * @param int $status Ticket status - * @param int $outputmode 0=HTML select string, 1=Array - * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. + * @param string $selected Preselected ticket + * @param string $htmlname Name of select html + * @param string $filtertype Filter on ticket type + * @param int $limit Limit on number of returned lines + * @param string $filterkey Filter on ticket ref or subject + * @param int $status Ticket status + * @param int $outputmode 0=HTML select string, 1=Array + * @param string|int<0,1> $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. * @param int $forcecombo Force to use combo box - * @param string $morecss Add more css on select - * @return array|string Array of keys for json or HTML component + * @param string $morecss Add more css on select + * @return array|string Array of keys for json or HTML component */ public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '') { @@ -7590,7 +7590,7 @@ class Form * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after) * @param array $ajaxoptions Options for ajax_autocompleter * @param int $socid Thirdparty Id (to get also price dedicated to this customer) - * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. + * @param string|int<0,1> $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. * @param int $forcecombo Force to use combo box * @param string $morecss Add more css on select * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...]) @@ -7657,7 +7657,7 @@ class Form * @param string $filterkey Filter on project ref or subject * @param int $status Ticket status * @param int $outputmode 0=HTML select string, 1=Array - * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. + * @param string|int<0,1> $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. * @param int $forcecombo Force to use combo box * @param string $morecss Add more css on select * @return array|string Array of keys for json or HTML component @@ -7819,7 +7819,7 @@ class Form * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon before and placeholder, 3 search icon after) * @param array $ajaxoptions Options for ajax_autocompleter * @param int $socid Thirdparty Id (to get also price dedicated to this customer) - * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. + * @param string|int<0,1> $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. * @param int $forcecombo Force to use combo box * @param string $morecss Add more css on select * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...]) @@ -7889,7 +7889,7 @@ class Form * @param string $filterkey Filter on member status * @param int $status Member status * @param int $outputmode 0=HTML select string, 1=Array - * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. + * @param string|int<0,1> $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text. * @param int $forcecombo Force to use combo box * @param string $morecss Add more css on select * @return array|string Array of keys for json or HTML string component @@ -8042,18 +8042,18 @@ class Form * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup. * This is the generic method that will replace all specific existing methods. * - * @param string $objectdesc 'ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'. For hard coded custom needs. Try to prefer method using $objectfield instead of $objectdesc. - * @param string $htmlname Name of HTML select component - * @param int $preSelectedValue Preselected value (ID of element) - * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...) - * @param string $searchkey Search criteria - * @param string $placeholder Place holder - * @param string $morecss More CSS - * @param string $moreparams More params provided to ajax call - * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification) - * @param int $disabled 1=Html component is disabled - * @param string $selected_input_value Value of preselected input text (for use with ajax) - * @param string $objectfield Object:Field that contains the definition (in table $fields or $extrafields). Example: 'Object:xxx' or 'Module_Object:xxx' or 'Object:options_xxx' or 'Module_Object:options_xxx' + * @param string $objectdesc 'ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'. For hard coded custom needs. Try to prefer method using $objectfield instead of $objectdesc. + * @param string $htmlname Name of HTML select component + * @param int $preSelectedValue Preselected value (ID of element) + * @param string|int<0,1> $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...) + * @param string $searchkey Search criteria + * @param string $placeholder Place holder + * @param string $morecss More CSS + * @param string $moreparams More params provided to ajax call + * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification) + * @param int $disabled 1=Html component is disabled + * @param string $selected_input_value Value of preselected input text (for use with ajax) + * @param string $objectfield Object:Field that contains the definition (in table $fields or $extrafields). Example: 'Object:xxx' or 'Module_Object:xxx' or 'Object:options_xxx' or 'Module_Object:options_xxx' * @return string Return HTML string * @see selectForFormsList(), select_thirdparty_list() */ @@ -8201,7 +8201,7 @@ class Form * @param Object $objecttmp Object to know the table to scan for combo. * @param string $htmlname Name of HTML select component * @param int $preselectedvalue Preselected value (ID of element) - * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...) + * @param string|int<0,1> $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...) * @param string $searchkey Search value * @param string $placeholder Place holder * @param string $morecss More CSS From ceeaf8b53488e3245ea34d3a5ee467f39044274b Mon Sep 17 00:00:00 2001 From: MDW Date: Tue, 26 Mar 2024 11:41:53 +0100 Subject: [PATCH 33/36] Be less restrictive on links index (for phpstan) --- htdocs/core/lib/functions.lib.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 49fffa7be7c..33fba3f8641 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -2220,7 +2220,7 @@ function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0 /** * Show tabs of a record * - * @param array,string>> $links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped. + * @param array> $links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped. * @param string $active Active tab name * @param string $title Title * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no separation under tab (to start a tab just after), -3=-2+'noborderbottom' From f41d21407fb6dd0141e10ad13cab6923e1f440c2 Mon Sep 17 00:00:00 2001 From: MDW Date: Tue, 26 Mar 2024 12:11:42 +0100 Subject: [PATCH 34/36] Fix typing for $links arg in dol_fiche_head() --- htdocs/core/lib/functions.lib.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 33fba3f8641..d58ee238e15 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -2220,7 +2220,7 @@ function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0 /** * Show tabs of a record * - * @param array> $links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped. + * @param array,string>> $links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped. * @param string $active Active tab name * @param string $title Title * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no separation under tab (to start a tab just after), -3=-2+'noborderbottom' From c0fd71f922095b0601d80f3ac11c4da16c285dc4 Mon Sep 17 00:00:00 2001 From: MDW Date: Tue, 26 Mar 2024 14:29:44 +0100 Subject: [PATCH 35/36] PHPdoc - correct return type for countMembersByTypeAndStatus --- htdocs/adherents/class/adherentstats.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/adherents/class/adherentstats.class.php b/htdocs/adherents/class/adherentstats.class.php index 612f408edd9..3417d97eec7 100644 --- a/htdocs/adherents/class/adherentstats.class.php +++ b/htdocs/adherents/class/adherentstats.class.php @@ -170,7 +170,7 @@ class AdherentStats extends Stats * Return count of member by status group by adh type, total and average * * @param int $numberYears Number of years to scan (0 = all) - * @return array Array with total of draft, pending, uptodate, expired, resiliated for each member type + * @return array Array with total of draft, pending, uptodate, expired, resiliated for each member type */ public function countMembersByTypeAndStatus($numberYears = 0) { From ebb4c2111acccdafdf21202e3fc6b90c4db4c36d Mon Sep 17 00:00:00 2001 From: MDW Date: Tue, 26 Mar 2024 14:40:42 +0100 Subject: [PATCH 36/36] Improve gender, admin, entity typing --- htdocs/user/class/user.class.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/htdocs/user/class/user.class.php b/htdocs/user/class/user.class.php index 2bbbb39519f..40d316d9ebc 100644 --- a/htdocs/user/class/user.class.php +++ b/htdocs/user/class/user.class.php @@ -11,9 +11,9 @@ * Copyright (C) 2013-2015 Alexandre Spangaro * Copyright (C) 2015 Marcos García * Copyright (C) 2018 charlene Benke - * Copyright (C) 2018-2021 Nicolas ZABOURI - * Copyright (C) 2019-2024 Frédéric France - * Copyright (C) 2019 Abbes Bahfir + * Copyright (C) 2018-2021 Nicolas ZABOURI + * Copyright (C) 2019-2024 Frédéric France + * Copyright (C) 2019 Abbes Bahfir * Copyright (C) 2024 MDW * * This program is free software; you can redistribute it and/or modify @@ -112,7 +112,7 @@ class User extends CommonObject public $fullname; /** - * @var string gender + * @var string|int<-1,-1> gender (man|woman|other) */ public $gender; @@ -337,7 +337,7 @@ class User extends CommonObject public $lastsearch_values; // To store last saved search criteria for user /** - * @var array|array Array of User (filled from fetchAll) or Array with hierarchy of user information (filled with get_full_tree() + * @var array|array,admin:int<0,1>,photo:string,fullpath:string,fullname:string,level:int}> Array of User (filled from fetchAll) or Array with hierarchy of user information (filled with get_full_tree() */ public $users = array(); public $parentof; // To store an array of all parents for all ids. @@ -1745,7 +1745,7 @@ class User extends CommonObject $this->civility_code = $contact->civility_code; $this->lastname = $contact->lastname; $this->firstname = $contact->firstname; - //$this->gender = $contact->gender; // contact ha sno gender + //$this->gender = $contact->gender; // contact has no gender $this->email = $contact->email; $this->socialnetworks = $contact->socialnetworks; $this->office_phone = $contact->phone_pro; @@ -2067,7 +2067,7 @@ class User extends CommonObject $sql .= ", employee = ".(int) $this->employee; $sql .= ", login = '".$this->db->escape($this->login)."'"; $sql .= ", api_key = ".($this->api_key ? "'".$this->db->escape(dolEncrypt($this->api_key, '', '', 'dolibarr'))."'" : "null"); - $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman' + $sql .= ", gender = ".($this->gender != -1 ? "'".$this->db->escape($this->gender)."'" : "null"); // 'man' or 'woman' or 'other' $sql .= ", birth=".(strval($this->birth) != '' ? "'".$this->db->idate($this->birth, 'tzserver')."'" : 'null'); if (!empty($user->admin)) { $sql .= ", admin = ".(int) $this->admin; // admin flag can be set/unset only by an admin user @@ -3706,7 +3706,7 @@ class User extends CommonObject * * @param int $deleteafterid Removed all users including the leaf $deleteafterid (and all its child) in user tree. * @param string $filter SQL filter on users. This parameter must not come from user input. - * @return int<-1,-1>|array Array of user information (also: $this->users). Note: $this->parentof is also set. + * @return int<-1,-1>|array,admin:int<0,1>,photo:string,fullpath:string,fullname:string,level:int}> Array of user information (also: $this->users). Note: $this->parentof is also set. */ public function get_full_tree($deleteafterid = 0, $filter = '') {