Merge branch 'develop' into setTemplateForEachModel

This commit is contained in:
Laurent Destailleur 2024-01-30 17:07:36 +01:00 committed by GitHub
commit 27a6a61827
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
31 changed files with 499 additions and 182 deletions

207
.github/logToCs.py vendored
View file

@ -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<file_endgroup>\[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()

View file

@ -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)

View file

@ -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;

View file

@ -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);
@ -100,9 +109,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)."'");
@ -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);

View file

@ -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
*/

View file

@ -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();

View file

@ -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;

View file

@ -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';

View file

@ -6,6 +6,7 @@
* Copyright (C) 2016 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
* Copyright (C) 2019-2024 Frédéric France <frederic.france@netlogic.fr>
* Copyright (C) 2023 Lenin Rivas <lenin.rivas777@gmail.com>
* Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
*
* 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{name:string,path:string,level1name:string,relativename:string,fullname:string,date:string,size:int,perm:int,type:string}> 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{rowid:string,label:string,name:string,path:string,level1name:string,fullname:string,fullpath_orig:string,date_c:string,datem:string,type:string,keywords:string,cover:string,position:int,acl:string,share:string,description:string}> 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<array{name:string,path:string,level1name:string,relativename:string,fullname:string,date:string,size:int,perm:int,type:string}> $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<string,string> $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<string,string> $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;

View file

@ -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;
}
/**

View file

@ -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');

View file

@ -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) {

View file

@ -8,6 +8,7 @@
* Copyright (C) 2018 Ferran Marcet <fmarcet@2byte.es>
* Copyright (C) 2021-2023 Frédéric France <frederic.france@netlogic.fr>
* Copyright (C) 2022 Charlène Benke <charlene@patas-monkey.com>
* Copyright (C) 2024 William Mead <william.mead@manchenumerique.fr>
*
* 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
@ -67,6 +68,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 = 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');
$socid = GETPOST('socid', 'int');
@ -183,6 +192,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 +323,14 @@ if ($search_desc) {
if ($search_status != '' && $search_status >= 0) {
$sql .= ' AND f.fk_statut = '.urlencode($search_status);
}
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);
}
@ -427,6 +452,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 +654,14 @@ if (!empty($arrayfields['fd.description']['checked'])) {
print '<td class="liste_titre">&nbsp;</td>';
}
if (!empty($arrayfields['fd.date']['checked'])) {
print '<td class="liste_titre">&nbsp;</td>';
print '<td class="liste_titre">';
print '<div class="nowrapfordate">';
print $form->selectDate($search_date_start ?: -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
print '</div>';
print '<div class="nowrapfordate">';
print $form->selectDate($search_date_end ?: -1, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
print '</div>';
print '</td>';
}
if (!empty($arrayfields['fd.duree']['checked'])) {
print '<td class="liste_titre">&nbsp;</td>';

View file

@ -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 "<br>\n";
print 'Try to go back, fix data of your form and resubmit it. You can contact also your technical support.';
print $errormessage;
print "<br>\n";
print 'Try to go back, fix data of your form and resubmit it. You can contact also your technical support.';
print '<!--'."\n";
print $errormessage2;
print "\n".'-->';
print "\n".'<!--'."\n";
print $errormessage2;
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);
}

View file

@ -1807,7 +1807,7 @@ while ($i < $imaxinloop) {
if (!empty($arrayfields['p.opp_amount']['checked'])) {
print '<td class="right">';
//if ($obj->opp_status_code)
if (strcmp($obj->opp_amount, '')) {
if (isset($obj->opp_amount) && strcmp($obj->opp_amount, '')) {
print '<span class="amount">'.price($obj->opp_amount, 1, $langs, 1, -1, -1, '').'</span>';
if (!isset($totalarray['val']['p.opp_amount'])) {
$totalarray['val']['p.opp_amount'] = $obj->opp_amount;

View file

@ -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);

View file

@ -259,7 +259,7 @@ if ($id > 0 || !empty($ref)) {
// Budget
print '<tr><td>'.$langs->trans("Budget").'</td><td>';
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 '</td></tr>';

View file

@ -216,7 +216,7 @@ if ($object->id > 0) {
// Budget
print '<tr><td>'.$langs->trans("Budget").'</td><td>';
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 '</td></tr>';

View file

@ -206,7 +206,7 @@ if ($object->id > 0) {
// Budget
print '<tr><td>'.$langs->trans("Budget").'</td><td>';
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 '</td></tr>';

View file

@ -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;

View file

@ -331,7 +331,7 @@ if ($id > 0 || !empty($ref)) {
// Budget
print '<tr><td>'.$langs->trans("Budget").'</td><td>';
if (strcmp($projectstatic->budget_amount, '')) {
if (isset($projectstatic->budget_amount) && strcmp($projectstatic->budget_amount, '')) {
print '<span class="amount">'.price($projectstatic->budget_amount, '', $langs, 1, 0, 0, $conf->currency).'</span>';
}
print '</td></tr>';

View file

@ -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;

View file

@ -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');

View file

@ -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

View file

@ -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;

View file

@ -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) {

View file

@ -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)) {

View file

@ -14,6 +14,7 @@
* Copyright (C) 2018-2021 Nicolas ZABOURI <info@inovea-conseil.com>
* Copyright (C) 2019-2023 Frédéric France <frederic.france@netlogic.fr>
* Copyright (C) 2019 Abbes Bahfir <dolipar@dolipar.org>
* Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
*
* 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.

View file

@ -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;
}
}

View file

@ -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')) {

View file

@ -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