From ea9f9c5bee87325947ec0db1d68a99fcfe9bbe3f Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 29 Jan 2024 11:30:58 +0100 Subject: [PATCH 01/28] Qual: Make phpcs messages in pre-commit extractable. # Qual: Make phpcs messages in pre-commit extractable. To make messages extractable for annotation when phpcs is run in pre-commit, change the report style to emacs. Also had to update logToCs.py. Using checkstyle directly as an option would not make the output readable when pre-commit is run from the CLI, on commit. --- .github/logToCs.py | 207 ++++++++++++++++++++++++++++++++++++---- .pre-commit-config.yaml | 4 +- 2 files changed, 191 insertions(+), 20 deletions(-) diff --git a/.github/logToCs.py b/.github/logToCs.py index d08628cef84..7befd310a0a 100755 --- a/.github/logToCs.py +++ b/.github/logToCs.py @@ -47,6 +47,8 @@ License: MIT License """ import argparse +import datetime as dt +import json import os import re import sys @@ -64,27 +66,149 @@ def remove_prefix(string, prefix): return string -def convert_to_checkstyle(messages, root_path=None): +def convert_notices_to_checkstyle(notices, root_path=None): """ - Convert provided message to CheckStyle format. + Convert annotation list to CheckStyle xml string """ root = ET.Element("checkstyle") - for message in messages: - fields = parse_message(message) - if fields: - add_error_entry(root, **fields, root_path=root_path) + for fields in notices: + add_error_entry(root, **fields, root_path=root_path) return ET.tostring(root, encoding="utf_8").decode("utf_8") -def convert_text_to_checkstyle(text, root_path=None): +def convert_lines_to_notices(lines): """ Convert provided message to CheckStyle format. """ - root = ET.Element("checkstyle") - for fields in parse_file(text): + notices = [] + for line in lines: + fields = parse_message(line) if fields: - add_error_entry(root, **fields, root_path=root_path) - return ET.tostring(root, encoding="utf_8").decode("utf_8") + notices.append(fields) + return notices + + +def convert_text_to_notices(text): + """ + Convert provided message to CheckStyle format. + """ + return parse_file(text) + + +# Initial version for Checkrun from: +# https://github.com/tayfun/flake8-your-pr/blob/50a175cde4dd26a656734c5b64ba1e5bb27151cb/src/main.py#L7C1-L123C36 +# MIT Licence +class CheckRun: + """ + Represents the check run + """ + + GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN", None) + GITHUB_EVENT_PATH = os.environ.get("GITHUB_EVENT_PATH", None) + + URI = "https://api.github.com" + API_VERSION = "2022-11-28" + ACCEPT_HEADER_VALUE = "application/vnd.github+json" + AUTH_HEADER_VALUE = f"Bearer {GITHUB_TOKEN}" + # This is the max annotations Github API accepts in one go. + MAX_ANNOTATIONS = 50 + + def __init__(self): + """ + Initialise Check Run object with information from checkrun + """ + self.read_event_file() + self.read_meta_data() + + def read_event_file(self): + """ + Read the event file to get the event information later. + """ + if self.GITHUB_EVENT_PATH is None: + raise ValueError("Not running in github workflow") + with open(self.GITHUB_EVENT_PATH, encoding="utf_8") as event_file: + self.event = json.loads(event_file.read()) + + def read_meta_data(self): + """ + Get meta data from event information + """ + self.repo_full_name = self.event["repository"]["full_name"] + pull_request = self.event.get("pull_request") + print("%r", self.event) + if pull_request: + self.head_sha = pull_request["head"]["sha"] + else: + print("%r", self.event) + check_suite = self.event.get("check_suite", None) + if check_suite is not None: + self.head_sha = check_suite["pull_requests"][0]["base"]["sha"] + else: + self.head_sha = None # Can't annotate? + + def submit( # pylint: disable=too-many-arguments + self, + notices, + title=None, + summary=None, + text=None, + conclusion=None, + ): + """ + Submit annotations to github + + See: + https://docs.github.com/en/rest/checks/runs?apiVersion=2022-11-28 + #update-a-check-run + + :param conclusion: success, failure + """ + # pylint: disable=import-outside-toplevel + import requests # Import here to not impose presence of module + + if self.head_sha is None: + return + + output = { + "annotations": notices[: CheckRun.MAX_ANNOTATIONS], + } + if title is not None: + output["title"] = title + if summary is not None: + output["summary"] = summary + if text is not None: + output["text"] = text + if conclusion is None: + # action_required, cancelled, failure, neutral, success + # skipped, stale, timed_out + if bool(notices): + conclusion = "failure" + else: + conclusion = "success" + + payload = { + "name": "log-to-pr-annotation", + "head_sha": self.head_sha, + "status": "completed", # queued, in_progress, completed + "conclusion": conclusion, + # "started_at": dt.datetime.now(dt.timezone.utc).isoformat(), + "completed_at": dt.datetime.now(dt.timezone.utc).isoformat(), + "output": output, + } + + # Create the check-run + response = requests.post( + f"{self.URI}/repos/{self.repo_full_name}/check-runs", + headers={ + "Accept": self.ACCEPT_HEADER_VALUE, + "Authorization": self.AUTH_HEADER_VALUE, + "X-GitHub-Api-Version": self.API_VERSION, + }, + json=payload, + timeout=30, + ) + print(response.content) + response.raise_for_status() ANY_REGEX = r".*?" @@ -123,6 +247,12 @@ PATTERNS = [ re.compile(r"^##(?P\[endgroup\])$"), # End file group # File socks4echo.sh: error: indent/outdent mismatch: -2. re.compile(f"^File {FILE_REGEX}:{SEVERITY_REGEX}: {MSG_REGEX}$"), + # Emacs style + # path/to/file:845:5: error - Expected 1 space after closing brace + re.compile( + rf"^{FILE_REGEX}:{LINE_REGEX}:{COLUMN_REGEX}:{SEVERITY_REGEX}" + rf"-?\s{MSG_REGEX}$" + ), # ESLint (JavaScript Linter), RoboCop, shellcheck # path/to/file.js:10:2: Some linting issue # path/to/file.rb:10:5: Style/Indentation: Incorrect indentation detected @@ -162,6 +292,23 @@ PATTERNS = [ ), ] +# Exceptionnaly some regexes match messages that are not error. +# This pattern matches those exceptions +EXCLUDE_MSG_PATTERN = re.compile( + r"^(" + r"Placeholder pattern" # To remove on first message pattern + r")" +) + +# Exceptionnaly some regexes match messages that are not error. +# This pattern matches those exceptions +EXCLUDE_FILE_PATTERN = re.compile( + r"^(" + # Codespell: (appears as a file name): + r"Used config files\b" + r")" +) + # Severities available in CodeSniffer report format SEVERITY_NOTICE = "notice" SEVERITY_WARNING = "warning" @@ -181,7 +328,7 @@ def parse_file(text): Returns the fields in a dict. """ - # pylint: disable=too-many-branches + # pylint: disable=too-many-branches,too-many-statements # regex required to allow same group names try: import regex # pylint: disable=import-outside-toplevel @@ -198,7 +345,7 @@ def parse_file(text): results = [] for fields in regex.finditer( - full_regex, strip_ansi(text), regex.MULTILINE + full_regex, strip_ansi(text), regex.MULTILINE | regex.IGNORECASE ): if not fields: continue @@ -212,6 +359,7 @@ def parse_file(text): confidence = result.pop("confidence", None) new_file_group = result.pop("file_group", None) file_endgroup = result.pop("file_endgroup", None) + message = result.get("message", None) if new_file_group is not None: # Start of file_group, just store file @@ -229,6 +377,15 @@ def parse_file(text): else: # No filename, skip continue + else: + if EXCLUDE_FILE_PATTERN.search(file_name): + # This file_name is excluded + continue + + if message is not None: + if EXCLUDE_MSG_PATTERN.search(message): + # This message is excluded + continue if confidence is not None: # Convert confidence level of cpplint @@ -264,7 +421,7 @@ def parse_message(message): Returns the fields in a dict. """ for pattern in PATTERNS: - fields = pattern.match(message) + fields = pattern.match(message, re.IGNORECASE) if not fields: continue result = fields.groupdict() @@ -378,6 +535,14 @@ def main(): " Defaults to working directory.", default=os.getcwd(), ) + parser.add_argument( + "--github-annotate", + action=argparse.BooleanOptionalAction, + help="Annotate when in Github workflow.", + # Currently disabled, + # Future: (os.environ.get("GITHUB_EVENT_PATH", None) is not None), + default=False, + ) args = parser.parse_args() @@ -397,11 +562,13 @@ def main(): root_path = os.path.join(args.root, "") try: - checkstyle_xml = convert_text_to_checkstyle(text, root_path=root_path) + notices = convert_text_to_notices(text) except ImportError: - checkstyle_xml = convert_to_checkstyle( - re.split(r"[\r\n]+", text), root_path=root_path - ) + notices = convert_lines_to_notices(re.split(r"[\r\n]+", text)) + + checkstyle_xml = convert_notices_to_checkstyle( + notices, root_path=root_path + ) if args.output == "-" and args.output_named: with open(args.output_named, "w", encoding="utf_8") as output_file: @@ -412,6 +579,10 @@ def main(): else: print(checkstyle_xml) + if args.github_annotate: + checkrun = CheckRun() + checkrun.submit(notices) + if __name__ == "__main__": main() diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 81159f37bed..8376ee6917f 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -57,10 +57,10 @@ repos: hooks: - id: php-cbf files: \.(php)$ - args: [--standard=dev/setup/codesniffer/ruleset.xml -p] + args: [--standard=dev/setup/codesniffer/ruleset.xml] - id: php-cs files: \.(php)$ - args: [--standard=dev/setup/codesniffer/ruleset.xml -p] + args: [--standard=dev/setup/codesniffer/ruleset.xml,--report=emacs] - id: php-lint # Prettier (format code, only for non common files) From 49b21b9cbe16ed015c091e134ef0104c720dbe8a Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 29 Jan 2024 14:05:25 +0100 Subject: [PATCH 02/28] Fix: Typing hint for hasRights parameter. # Fix: Typing hint for hasRights parameter. Correct typing hint for static tools --- htdocs/user/class/user.class.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/user/class/user.class.php b/htdocs/user/class/user.class.php index 3274171423e..7b59b1f4375 100644 --- a/htdocs/user/class/user.class.php +++ b/htdocs/user/class/user.class.php @@ -14,6 +14,7 @@ * Copyright (C) 2018-2021 Nicolas ZABOURI * Copyright (C) 2019-2023 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 * it under the terms of the GNU General Public License as published by @@ -750,7 +751,7 @@ class User extends CommonObject * You can use it like this: if ($user->hasRight('module', 'level11')). * It replaces old syntax: if ($user->rights->module->level1) * - * @param int $module Module of permission to check + * @param string $module Module of permission to check * @param string $permlevel1 Permission level1 (Example: 'read', 'write', 'delete') * @param string $permlevel2 Permission level2 * @return int 1 if user has permission, 0 if not. From d13d931e2a0d60af4321b787362140f8d18c125f Mon Sep 17 00:00:00 2001 From: thibdrev Date: Mon, 29 Jan 2024 17:39:19 +0100 Subject: [PATCH 03/28] qual: phpstan for htdocs/expedition/card.php htdocs/expedition/card.php 614 Property CommonObjectLine::$id (int) does not accept array|string. htdocs/expedition/card.php 760 Property CommonObjectLine::$id (int) does not accept array|string. htdocs/expedition/card.php 761 Property ExpeditionLigne::$entrepot_id (int) does not accept array|string. htdocs/expedition/card.php 762 Property ExpeditionLigne::$qty (float) does not accept array|string. htdocs/expedition/card.php 773 Property CommonObjectLine::$id (int) does not accept array|string. htdocs/expedition/card.php 774 Property ExpeditionLigne::$entrepot_id (int) does not accept array|string. htdocs/expedition/card.php 775 Property ExpeditionLigne::$qty (float) does not accept array|string. htdocs/expedition/card.php 791 Property ExpeditionLigne::$entrepot_id (int) does not accept array|string. htdocs/expedition/card.php 792 Property ExpeditionLigne::$qty (float) does not accept array|string. htdocs/expedition/card.php 806 Property CommonObjectLine::$id (int) does not accept array|string. htdocs/expedition/card.php 807 Property ExpeditionLigne::$qty (float) does not accept array|string. htdocs/expedition/card.php 820 Property CommonObjectLine::$id (int) does not accept array|string. htdocs/expedition/card.php 821 Property ExpeditionLigne::$qty (float) does not accept array|string. --- htdocs/expedition/card.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/htdocs/expedition/card.php b/htdocs/expedition/card.php index 053424b9e25..decb5ab0cf3 100644 --- a/htdocs/expedition/card.php +++ b/htdocs/expedition/card.php @@ -83,7 +83,7 @@ if (empty($origin_id)) { $origin_id = GETPOST('object_id', 'int'); // Id of order or propal } $ref = GETPOST('ref', 'alpha'); -$line_id = GETPOST('lineid', 'int') ? GETPOST('lineid', 'int') : ''; +$line_id = GETPOSTINT('lineid'); $facid = GETPOST('facid', 'int'); $action = GETPOST('action', 'alpha'); @@ -771,8 +771,8 @@ if (empty($reshook)) { $stockLocation = "entl".$line_id; $qty = "qtyl".$line_id; $line->id = $line_id; - $line->entrepot_id = GETPOST($stockLocation, 'int'); - $line->qty = GETPOST($qty, 'int'); + $line->entrepot_id = GETPOSTINT($stockLocation); + $line->qty = GETPOSTFLOAT($qty); if ($line->update($user) < 0) { setEventMessages($line->error, $line->errors, 'errors'); $error++; @@ -785,11 +785,11 @@ if (empty($reshook)) { if (!$error) { $stockLocation = "entl".$detail_entrepot->line_id; $qty = "qtyl".$detail_entrepot->line_id; - $warehouse = GETPOST($stockLocation, 'int'); + $warehouse = GETPOSTINT($stockLocation); if (!empty($warehouse)) { $line->id = $detail_entrepot->line_id; $line->entrepot_id = $warehouse; - $line->qty = GETPOST($qty, 'int'); + $line->qty = GETPOSTFLOAT($qty); if ($line->update($user) < 0) { setEventMessages($line->error, $line->errors, 'errors'); $error++; @@ -804,7 +804,7 @@ if (empty($reshook)) { } elseif (!isModEnabled('stock') && empty($conf->productbatch->enabled)) { // both product batch and stock are not activated. $qty = "qtyl".$line_id; $line->id = $line_id; - $line->qty = GETPOST($qty, 'int'); + $line->qty = GETPOSTFLOAT($qty); $line->entrepot_id = 0; if ($line->update($user) < 0) { setEventMessages($line->error, $line->errors, 'errors'); @@ -818,7 +818,7 @@ if (empty($reshook)) { // Product no predefined $qty = "qtyl".$line_id; $line->id = $line_id; - $line->qty = GETPOST($qty, 'int'); + $line->qty = GETPOSTFLOAT($qty); $line->entrepot_id = 0; if ($line->update($user) < 0) { setEventMessages($line->error, $line->errors, 'errors'); From b53c7b5eb52dcda3930a907325cd024c2b89e8b1 Mon Sep 17 00:00:00 2001 From: thibdrev Date: Mon, 29 Jan 2024 17:43:40 +0100 Subject: [PATCH 04/28] qual: phpstan for htdocs/expedition/dispatch.php htdocs/expedition/dispatch.php 216 Property ExpeditionLigne::$qty (float) does not accept string. htdocs/expedition/dispatch.php 217 Property ExpeditionLigne::$entrepot_id (int) does not accept array|string. htdocs/expedition/dispatch.php 274 Property ExpeditionLigne::$entrepot_id (int) does not accept array|string. htdocs/expedition/dispatch.php 275 Property ExpeditionLigne::$fk_origin_line (int) does not accept array|string. htdocs/expedition/dispatch.php 276 Property ExpeditionLigne::$qty (float) does not accept string. --- htdocs/expedition/dispatch.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/htdocs/expedition/dispatch.php b/htdocs/expedition/dispatch.php index 8ba6e6d7768..cc3a31140ee 100644 --- a/htdocs/expedition/dispatch.php +++ b/htdocs/expedition/dispatch.php @@ -160,7 +160,7 @@ if ($action == 'updatelines' && $usercancreate) { $dDLC = dol_mktime(12, 0, 0, GETPOST('dlc_'.$reg[1].'_'.$reg[2].'month', 'int'), GETPOST('dlc_'.$reg[1].'_'.$reg[2].'day', 'int'), GETPOST('dlc_'.$reg[1].'_'.$reg[2].'year', 'int')); } - $newqty = price2num(GETPOST($qty, 'alpha'), 'MS'); + $newqty = GETPOSTFLOAT($qty, 'MS'); //var_dump("modebatch=".$modebatch." newqty=".$newqty." ent=".$ent." idline=".$idline); // We ask to move a qty @@ -214,7 +214,7 @@ if ($action == 'updatelines' && $usercancreate) { } else { $qtystart = $expeditiondispatch->qty; $expeditiondispatch->qty = $newqty; - $expeditiondispatch->entrepot_id = GETPOST($ent, 'int'); + $expeditiondispatch->entrepot_id = GETPOSTINT($ent); if ($newqty > 0) { $result = $expeditiondispatch->update($user); @@ -271,8 +271,8 @@ if ($action == 'updatelines' && $usercancreate) { } } else { $expeditiondispatch->fk_expedition = $object->id; - $expeditiondispatch->entrepot_id = GETPOST($ent, 'int'); - $expeditiondispatch->fk_origin_line = GETPOST($fk_commandedet, 'int'); + $expeditiondispatch->entrepot_id = GETPOSTINT($ent); + $expeditiondispatch->fk_origin_line = GETPOSTINT($fk_commandedet); $expeditiondispatch->qty = $newqty; if ($newqty > 0) { From 2fe5347d66fab42c7f1027f57c4ba943712a1227 Mon Sep 17 00:00:00 2001 From: thibdrev Date: Mon, 29 Jan 2024 18:22:54 +0100 Subject: [PATCH 05/28] qual: phpstan for htdocs/core/lib/functions.lib.php htdocs/core/lib/functions.lib.php 128 Function getMultidirOutput() should return string|void but returns null. htdocs/core/lib/functions.lib.php 9889 Function getLanguageCodeFromCountryCode() should return string but returns null. htdocs/core/lib/functions.lib.php 10105 Function getLanguageCodeFromCountryCode() should return string but returns null. htdocs/core/lib/functions.lib.php 11372 Function roundUpToNextMultiple() should return int but returns float. --- htdocs/core/lib/functions.lib.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 37c95a9574e..6f5ecc7711b 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -117,7 +117,7 @@ if (!function_exists('str_contains')) { * * @param CommonObject $object Dolibarr common object * @param string $module Override object element, for example to use 'mycompany' instead of 'societe' - * @return string|void The path of the relative directory of the module + * @return string|null The path of the relative directory of the module * @since Dolibarr V18 */ function getMultidirOutput($object, $module = '') @@ -9879,7 +9879,7 @@ function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0) * Return null if not found. * * @param string $countrycode Country code like 'US', 'FR', 'CA', 'ES', 'IN', 'MX', ... - * @return string Value of locale like 'en_US', 'fr_FR', ... or null if not found + * @return string|null Value of locale like 'en_US', 'fr_FR', ... or null if not found */ function getLanguageCodeFromCountryCode($countrycode) { @@ -11369,7 +11369,8 @@ function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal */ function roundUpToNextMultiple($n, $x = 5) { - return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x; + $result = (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x; + return (int) $result; } /** From f0cb07837885d371d31bb19bb197293e1c52547e Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 29 Jan 2024 18:31:50 +0100 Subject: [PATCH 06/28] Qual: Fix typing in files.lib Fix several typing hints in files.lib . Fixed some initialisers. Simplified some expressions. Cast some `return $result` statements (could be null). --- htdocs/core/lib/files.lib.php | 102 ++++++++++++++++++---------------- 1 file changed, 53 insertions(+), 49 deletions(-) diff --git a/htdocs/core/lib/files.lib.php b/htdocs/core/lib/files.lib.php index f5d930f26b6..d4af8e1fded 100644 --- a/htdocs/core/lib/files.lib.php +++ b/htdocs/core/lib/files.lib.php @@ -6,6 +6,7 @@ * Copyright (C) 2016 Raphaël Doursenaud * Copyright (C) 2019-2024 Frédéric France * Copyright (C) 2023 Lenin Rivas + * 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 @@ -40,24 +41,24 @@ function dol_basename($pathfile) } /** - * Scan a directory and return a list of files/directories. - * Content for string is UTF8 and dir separator is "/". + * Scan a directory and return a list of files/directories. + * Content for string is UTF8 and dir separator is "/". * - * @param string $path Starting path from which to search. This is a full path. - * @param string $types Can be "directories", "files", or "all" - * @param int $recursive Determines whether subdirectories are searched - * @param string $filter Regex filter to restrict list. This regex value must be escaped for '/' by doing preg_quote($var,'/'), since this char is used for preg_match function, + * @param string $path Starting path from which to search. This is a full path. + * @param string $types Can be "directories", "files", or "all" + * @param int $recursive Determines whether subdirectories are searched + * @param string $filter Regex filter to restrict list. This regex value must be escaped for '/' by doing preg_quote($var,'/'), since this char is used for preg_match function, * but must not contains the start and end '/'. Filter is checked into basename only. - * @param array $excludefilter Array of Regex for exclude filter (example: array('(\.meta|_preview.*\.png)$','^\.')). Exclude is checked both into fullpath and into basename (So '^xxx' may exclude 'xxx/dirscanned/...' and dirscanned/xxx'). - * @param string $sortcriteria Sort criteria ('','fullname','relativename','name','date','size') - * @param int $sortorder Sort order (SORT_ASC, SORT_DESC) - * @param int $mode 0=Return array minimum keys loaded (faster), 1=Force all keys like date and size to be loaded (slower), 2=Force load of date only, 3=Force load of size only, 4=Force load of perm - * @param int $nohook Disable all hooks - * @param string $relativename For recursive purpose only. Must be "" at first call. - * @param int $donotfollowsymlinks Do not follow symbolic links - * @param int $nbsecondsold Only files older than $nbsecondsold - * @return array Array of array('name'=>'xxx','fullname'=>'/abc/xxx','date'=>'yyy','size'=>99,'type'=>'dir|file',...) - * @see dol_dir_list_in_database() + * @param string[] $excludefilter Array of Regex for exclude filter (example: array('(\.meta|_preview.*\.png)$','^\.')). Exclude is checked both into fullpath and into basename (So '^xxx' may exclude 'xxx/dirscanned/...' and dirscanned/xxx'). + * @param string $sortcriteria Sort criteria ('','fullname','relativename','name','date','size') + * @param int $sortorder Sort order (SORT_ASC, SORT_DESC) + * @param int $mode 0=Return array minimum keys loaded (faster), 1=Force all keys like date and size to be loaded (slower), 2=Force load of date only, 3=Force load of size only, 4=Force load of perm + * @param int $nohook Disable all hooks + * @param string $relativename For recursive purpose only. Must be "" at first call. + * @param int $donotfollowsymlinks Do not follow symbolic links + * @param int $nbsecondsold Only files older than $nbsecondsold + * @return array Array of array('name'=>'xxx','fullname'=>'/abc/xxx','date'=>'yyy','size'=>99,'type'=>'dir|file',...) + * @see dol_dir_list_in_database() */ function dol_dir_list($path, $types = "all", $recursive = 0, $filter = "", $excludefilter = null, $sortcriteria = "name", $sortorder = SORT_ASC, $mode = 0, $nohook = 0, $relativename = "", $donotfollowsymlinks = 0, $nbsecondsold = 0) { @@ -69,9 +70,9 @@ function dol_dir_list($path, $types = "all", $recursive = 0, $filter = "", $excl //print 'xxx'."files.lib.php::dol_dir_list path=".$path." types=".$types." recursive=".$recursive." filter=".$filter." excludefilter=".json_encode($excludefilter); } - $loaddate = ($mode == 1 || $mode == 2 || $nbsecondsold) ? true : false; - $loadsize = ($mode == 1 || $mode == 3) ? true : false; - $loadperm = ($mode == 1 || $mode == 4) ? true : false; + $loaddate = ($mode == 1 || $mode == 2 || $nbsecondsold != 0); + $loadsize = ($mode == 1 || $mode == 3); + $loadperm = ($mode == 1 || $mode == 4); // Clean parameters $path = preg_replace('/([\\/]+)$/i', '', $path); @@ -222,17 +223,17 @@ function dol_dir_list($path, $types = "all", $recursive = 0, $filter = "", $excl /** - * Scan a directory and return a list of files/directories. - * Content for string is UTF8 and dir separator is "/". + * Scan a directory and return a list of files/directories. + * Content for string is UTF8 and dir separator is "/". * - * @param string $path Starting path from which to search. Example: 'produit/MYPROD' - * @param string $filter Regex filter to restrict list. This regex value must be escaped for '/', since this char is used for preg_match function - * @param array|null $excludefilter Array of Regex for exclude filter (example: array('(\.meta|_preview.*\.png)$','^\.')) - * @param string $sortcriteria Sort criteria ("","fullname","name","date","size") - * @param string $sortorder Sort order (SORT_ASC, SORT_DESC) - * @param int $mode 0=Return array minimum keys loaded (faster), 1=Force all keys like description - * @return array Array of array('name'=>'xxx','fullname'=>'/abc/xxx','type'=>'dir|file',...) - * @see dol_dir_list() + * @param string $path Starting path from which to search. Example: 'produit/MYPROD' + * @param string $filter Regex filter to restrict list. This regex value must be escaped for '/', since this char is used for preg_match function + * @param string[]|null $excludefilter Array of Regex for exclude filter (example: array('(\.meta|_preview.*\.png)$','^\.')) + * @param string $sortcriteria Sort criteria ("","fullname","name","date","size") + * @param int $sortorder Sort order (SORT_ASC, SORT_DESC) + * @param int $mode 0=Return array minimum keys loaded (faster), 1=Force all keys like description + * @return array Array of array('name'=>'xxx','fullname'=>'/abc/xxx','date'=>'yyy','size'=>99,'type'=>'dir|file',...) + * @see dol_dir_list() */ function dol_dir_list_in_database($path, $filter = "", $excludefilter = null, $sortcriteria = "name", $sortorder = SORT_ASC, $mode = 0) { @@ -308,7 +309,7 @@ function dol_dir_list_in_database($path, $filter = "", $excludefilter = null, $s * Complete $filearray with data from database. * This will call doldir_list_indatabase to complete filearray. * - * @param array $filearray Array of files obtained using dol_dir_list + * @param array $filearray Array of array('name'=>'xxx','fullname'=>'/abc/xxx','date'=>'yyy','size'=>99,'type'=>'dir|file',...) Array of files obtained using dol_dir_list * @param string $relativedir Relative dir from DOL_DATA_ROOT * @return void */ @@ -528,6 +529,7 @@ function dol_dir_is_emtpy($folder) if (is_dir($newfolder)) { $handle = opendir($newfolder); $folder_content = ''; + $name_array = []; while ((gettype($name = readdir($handle)) != "boolean")) { $name_array[] = $name; } @@ -564,8 +566,10 @@ function dol_count_nb_of_line($file) if ($fp) { while (!feof($fp)) { $line = fgets($fp); - // We increase count only if read was success. We need test because feof return true only after fgets so we do n+1 fgets for a file with n lines. - if (!$line === false) { + // Increase count only if read was success. + // Test needed because feof returns true only after fgets + // so we do n+1 fgets for a file with n lines. + if ($line !== false) { $nb++; } } @@ -619,15 +623,15 @@ function dol_fileperm($pathoffile) * Make replacement of strings into a file. * * @param string $srcfile Source file (can't be a directory) - * @param array $arrayreplacement Array with strings to replace. Example: array('valuebefore'=>'valueafter', ...) + * @param array $arrayreplacement Array with strings to replace. Example: array('valuebefore'=>'valueafter', ...) * @param string $destfile Destination file (can't be a directory). If empty, will be same than source file. - * @param int $newmask Mask for new file (0 by default means $conf->global->MAIN_UMASK). Example: '0666' + * @param string $newmask Mask for new file (0 by default means $conf->global->MAIN_UMASK). Example: '0666' * @param int $indexdatabase 1=index new file into database. * @param int $arrayreplacementisregex 1=Array of replacement is already an array with key that is a regex. Warning: the key must be escaped with preg_quote for '/' * @return int Return integer <0 if error, 0 if nothing done (dest file already exists), >0 if OK * @see dol_copy() */ -function dolReplaceInFile($srcfile, $arrayreplacement, $destfile = '', $newmask = 0, $indexdatabase = 0, $arrayreplacementisregex = 0) +function dolReplaceInFile($srcfile, $arrayreplacement, $destfile = '', $newmask = '0', $indexdatabase = 0, $arrayreplacementisregex = 0) { global $conf; @@ -670,7 +674,7 @@ function dolReplaceInFile($srcfile, $arrayreplacement, $destfile = '', $newmask dol_delete_file($tmpdestfile); // Create $newpathoftmpdestfile from $newpathofsrcfile - $content = file_get_contents($newpathofsrcfile, 'r'); + $content = file_get_contents($newpathofsrcfile); if (empty($arrayreplacementisregex)) { $content = make_substitutions($content, $arrayreplacement, null); @@ -708,14 +712,14 @@ function dolReplaceInFile($srcfile, $arrayreplacement, $destfile = '', $newmask * * @param string $srcfile Source file (can't be a directory) * @param string $destfile Destination file (can't be a directory) - * @param int $newmask Mask for new file (0 by default means $conf->global->MAIN_UMASK). Example: '0666' + * @param string $newmask Mask for new file (0 by default means $conf->global->MAIN_UMASK). Example: '0666' * @param int $overwriteifexists Overwrite file if exists (1 by default) * @param int $testvirus Do an antivirus test. Move is canceled if a virus is found. * @param int $indexdatabase Index new file into database. * @return int Return integer <0 if error, 0 if nothing done (dest file already exists and overwriteifexists=0), >0 if OK * @see dol_delete_file() dolCopyDir() */ -function dol_copy($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 0) +function dol_copy($srcfile, $destfile, $newmask = '0', $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 0) { global $db, $user; @@ -827,7 +831,7 @@ function dol_copy($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1, $te } } - return $result; + return (int) $result; } /** @@ -835,11 +839,11 @@ function dol_copy($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1, $te * * @param string $srcfile Source file (a directory) * @param string $destfile Destination file (a directory) - * @param int $newmask Mask for new file (0 by default means $conf->global->MAIN_UMASK). Example: '0666' + * @param string $newmask Mask for new file (0 by default means $conf->global->MAIN_UMASK). Example: '0666' * @param int $overwriteifexists Overwrite file if exists (1 by default) - * @param array $arrayreplacement Array to use to replace filenames with another one during the copy (works only on file names, not on directory names). + * @param array $arrayreplacement Array to use to replace filenames with another one during the copy (works only on file names, not on directory names). * @param int $excludesubdir 0=Do not exclude subdirectories, 1=Exclude subdirectories, 2=Exclude subdirectories if name is not a 2 chars (used for country codes subdirectories). - * @param array $excludefileext Exclude some file extensions + * @param string[] $excludefileext Exclude some file extensions * @return int Return integer <0 if error, 0 if nothing done (all files already exists and overwriteifexists=0), >0 if OK * @see dol_copy() */ @@ -925,7 +929,7 @@ function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayrep $result = -2; } - return $result; + return (int) $result; } @@ -938,15 +942,15 @@ function dolCopyDir($srcfile, $destfile, $newmask, $overwriteifexists, $arrayrep * * @param string $srcfile Source file (can't be a directory. use native php @rename() to move a directory) * @param string $destfile Destination file (can't be a directory. use native php @rename() to move a directory) - * @param integer $newmask Mask in octal string for new file (0 by default means $conf->global->MAIN_UMASK) + * @param string $newmask Mask in octal string for new file (0 by default means $conf->global->MAIN_UMASK) * @param int $overwriteifexists Overwrite file if exists (1 by default) * @param int $testvirus Do an antivirus test. Move is canceled if a virus is found. * @param int $indexdatabase Index new file into database. - * @param int $moreinfo Array with more information + * @param array $moreinfo Array with more information * @return boolean True if OK, false if KO * @see dol_move_uploaded_file() */ -function dol_move($srcfile, $destfile, $newmask = 0, $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 1, $moreinfo = array()) +function dol_move($srcfile, $destfile, $newmask = '0', $overwriteifexists = 1, $testvirus = 0, $indexdatabase = 1, $moreinfo = array()) { global $user, $db, $conf; $result = false; @@ -1177,7 +1181,7 @@ function dol_unescapefile($filename) * * @param string $src_file Source file to check * @param string $dest_file Destination file name (to know the expected type) - * @return array Array of errors, or empty array if not virus found + * @return string[] Array of errors, or empty array if not virus found */ function dolCheckVirus($src_file, $dest_file = '') { @@ -1359,7 +1363,7 @@ function dol_move_uploaded_file($src_file, $dest_file, $allowoverwrite, $disable * @param int $disableglob Disable usage of glob like * so function is an exact delete function that will return error if no file found * @param int $nophperrors Disable all PHP output errors * @param int $nohook Disable all hooks - * @param object $object Current object in use + * @param object|null $object Current object in use * @param boolean $allowdotdot Allow to delete file path with .. inside. Never use this, it is reserved for migration purpose. * @param int $indexdatabase Try to remove also index entries. * @param int $nolog Disable log file @@ -2445,7 +2449,7 @@ function dol_uncompress($inputfile, $outputdir) * @return int Return integer <0 if KO, >0 if OK * @see dol_uncompress(), dol_compress_file() */ -function dol_compress_dir($inputdir, $outputfile, $mode = "zip", $excludefiles = '', $rootdirinzip = '', $newmask = 0) +function dol_compress_dir($inputdir, $outputfile, $mode = "zip", $excludefiles = '', $rootdirinzip = '', $newmask = '0') { $foundhandler = 0; From 044d342956392d1f5b01eca7578a67c372ea418f Mon Sep 17 00:00:00 2001 From: MDW Date: Mon, 29 Jan 2024 18:56:17 +0100 Subject: [PATCH 07/28] Fix: LABEL is required on the db classes. # Fix: LABEL is required on the db classes. Define const in parent type so that it is required in the subclasses. --- htdocs/core/db/DoliDB.class.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/htdocs/core/db/DoliDB.class.php b/htdocs/core/db/DoliDB.class.php index d20d91462e6..498183faca6 100644 --- a/htdocs/core/db/DoliDB.class.php +++ b/htdocs/core/db/DoliDB.class.php @@ -30,8 +30,10 @@ require_once DOL_DOCUMENT_ROOT.'/core/db/Database.interface.php'; */ abstract class DoliDB implements Database { - /** Force subclass to implement VERSIONMIN*/ + /** Force subclass to implement VERSIONMIN - required DB version */ const VERSIONMIN = self::VERSIONMIN; + /** Force subclass to implement LABEL - description of DB type */ + const LABEL = self::LABEL; /** @var bool|resource|mysqli|SQLite3|PgSql\Connection Database handler */ public $db; From b19d230a18b274edff9cc6d73c705e481ed5fe3f Mon Sep 17 00:00:00 2001 From: thibdrev Date: Mon, 29 Jan 2024 19:01:18 +0100 Subject: [PATCH 08/28] qual: phpstan for htdocs/projet/tasks.php htdocs/projet/tasks.php 345 Property CommonObject::$fk_project (int) does not accept array|string. htdocs/projet/tasks.php 356 Property Task::$budget_amount (float) does not accept array|string. --- htdocs/projet/tasks.php | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/htdocs/projet/tasks.php b/htdocs/projet/tasks.php index 0e0381fd831..b93adda4b16 100644 --- a/htdocs/projet/tasks.php +++ b/htdocs/projet/tasks.php @@ -49,7 +49,7 @@ $show_files = GETPOST('show_files', 'int'); $confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); -$id = GETPOST('id', 'int'); +$id = GETPOSTINT('id'); $ref = GETPOST('ref', 'alpha'); $taskref = GETPOST('taskref', 'alpha'); @@ -143,7 +143,7 @@ $diroutputmassaction = $conf->project->dir_output.'/tasks/temp/massgeneration/'. $hookmanager->initHooks(array('projecttaskscard', 'globalcard')); $progress = GETPOST('progress', 'int'); -$budget_amount = GETPOST('budget_amount', 'int'); +$budget_amount = GETPOSTFLOAT('budget_amount'); $label = GETPOST('label', 'alpha'); $description = GETPOST('description', 'restricthtml'); $planned_workloadhour = (GETPOST('planned_workloadhour', 'int') ? GETPOST('planned_workloadhour', 'int') : 0); @@ -331,14 +331,8 @@ if ($action == 'createtask' && $user->hasRight('projet', 'creer')) { if (!$error) { $tmparray = explode('_', GETPOST('task_parent')); - $projectid = $tmparray[0]; - if (empty($projectid)) { - $projectid = $id; // If projectid is '' - } - $task_parent = $tmparray[1]; - if (empty($task_parent)) { - $task_parent = 0; // If task_parent is '' - } + $projectid = empty($tmparray[0]) ? $id : (int) $tmparray[0]; + $task_parent = empty($tmparray[1]) ? 0 : $tmparray[1]; $task = new Task($db); From 70b9a06986f372ef446fe2d6d22fd37d3d9d5a61 Mon Sep 17 00:00:00 2001 From: thibdrev Date: Mon, 29 Jan 2024 19:04:06 +0100 Subject: [PATCH 09/28] qual: phpstan for htdocs/projet/tasks/stats/index.php htdocs/projet/tasks/stats/index.php 83 Property Stats::$year (int) does not accept array|string. htdocs/projet/tasks/stats/index.php 125 Property Stats::$year (int) does not accept array|string. --- htdocs/projet/tasks/stats/index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/projet/tasks/stats/index.php b/htdocs/projet/tasks/stats/index.php index eb720c69f74..2c402efac39 100644 --- a/htdocs/projet/tasks/stats/index.php +++ b/htdocs/projet/tasks/stats/index.php @@ -45,7 +45,7 @@ if ($user->socid > 0) { $socid = $user->socid; } $nowyear = dol_print_date(dol_now('gmt'), "%Y", 'gmt'); -$year = GETPOST('year') > 0 ? GETPOST('year') : $nowyear; +$year = GETPOSTINT('year') > 0 ? GETPOSTINT('year') : $nowyear; $startyear = $year - (!getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS') ? 2 : max(1, min(10, getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS')))); $endyear = $year; From 8e1dc0e450bd744d1c90217607381d3e9121d91f Mon Sep 17 00:00:00 2001 From: thibdrev Date: Mon, 29 Jan 2024 19:09:34 +0100 Subject: [PATCH 10/28] qual: phpstan for htdocs/public/bookcal/index.php htdocs/public/bookcal/index.php 239 Property ActionComm::$datep (int) does not accept array|string. htdocs/public/bookcal/index.php 243 Property ActionComm::$fk_bookcal_calendar (int) does not accept array|string. --- htdocs/public/bookcal/index.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/public/bookcal/index.php b/htdocs/public/bookcal/index.php index d2633a1d51a..9bc7e7fcf52 100644 --- a/htdocs/public/bookcal/index.php +++ b/htdocs/public/bookcal/index.php @@ -50,7 +50,7 @@ require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; $langs->loadLangs(array("main", "other", "dict", "agenda", "errors", "companies")); $action = GETPOST('action', 'aZ09'); -$id = GETPOST('id', 'int'); +$id = GETPOSTINT('id'); $id_availability = GETPOST('id_availability', 'int'); $year = GETPOST("year", "int") ? GETPOST("year", "int") : date("Y"); @@ -236,7 +236,7 @@ if ($action == 'add') { $actioncomm->label = $langs->trans("BookcalBookingTitle"); $actioncomm->type = 'AC_RDV'; $actioncomm->type_id = 5; - $actioncomm->datep = GETPOST("datetimebooking", 'int'); + $actioncomm->datep = GETPOSTINT("datetimebooking"); $actioncomm->datef = $dateend; $actioncomm->note_private = GETPOST("description"); $actioncomm->percentage = -1; From 473980a022d5681e3bfff3e6096c93442f0c5141 Mon Sep 17 00:00:00 2001 From: thibdrev Date: Mon, 29 Jan 2024 19:12:02 +0100 Subject: [PATCH 11/28] qual: phpstan for htdocs/public/company/new.php htdocs/public/company/new.php 222 Property Societe::$country_id (int) does not accept array|string. htdocs/public/company/new.php 232 Property Societe::$code_client (string) does not accept int. --- htdocs/public/company/new.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/public/company/new.php b/htdocs/public/company/new.php index 28b81207da4..679eff25dff 100644 --- a/htdocs/public/company/new.php +++ b/htdocs/public/company/new.php @@ -219,7 +219,7 @@ if (empty($reshook) && $action == 'add') { $societe->address = GETPOST('address', 'alphanohtml'); - $societe->country_id = GETPOST('country_id', 'int'); + $societe->country_id = GETPOSTINT('country_id'); $societe->phone = GETPOST('phone', 'alpha'); @@ -229,7 +229,7 @@ if (empty($reshook) && $action == 'add') { $societe->client = 2 ; // our client is a prospect - $societe->code_client = -1; + $societe->code_client = '-1'; $societe->name_alias = GETPOST('name_alias', 'alphanohtml'); From b8314209ce392a5cd104a91bff948e9b95620752 Mon Sep 17 00:00:00 2001 From: thibdrev Date: Mon, 29 Jan 2024 19:13:04 +0100 Subject: [PATCH 12/28] qual: phspstan for htdocs/public/eventorganization/attendee_new.php htdocs/public/eventorganization/attendee_new.php 468 Property Societe::$country_id (int) does not accept array|string. htdocs/public/eventorganization/attendee_new.php 469 Property CommonObject::$state_id (int) does not accept array|string. --- htdocs/public/eventorganization/attendee_new.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/public/eventorganization/attendee_new.php b/htdocs/public/eventorganization/attendee_new.php index 8973e1c6be2..a80f742e64d 100644 --- a/htdocs/public/eventorganization/attendee_new.php +++ b/htdocs/public/eventorganization/attendee_new.php @@ -465,8 +465,8 @@ if (empty($reshook) && $action == 'add' && (!empty($conference->id) && $conferen $thirdparty->town = GETPOST("town"); $thirdparty->client = $thirdparty::PROSPECT; $thirdparty->fournisseur = 0; - $thirdparty->country_id = GETPOST("country_id", 'int'); - $thirdparty->state_id = GETPOST("state_id", 'int'); + $thirdparty->country_id = GETPOSTINT("country_id"); + $thirdparty->state_id = GETPOSTINT("state_id"); $thirdparty->email = ($emailcompany ? $emailcompany : $email); // Load object modCodeTiers From 0d21087e47d456b96e854d01775f5079a7eee475 Mon Sep 17 00:00:00 2001 From: thibdrev Date: Mon, 29 Jan 2024 19:16:18 +0100 Subject: [PATCH 13/28] qual: phpstan for htdocs/public/members/new.php htdocs/public/members/new.php 294 Property CommonObject::$country_id (int) does not accept string. htdocs/public/members/new.php 295 Property CommonObject::$state_id (int) does not accept array|string. htdocs/public/members/new.php 296 Property Adherent::$typeid (int) does not accept string. --- htdocs/public/members/new.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/public/members/new.php b/htdocs/public/members/new.php index 14a45eb421c..9a6950fd497 100644 --- a/htdocs/public/members/new.php +++ b/htdocs/public/members/new.php @@ -291,9 +291,9 @@ if (empty($reshook) && $action == 'add') { $adh->pass = GETPOST('pass1'); } $adh->photo = GETPOST('photo'); - $adh->country_id = getDolGlobalString("MEMBER_NEWFORM_FORCECOUNTRYCODE", GETPOST('country_id', 'int')); - $adh->state_id = GETPOST('state_id', 'int'); - $adh->typeid = getDolGlobalString("MEMBER_NEWFORM_FORCETYPE", GETPOST('typeid', 'int')); + $adh->country_id = getDolGlobalInt("MEMBER_NEWFORM_FORCECOUNTRYCODE", GETPOSTINT('country_id')); + $adh->state_id = GETPOSTINT('state_id'); + $adh->typeid = getDolGlobalInt("MEMBER_NEWFORM_FORCETYPE", GETPOSTINT('typeid')); $adh->note_private = GETPOST('note_private'); $adh->morphy = getDolGlobalString("MEMBER_NEWFORM_FORCEMORPHY", GETPOST('morphy')); $adh->birth = $birthday; From b4ad9045daaff92a5c08af9f9d34e5d520b6482d Mon Sep 17 00:00:00 2001 From: thibdrev Date: Mon, 29 Jan 2024 21:22:28 +0100 Subject: [PATCH 14/28] qual: phpstan for htdocs/societe/paymentmodes.php htdocs/societe/paymentmodes.php 170 Property Account::$courant (int) does not accept array|string. htdocs/societe/paymentmodes.php 171 Property Account::$clos (int) does not accept array|string. htdocs/societe/paymentmodes.php 300 Property Account::$courant (int) does not accept array|string. htdocs/societe/paymentmodes.php 301 Property Account::$clos (int) does not accept array|string. --- htdocs/societe/paymentmodes.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/htdocs/societe/paymentmodes.php b/htdocs/societe/paymentmodes.php index fa1495ab87c..5c7e2e58749 100644 --- a/htdocs/societe/paymentmodes.php +++ b/htdocs/societe/paymentmodes.php @@ -167,8 +167,8 @@ if (empty($reshook)) { $companybankaccount->bank = GETPOST('bank', 'alpha'); $companybankaccount->label = GETPOST('label', 'alpha'); - $companybankaccount->courant = GETPOST('courant', 'alpha'); - $companybankaccount->clos = GETPOST('clos', 'alpha'); + $companybankaccount->courant = GETPOSTINT('courant'); + $companybankaccount->clos = GETPOSTINT('clos'); $companybankaccount->code_banque = GETPOST('code_banque', 'alpha'); $companybankaccount->code_guichet = GETPOST('code_guichet', 'alpha'); $companybankaccount->number = GETPOST('number', 'alpha'); @@ -297,8 +297,8 @@ if (empty($reshook)) { $companybankaccount->bank = GETPOST('bank', 'alpha'); $companybankaccount->label = GETPOST('label', 'alpha'); - $companybankaccount->courant = GETPOST('courant', 'alpha'); - $companybankaccount->clos = GETPOST('clos', 'alpha'); + $companybankaccount->courant = GETPOSTINT('courant'); + $companybankaccount->clos = GETPOSTINT('clos'); $companybankaccount->code_banque = GETPOST('code_banque', 'alpha'); $companybankaccount->code_guichet = GETPOST('code_guichet', 'alpha'); $companybankaccount->number = GETPOST('number', 'alpha'); @@ -311,8 +311,8 @@ if (empty($reshook)) { $companybankaccount->frstrecur = GETPOST('frstrecur', 'alpha'); $companybankaccount->rum = GETPOST('rum', 'alpha'); $companybankaccount->date_rum = dol_mktime(0, 0, 0, GETPOST('date_rummonth', 'int'), GETPOST('date_rumday', 'int'), GETPOST('date_rumyear', 'int')); - $companybankaccount->datec = dol_now(); - $companybankaccount->status = 1; + $companybankaccount->datec = dol_now(); + $companybankaccount->status = 1; $companybankaccount->bank = trim($companybankaccount->bank); if (empty($companybankaccount->bank) && !empty($companybankaccount->thirdparty)) { From 60a2c30f872e0cf414c61c2773746377efd24408 Mon Sep 17 00:00:00 2001 From: thibdrev Date: Mon, 29 Jan 2024 22:05:05 +0100 Subject: [PATCH 15/28] qual: phpdoc for htdocs/core/class/cregion.class.php --- htdocs/core/class/cregion.class.php | 33 ++++++++++++++++++----------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/htdocs/core/class/cregion.class.php b/htdocs/core/class/cregion.class.php index ba0e966ba05..9f2bbf779a9 100644 --- a/htdocs/core/class/cregion.class.php +++ b/htdocs/core/class/cregion.class.php @@ -34,16 +34,25 @@ class Cregion extends CommonDict //public $element = 'cregion'; //!< Id that identify managed objects //public $table_element = 'c_regions'; //!< Name of table without prefix where object is stored + /** + * @var int The code of the region + */ public $code_region; + + /** + * @var int The ID of the country of the region + */ public $fk_pays; /** - * @var string Region name + * @var string The name of the region */ public $name; /** - * @var string Region chef lieu + * @var string The reference of the "chef-lieu" of the region + * A.k.a. the administrative headquarter of the region + * (examples: HU33, PT9, 97601) */ public $cheflieu; @@ -73,13 +82,13 @@ class Cregion extends CommonDict // Clean parameters if (isset($this->code_region)) { - $this->code_region = trim($this->code_region); + $this->code_region = (int) $this->code_region; } if (isset($this->fk_pays)) { - $this->fk_pays = trim($this->fk_pays); + $this->fk_pays = (int) $this->fk_pays; } - if (isset($this->nom)) { - $this->nom = trim($this->nom); + if (isset($this->name)) { + $this->name = trim($this->name); } if (isset($this->cheflieu)) { $this->cheflieu = trim($this->cheflieu); @@ -139,12 +148,12 @@ class Cregion extends CommonDict /** * Load object in memory from database * - * @param int $id Id object - * @param string $code_region Code - * @param string $fk_pays Country Id + * @param int $id Id object + * @param string $code_region Code + * @param int $fk_pays Country Id * @return int >0 if OK, 0 if not found, <0 if KO */ - public function fetch($id, $code_region = '', $fk_pays = '') + public function fetch($id, $code_region = '', $fk_pays = 0) { $sql = "SELECT"; $sql .= " t.rowid,"; @@ -203,10 +212,10 @@ class Cregion extends CommonDict // Clean parameters if (isset($this->code_region)) { - $this->code_region = trim($this->code_region); + $this->code_region = (int) $this->code_region; } if (isset($this->fk_pays)) { - $this->fk_pays = trim($this->fk_pays); + $this->fk_pays = (int) $this->fk_pays; } if (isset($this->name)) { $this->name = trim($this->name); From 3da8970a09621512e6601376740c058d5561b6ff Mon Sep 17 00:00:00 2001 From: thibdrev Date: Mon, 29 Jan 2024 22:20:18 +0100 Subject: [PATCH 16/28] qual: phpdoc for htdocs/core/class/cstate.class.php --- htdocs/core/class/cstate.class.php | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/htdocs/core/class/cstate.class.php b/htdocs/core/class/cstate.class.php index 0ed00e3e847..a6d4e93f9fa 100644 --- a/htdocs/core/class/cstate.class.php +++ b/htdocs/core/class/cstate.class.php @@ -31,14 +31,18 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commondict.class.php'; class Cstate extends CommonDict { /** - * @var int ID + * @var int The ID of the state */ public $rowid; + /** + * @var string The code of the state + * (ex: LU0011, MA12, 07, 0801, etc.) + */ public $code_departement; /** - * @var string name + * @var string The name of the state */ public $name = ''; @@ -130,8 +134,8 @@ class Cstate extends CommonDict /** * Load object in memory from database * - * @param int $id Id object - * @param string $code Code + * @param int $id State ID + * @param string $code State code * @return int Return integer <0 if KO, >0 if OK */ public function fetch($id, $code = '') @@ -174,7 +178,7 @@ class Cstate extends CommonDict /** * Update object into database * - * @param User $user User that modify + * @param User $user User who updates * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int Return integer <0 if KO, >0 if OK */ From 1aef35e96dfb05a21194c3516af22bf0caaebb43 Mon Sep 17 00:00:00 2001 From: thibdrev Date: Mon, 29 Jan 2024 22:59:31 +0100 Subject: [PATCH 17/28] qual: phpdoc for htdocs/core/class/translate.class.php --- htdocs/core/class/translate.class.php | 63 +++++++++++++++++++++++---- 1 file changed, 55 insertions(+), 8 deletions(-) diff --git a/htdocs/core/class/translate.class.php b/htdocs/core/class/translate.class.php index 20102ba29ff..336241261ad 100644 --- a/htdocs/core/class/translate.class.php +++ b/htdocs/core/class/translate.class.php @@ -30,20 +30,67 @@ */ class Translate { - public $dir; // Directories that contains /langs subdirectory + /** + * @var string Directory containing the /langs subdirectory + */ + public $dir; - public $defaultlang; // Current language for current user - public $shortlang; // Short language for current user - public $charset_output = 'UTF-8'; // Codage used by "trans" method outputs + /** + * @var string Current language for current user + */ + public $defaultlang; - public $tab_translate = array(); // Array of all translations key=>value - private $_tab_loaded = array(); // Array to store result after loading each language file + /** + * @var string Short language code for current user + */ + public $shortlang; - public $cache_labels = array(); // Cache for labels return by getLabelFromKey method - public $cache_currencies = array(); // Cache to store currency symbols + /** + * @var string Codage used by "trans" method outputs + */ + public $charset_output = 'UTF-8'; + + + /** + * @var array Array of all translations key=>value + */ + public $tab_translate = array(); + + /** + * @var array Array to store result after loading each language file + */ + private $_tab_loaded = array(); + + /** + * @var array Cache for labels returned by getLabelFromKey method + */ + public $cache_labels = array(); + + /** + * @var array Cache to store currency symbols + */ + public $cache_currencies = array(); + + /** + * @var bool True if all currencies have been loaded in this->cache_currencies + * @see $cache_currencies + */ private $cache_currencies_all_loaded = false; + + /** + * @var string Language to use + */ public $origlang; + + /** + * @var string Error message + * @see $errors + */ public $error; + + /** + * @var string[] Array of error messages + */ public $errors = array(); From 736a26a527a9e66114fc97e7c8c5750a192a1f2e Mon Sep 17 00:00:00 2001 From: thibdrev Date: Mon, 29 Jan 2024 23:00:53 +0100 Subject: [PATCH 18/28] phpcs --- htdocs/core/class/cstate.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/core/class/cstate.class.php b/htdocs/core/class/cstate.class.php index a6d4e93f9fa..99ad05c668a 100644 --- a/htdocs/core/class/cstate.class.php +++ b/htdocs/core/class/cstate.class.php @@ -37,8 +37,8 @@ class Cstate extends CommonDict /** * @var string The code of the state - * (ex: LU0011, MA12, 07, 0801, etc.) - */ + * (ex: LU0011, MA12, 07, 0801, etc.) + */ public $code_departement; /** From d0ada38b79ae0c979cf520ca53a1499ebc89ac75 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 30 Jan 2024 13:13:58 +0100 Subject: [PATCH 19/28] SEC Reduce nb of var without WAF used when using the website module --- htdocs/main.inc.php | 60 +++++++++++++++++++++++----------------- htdocs/website/index.php | 5 ++-- 2 files changed, 38 insertions(+), 27 deletions(-) diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php index 53eeeba0274..c5bf06cb31d 100644 --- a/htdocs/main.inc.php +++ b/htdocs/main.inc.php @@ -127,7 +127,7 @@ function testSqlAndScriptInject($val, $type) // If $val has changed after removing non valid UTF8 chars, it means we have an evil string. $inj += 1; } - //print 'type='.$type.'-val='.$val.'-newval='.$newval."-inj=".$inj."\n"; + //print 'inj='.$inj.'-type='.$type.'-val='.$val.'-newval='.$newval."\n"; // For SQL Injection (only GET are used to scan for such injection strings) if ($type == 1 || $type == 3) { @@ -213,14 +213,20 @@ function testSqlAndScriptInject($val, $type) * Return true if security check on parameters are OK, false otherwise. * * @param string|array $var Variable name - * @param string $type 1=GET, 0=POST, 2=PHP_SELF - * @return boolean|null true if there is no injection. Stop code if injection found. + * @param int $type 1=GET, 0=POST, 2=PHP_SELF + * @param int $stopcode 0=No stop code, 1=Stop code (default) if injection found + * @return boolean|null True if there is no injection. */ -function analyseVarsForSqlAndScriptsInjection(&$var, $type) +function analyseVarsForSqlAndScriptsInjection(&$var, $type, $stopcode = 1) { if (is_array($var)) { foreach ($var as $key => $value) { // Warning, $key may also be used for attacks - if (analyseVarsForSqlAndScriptsInjection($key, $type) && analyseVarsForSqlAndScriptsInjection($value, $type)) { + // Exclude check for some variable keys + if ($type === 0 && defined('NOSCANPOSTFORINJECTION') && is_array(constant('NOSCANPOSTFORINJECTION')) && in_array($key, constant('NOSCANPOSTFORINJECTION'))) { + continue; + } + + if (analyseVarsForSqlAndScriptsInjection($key, $type, $stopcode) && analyseVarsForSqlAndScriptsInjection($value, $type, $stopcode)) { //$var[$key] = $value; // This is useless } else { http_response_code(403); @@ -228,29 +234,33 @@ function analyseVarsForSqlAndScriptsInjection(&$var, $type) // Get remote IP: PS: We do not use getRemoteIP(), function is not yet loaded and we need a value that can't be spoofed $ip = (empty($_SERVER['REMOTE_ADDR']) ? 'unknown' : $_SERVER['REMOTE_ADDR']); - $errormessage = 'Access refused to '.htmlentities($ip, ENT_COMPAT, 'UTF-8').' by SQL or Script injection protection in main.inc.php:analyseVarsForSqlAndScriptsInjection type='.htmlentities($type, ENT_COMPAT, 'UTF-8'); + if ($stopcode) { + $errormessage = 'Access refused to '.htmlentities($ip, ENT_COMPAT, 'UTF-8').' by SQL or Script injection protection in main.inc.php:analyseVarsForSqlAndScriptsInjection type='.htmlentities($type, ENT_COMPAT, 'UTF-8'); - $errormessage2 = 'paramkey='.htmlentities($key, ENT_COMPAT, 'UTF-8'); - $errormessage2 .= ' paramvalue='.htmlentities($value, ENT_COMPAT, 'UTF-8'); - $errormessage2 .= ' page='.htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT, 'UTF-8'); + $errormessage2 = 'page='.htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT, 'UTF-8'); + $errormessage2 .= ' paramkey='.htmlentities($key, ENT_COMPAT, 'UTF-8'); + $errormessage2 .= ' paramvalue='.htmlentities($value, ENT_COMPAT, 'UTF-8'); - print $errormessage; - print "
\n"; - print 'Try to go back, fix data of your form and resubmit it. You can contact also your technical support.'; + print $errormessage; + print "
\n"; + print 'Try to go back, fix data of your form and resubmit it. You can contact also your technical support.'; - print ''; + print "\n".''; - // Add entry into error the PHP server error log - if (function_exists('error_log')) { - error_log($errormessage.' '.$errormessage2); + // Add entry into the PHP server error log + if (function_exists('error_log')) { + error_log($errormessage.' '.substr($errormessage2, 2000)); + } + + // Note: No addition into security audit table is done because we don't want to execute code in such a case. + // Detection of too many such requests can be done with a fail2ban rule on 403 error code or into the PHP server error log. + + exit; + } else { + return false; } - - // Note: No addition into security audit table is done because we don't want to execute code in such a case. - // Detection of too many such requests can be done with a fail2ban rule on 403 error code or into the PHP server error log. - - exit; } } return true; @@ -262,7 +272,7 @@ function analyseVarsForSqlAndScriptsInjection(&$var, $type) // To disable the WAF for GET and POST and PHP_SELF, uncomment this //define('NOSCANPHPSELFFORINJECTION', 1); //define('NOSCANGETFORINJECTION', 1); -//define('NOSCANPOSTFORINJECTION', 1); +//define('NOSCANPOSTFORINJECTION', 1 or 2); // Check consistency of NOREQUIREXXX DEFINES if ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && !defined('NOREQUIREMENU')) { @@ -288,7 +298,7 @@ if (!defined('NOSCANGETFORINJECTION') && !empty($_SERVER["QUERY_STRING"])) { analyseVarsForSqlAndScriptsInjection($morevaltochecklikeget, 1); } // Sanity check on POST -if (!defined('NOSCANPOSTFORINJECTION')) { +if (!defined('NOSCANPOSTFORINJECTION') || is_array(constant('NOSCANPOSTFORINJECTION'))) { analyseVarsForSqlAndScriptsInjection($_POST, 0); } diff --git a/htdocs/website/index.php b/htdocs/website/index.php index 872431c1bb9..57084b61cdf 100644 --- a/htdocs/website/index.php +++ b/htdocs/website/index.php @@ -23,8 +23,9 @@ * \brief Page to website view/edit */ -define('NOSCANPOSTFORINJECTION', 1); -define('NOSTYLECHECK', 1); +// We allow POST of rich content with js and style, but only for this php file and if into some given POST variable +define('NOSCANPOSTFORINJECTION', array('PAGE_CONTENT', 'WEBSITE_JS_INLINE', 'WEBSITE_HTML_HEADER')); + define('USEDOLIBARREDITOR', 1); define('FORCE_CKEDITOR', 1); // We need CKEditor, even if module is off. if (!defined('DISABLE_JS_GRAHP')) { From 63c5b65592a26234e8a396a5153ee9f77531e725 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 30 Jan 2024 13:22:53 +0100 Subject: [PATCH 20/28] Allow the page for website account by default --- htdocs/core/lib/company.lib.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/htdocs/core/lib/company.lib.php b/htdocs/core/lib/company.lib.php index aeffdb434df..0fbac2488fa 100644 --- a/htdocs/core/lib/company.lib.php +++ b/htdocs/core/lib/company.lib.php @@ -243,10 +243,7 @@ function societe_prepare_head(Societe $object) $h++; } - if ( - ((isModEnabled('website') && getDolGlobalString('WEBSITE_USE_WEBSITE_ACCOUNTS')) || isModEnabled('webportal')) - && $user->hasRight('societe', 'lire') - ) { + if ((isModEnabled('website') || isModEnabled('webportal')) && $user->hasRight('societe', 'lire')) { $site_filter_list = array(); if (isModEnabled('website')) { $site_filter_list[] = 'dolibarr_website'; From cd5bca5e1553476cf25f2f96b08a8ad52f8cc787 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 30 Jan 2024 13:44:14 +0100 Subject: [PATCH 21/28] Fix filter on user lost on navigation in list of salaries --- htdocs/salaries/list.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/salaries/list.php b/htdocs/salaries/list.php index 89dc0b6927c..f1e58537c7f 100644 --- a/htdocs/salaries/list.php +++ b/htdocs/salaries/list.php @@ -370,10 +370,10 @@ if ($search_type_id) { if ($optioncss != '') { $param .= '&optioncss='.urlencode($optioncss); } -if ($search_ref) { +if ($search_ref != '') { $param .= '&search_ref='.urlencode($search_ref); } -if ($search_user > 0) { +if ($search_user != '') { $param .= '&search_user='.urlencode($search_user); } if ($search_label) { From a89b00810a965ff7dd0dc7dfbacc4372c4977fe1 Mon Sep 17 00:00:00 2001 From: Hystepik Date: Tue, 30 Jan 2024 15:00:14 +0100 Subject: [PATCH 22/28] Fix some php warnings --- htdocs/comm/action/class/actioncomm.class.php | 2 +- htdocs/projet/list.php | 2 +- htdocs/projet/tasks/contact.php | 2 +- htdocs/projet/tasks/document.php | 2 +- htdocs/projet/tasks/note.php | 2 +- htdocs/projet/tasks/task.php | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index 2cfbc4a99f4..c784967e4f8 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -442,7 +442,7 @@ class ActionComm extends CommonObject // Clean parameters $this->label = dol_trunc(trim($this->label), 128); - $this->location = dol_trunc(trim($this->location), 128); + $this->location = (!empty($this->location) ? dol_trunc(trim($this->location), 128) : ""); $this->note_private = dol_htmlcleanlastbr(trim(empty($this->note_private) ? $this->note : $this->note_private)); if (empty($this->percentage)) { $this->percentage = 0; diff --git a/htdocs/projet/list.php b/htdocs/projet/list.php index b4bca156beb..d98ef553748 100644 --- a/htdocs/projet/list.php +++ b/htdocs/projet/list.php @@ -1807,7 +1807,7 @@ while ($i < $imaxinloop) { if (!empty($arrayfields['p.opp_amount']['checked'])) { print ''; //if ($obj->opp_status_code) - if (strcmp($obj->opp_amount, '')) { + if (isset($obj->opp_amount) && strcmp($obj->opp_amount, '')) { print ''.price($obj->opp_amount, 1, $langs, 1, -1, -1, '').''; if (!isset($totalarray['val']['p.opp_amount'])) { $totalarray['val']['p.opp_amount'] = $obj->opp_amount; diff --git a/htdocs/projet/tasks/contact.php b/htdocs/projet/tasks/contact.php index 636a2c8a791..f083fb19c5f 100644 --- a/htdocs/projet/tasks/contact.php +++ b/htdocs/projet/tasks/contact.php @@ -259,7 +259,7 @@ if ($id > 0 || !empty($ref)) { // Budget print ''.$langs->trans("Budget").''; - if (strcmp($projectstatic->budget_amount, '')) { + if (isset($projectstatic->budget_amount) && strcmp($projectstatic->budget_amount, '')) { print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); } print ''; diff --git a/htdocs/projet/tasks/document.php b/htdocs/projet/tasks/document.php index c84f17371c8..b32d6e1a0e6 100644 --- a/htdocs/projet/tasks/document.php +++ b/htdocs/projet/tasks/document.php @@ -216,7 +216,7 @@ if ($object->id > 0) { // Budget print ''.$langs->trans("Budget").''; - if (strcmp($projectstatic->budget_amount, '')) { + if (isset($projectstatic->budget_amount) && strcmp($projectstatic->budget_amount, '')) { print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); } print ''; diff --git a/htdocs/projet/tasks/note.php b/htdocs/projet/tasks/note.php index 442e6c2f8ed..617b55a845c 100644 --- a/htdocs/projet/tasks/note.php +++ b/htdocs/projet/tasks/note.php @@ -206,7 +206,7 @@ if ($object->id > 0) { // Budget print ''.$langs->trans("Budget").''; - if (strcmp($projectstatic->budget_amount, '')) { + if (isset($projectstatic->budget_amount) && strcmp($projectstatic->budget_amount, '')) { print price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency); } print ''; diff --git a/htdocs/projet/tasks/task.php b/htdocs/projet/tasks/task.php index c9a6c4d3aa4..59b260fc142 100644 --- a/htdocs/projet/tasks/task.php +++ b/htdocs/projet/tasks/task.php @@ -331,7 +331,7 @@ if ($id > 0 || !empty($ref)) { // Budget print ''.$langs->trans("Budget").''; - if (strcmp($projectstatic->budget_amount, '')) { + if (isset($projectstatic->budget_amount) && strcmp($projectstatic->budget_amount, '')) { print ''.price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency).''; } print ''; From a28af6f5cac7c96909282ff391e92bce0f794c04 Mon Sep 17 00:00:00 2001 From: William Mead Date: Tue, 30 Jan 2024 15:13:12 +0100 Subject: [PATCH 23/28] Added date filter --- htdocs/fichinter/list.php | 49 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/htdocs/fichinter/list.php b/htdocs/fichinter/list.php index b4d6eb6c20c..11db1bc0045 100644 --- a/htdocs/fichinter/list.php +++ b/htdocs/fichinter/list.php @@ -67,6 +67,14 @@ $search_projet_ref = GETPOST('search_projet_ref', 'alpha'); $search_contrat_ref = GETPOST('search_contrat_ref', 'alpha'); $search_status = GETPOST('search_status', 'alpha'); $search_all = trim((GETPOST('search_all', 'alphanohtml') != '') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); +$search_date_startday = GETPOST('search_date_startday', 'int'); +$search_date_startmonth = GETPOST('search_date_startmonth', 'int'); +$search_date_startyear = GETPOST('search_date_startyear', 'int'); +$search_date_endday = GETPOST('search_date_endday', 'int'); +$search_date_endmonth = GETPOST('search_date_endmonth', 'int'); +$search_date_endyear = GETPOST('search_date_endyear', 'int'); +$search_date_start = dol_mktime(0, 0, 0, $search_date_startmonth, $search_date_startday, $search_date_startyear); // Use tzserver +$search_date_end = dol_mktime(23, 59, 59, $search_date_endmonth, $search_date_endday, $search_date_endyear); $optioncss = GETPOST('optioncss', 'alpha'); $socid = GETPOST('socid', 'int'); @@ -183,6 +191,14 @@ if (empty($reshook)) { $search_contrat_ref = ""; $search_desc = ""; $search_status = ""; + $search_date_startday = ''; + $search_date_startmonth = ''; + $search_date_startyear = ''; + $search_date_endday = ''; + $search_date_endmonth = ''; + $search_date_endyear = ''; + $search_date_start = ''; + $search_date_end = ''; $toselect = array(); $search_array_options = array(); } @@ -306,6 +322,12 @@ if ($search_desc) { if ($search_status != '' && $search_status >= 0) { $sql .= ' AND f.fk_statut = '.urlencode($search_status); } +if ($search_date_start) { + $sql .= " AND fd.date >= '".$db->idate($search_date_start)."'"; +} +if ($search_date_end) { + $sql .= " AND fd.date <= '".$db->idate($search_date_end)."'"; +} if (!$user->hasRight('societe', 'client', 'voir')) { $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id); } @@ -427,6 +449,24 @@ if ($search_desc) { if ($search_status != '' && $search_status > -1) { $param .= "&search_status=".urlencode($search_status); } +if ($search_date_startday > 0) { + $param .= '&search_date_startday='.urlencode($search_date_startday); +} +if ($search_date_startmonth > 0) { + $param .= '&search_date_startmonth='.urlencode($search_date_startmonth); +} +if ($search_date_startyear > 0) { + $param .= '&search_date_startyear='.urlencode($search_date_startyear); +} +if ($search_date_endday > 0) { + $param .= '&search_date_endday='.urlencode($search_date_endday); +} +if ($search_date_endmonth > 0) { + $param .= '&search_date_endmonth='.urlencode($search_date_endmonth); +} +if ($search_date_endyear > 0) { + $param .= '&search_date_endyear='.urlencode($search_date_endyear); +} if ($show_files) { $param .= '&show_files='.urlencode($show_files); } @@ -611,7 +651,14 @@ if (!empty($arrayfields['fd.description']['checked'])) { print ' '; } if (!empty($arrayfields['fd.date']['checked'])) { - print ' '; + print ''; + print '
'; + print $form->selectDate($search_date_start ?: -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); + print '
'; + print '
'; + print $form->selectDate($search_date_end ?: -1, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); + print '
'; + print ''; } if (!empty($arrayfields['fd.duree']['checked'])) { print ' '; From 9171051268159f89758bf90c686bd9c4f45ff891 Mon Sep 17 00:00:00 2001 From: William Mead Date: Tue, 30 Jan 2024 15:14:15 +0100 Subject: [PATCH 24/28] Added contributor details --- htdocs/fichinter/list.php | 1 + 1 file changed, 1 insertion(+) diff --git a/htdocs/fichinter/list.php b/htdocs/fichinter/list.php index 11db1bc0045..19f82735036 100644 --- a/htdocs/fichinter/list.php +++ b/htdocs/fichinter/list.php @@ -8,6 +8,7 @@ * Copyright (C) 2018 Ferran Marcet * Copyright (C) 2021-2023 Frédéric France * Copyright (C) 2022 Charlène Benke + * Copyright (C) 2024 William Mead * * 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 From 53818636ed2591b45b083901408aa3e81595a2cc Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 30 Jan 2024 16:05:48 +0100 Subject: [PATCH 25/28] Fix phpstan --- htdocs/website/class/website.class.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/htdocs/website/class/website.class.php b/htdocs/website/class/website.class.php index dd01c2c723f..16e2625ddb6 100644 --- a/htdocs/website/class/website.class.php +++ b/htdocs/website/class/website.class.php @@ -2068,9 +2068,10 @@ class Website extends CommonObject /** * Replace line by line in file using num of line - * @param string $desfFile path of file dest - * @param array $differences array of differences between files - * @return false|int false if we can't replace + * + * @param string $desfFile path of file dest + * @param array $differences array of differences between files + * @return int 0 if we can't replace */ protected function replaceLineUsingNum($desfFile, $differences) { @@ -2093,6 +2094,7 @@ class Website extends CommonObject unset($differences['file_destination']); $contentDest = file($desfFile, FILE_IGNORE_NEW_LINES); foreach ($differences as $key => $ligneSource) { + $matches = array(); if (preg_match('/(Ajoutée|Modifiée) à la ligne (\d+)/', $key, $matches)) { $typeModification = $matches[1]; $numLigne = (int) $matches[2] - 1; @@ -2116,5 +2118,7 @@ class Website extends CommonObject dolReplaceInFile($desfFile, array($linechanged => $line)); } } + + return 0; } } From 5a5e8926c445e8a8fa5512c97baa3ba973ed623f Mon Sep 17 00:00:00 2001 From: William Mead Date: Tue, 30 Jan 2024 16:06:31 +0100 Subject: [PATCH 26/28] Refactored code --- htdocs/fichinter/list.php | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/htdocs/fichinter/list.php b/htdocs/fichinter/list.php index 19f82735036..20eb6c8e26c 100644 --- a/htdocs/fichinter/list.php +++ b/htdocs/fichinter/list.php @@ -68,12 +68,12 @@ $search_projet_ref = GETPOST('search_projet_ref', 'alpha'); $search_contrat_ref = GETPOST('search_contrat_ref', 'alpha'); $search_status = GETPOST('search_status', 'alpha'); $search_all = trim((GETPOST('search_all', 'alphanohtml') != '') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); -$search_date_startday = GETPOST('search_date_startday', 'int'); -$search_date_startmonth = GETPOST('search_date_startmonth', 'int'); -$search_date_startyear = GETPOST('search_date_startyear', 'int'); -$search_date_endday = GETPOST('search_date_endday', 'int'); -$search_date_endmonth = GETPOST('search_date_endmonth', 'int'); -$search_date_endyear = GETPOST('search_date_endyear', 'int'); +$search_date_startday = GETPOSTINT('search_date_startday'); +$search_date_startmonth = GETPOSTINT('search_date_startmonth'); +$search_date_startyear = GETPOSTINT('search_date_startyear'); +$search_date_endday = GETPOSTINT('search_date_endday'); +$search_date_endmonth = GETPOSTINT('search_date_endmonth'); +$search_date_endyear = GETPOSTINT('search_date_endyear'); $search_date_start = dol_mktime(0, 0, 0, $search_date_startmonth, $search_date_startday, $search_date_startyear); // Use tzserver $search_date_end = dol_mktime(23, 59, 59, $search_date_endmonth, $search_date_endday, $search_date_endyear); $optioncss = GETPOST('optioncss', 'alpha'); @@ -323,11 +323,13 @@ if ($search_desc) { if ($search_status != '' && $search_status >= 0) { $sql .= ' AND f.fk_statut = '.urlencode($search_status); } -if ($search_date_start) { - $sql .= " AND fd.date >= '".$db->idate($search_date_start)."'"; -} -if ($search_date_end) { - $sql .= " AND fd.date <= '".$db->idate($search_date_end)."'"; +if (!getDolGlobalString('FICHINTER_DISABLE_DETAILS') && $atleastonefieldinlines) { + if ($search_date_start) { + $sql .= " AND fd.date >= '".$db->idate($search_date_start)."'"; + } + if ($search_date_end) { + $sql .= " AND fd.date <= '".$db->idate($search_date_end)."'"; + } } if (!$user->hasRight('societe', 'client', 'voir')) { $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id); From e523fd58fadef8198cb03325175e2011e257e5ca Mon Sep 17 00:00:00 2001 From: MDW Date: Tue, 30 Jan 2024 11:07:01 +0100 Subject: [PATCH 27/28] Qual: Add yamlfix configuration Add a yamlfix configuration so that it can be adapted to the project's preferences --- pyproject.toml | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 87817e93929..8ff8446a01a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,3 +26,25 @@ uri-ignore-words-list="ned" [tool.setuptools] include-package-data = false + +# pyproject.toml + +[tool.yamlfix] +# allow_duplicate_keys = true +line_length = 80 +# none_representation = "null" +# comments_min_spaces_from_content = 2 +# comments_require_starting_space = true +# whitelines = 0 +# comment_whitelines = 0 +# section_whitelines = 0 +# explicit_start = true +# sequence_style = keep_style # flow_style, block_style, keep_style +# indent_mapping = 2 +# indent_offset = 2 +# indent_sequence = 4 +# none_representation = "" +# quote_basic_values = false +# YAMLFIX_quote_keys_and_basic_values = false +# uote_representation = false +# preserve_quotes = false From ea6982f7639b67b9c324947006a3ef7c2b8c32ec Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 30 Jan 2024 16:59:44 +0100 Subject: [PATCH 28/28] Fix sql to use int --- htdocs/core/class/cregion.class.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/core/class/cregion.class.php b/htdocs/core/class/cregion.class.php index ba0e966ba05..74836cb783d 100644 --- a/htdocs/core/class/cregion.class.php +++ b/htdocs/core/class/cregion.class.php @@ -100,9 +100,9 @@ class Cregion extends CommonDict $sql .= "cheflieu,"; $sql .= "active"; $sql .= ") VALUES ("; - $sql .= " ".(!isset($this->rowid) ? 'NULL' : "'".$this->db->escape($this->rowid)."'").","; - $sql .= " ".(!isset($this->code_region) ? 'NULL' : "'".$this->db->escape($this->code_region)."'").","; - $sql .= " ".(!isset($this->fk_pays) ? 'NULL' : "'".$this->db->escape($this->fk_pays)."'").","; + $sql .= " ".(!isset($this->rowid) ? 'NULL' : (int) $this->rowid).","; + $sql .= " ".(!isset($this->code_region) ? 'NULL' : (int) $this->code_region).","; + $sql .= " ".(!isset($this->fk_pays) ? 'NULL' : (int) $this->fk_pays).","; $sql .= " ".(!isset($this->name) ? 'NULL' : "'".$this->db->escape($this->name)."'").","; $sql .= " ".(!isset($this->cheflieu) ? 'NULL' : "'".$this->db->escape($this->cheflieu)."'").","; $sql .= " ".(!isset($this->active) ? 'NULL' : "'".$this->db->escape($this->active)."'");