diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index b57ceda24aa..d17347a0ad7 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -4,15 +4,17 @@ How to contribute to Dolibarr Bug reports and feature requests -------------------------------- -*Note*: Issues are not a support forum. If you need help using the software, please use [the forums](https://www.dolibarr.org/forum.php). Forums exist in different languages. +*Note*: **GitHub Issues is not a support forum.** If you have questions about Dolibarr / need help using the software, please use [the forums](https://www.dolibarr.org/forum.php). Forums exist in different languages. Issues are managed on [GitHub](https://github.com/Dolibarr/dolibarr/issues). -Default language here is english. So please prepare your contributions in english. +Default **language here is english**. So please prepare your contributions in english. 1. Please [use the search engine](https://help.github.com/articles/searching-issues) to check if nobody's already reported your problem. 2. [Create an issue](https://help.github.com/articles/creating-an-issue). Choose an appropriate title. Prepend appropriately with Bug or Feature Request. -4. Tell us the version you are using! (look at /htdocs/admin/system/dolibarr.php? and check if you are using the latest version) -3. Write a report with as much detail as possible (Use [screenshots](https://help.github.com/articles/issue-attachments) or even screencasts and provide logging and debugging informations whenever possible). +3. Tell us the version you are using! (look at /htdocs/admin/system/dolibarr.php? and check if you are using the latest version) +4. Write a report with as much detail as possible (Use [screenshots](https://help.github.com/articles/issue-attachments) or even screencasts and provide logging and debugging informations whenever possible). +5. Delete unnecessary submissions. +6. **Check your Message at Preview before sending.** diff --git a/DCO b/DCO new file mode 100644 index 00000000000..d54f007a8c5 --- /dev/null +++ b/DCO @@ -0,0 +1,34 @@ +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2002 - Today, The Dolibarr team and its contributors. + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. diff --git a/build/generate_filelist_xml.php b/build/generate_filelist_xml.php index 6bfbb9c5c9c..63562f1f4f3 100755 --- a/build/generate_filelist_xml.php +++ b/build/generate_filelist_xml.php @@ -22,7 +22,9 @@ * \brief This script create a xml checksum file */ -if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +if (! defined('NOREQUIREDB')) { + define('NOREQUIREDB', '1'); // Do not create database handler $db +} $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); @@ -30,8 +32,8 @@ $path=dirname(__FILE__).'/'; // Test if batch mode if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; } require_once $path."../htdocs/master.inc.php"; @@ -46,30 +48,33 @@ $includecustom=0; $includeconstants=array(); if (empty($argv[1])) { - print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n"; - print "Example: ".$script_file." release=6.0.0 includecustom=1 includeconstant=FR:INVOICE_CAN_ALWAYS_BE_REMOVED:0 includeconstant=all:MAILING_NO_USING_PHPMAIL:1\n"; - exit -1; + print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n"; + print "Example: ".$script_file." release=6.0.0 includecustom=1 includeconstant=FR:INVOICE_CAN_ALWAYS_BE_REMOVED:0 includeconstant=all:MAILING_NO_USING_PHPMAIL:1\n"; + exit -1; } + parse_str($argv[1]); $i=0; while ($i < $argc) { - if (! empty($argv[$i])) parse_str($argv[$i]); - if (preg_match('/includeconstant=/', $argv[$i])) { - $tmp=explode(':', $includeconstant, 3); - if (count($tmp) != 3) { - print "Error: Bad parameter includeconstant ".$includeconstant."\n"; - exit -1; - } - $includeconstants[$tmp[0]][$tmp[1]] = $tmp[2]; - } - $i++; + if (! empty($argv[$i])) { + parse_str($argv[$i]); + } + if (preg_match('/includeconstant=/', $argv[$i])) { + $tmp=explode(':', $includeconstant, 3); // $includeconstant has been set with previous parse_str() + if (count($tmp) != 3) { + print "Error: Bad parameter includeconstant=".$includeconstant."\n"; + exit -1; + } + $includeconstants[$tmp[0]][$tmp[1]] = $tmp[2]; + } + $i++; } if (empty($release)) { - print "Error: Missing release paramater\n"; - print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n"; - exit -1; + print "Error: Missing release paramater\n"; + print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n"; + exit -1; } $savrelease = $release; @@ -77,32 +82,34 @@ $savrelease = $release; // If release is auto, we take current version $tmpver=explode('-', $release, 2); if ($tmpver[0] == 'auto' || $tmpver[0] == 'autostable') { - $release=DOL_VERSION; - if ($tmpver[1] && $tmpver[0] == 'auto') $release.='-'.$tmpver[1]; + $release=DOL_VERSION; + if ($tmpver[1] && $tmpver[0] == 'auto') { + $release.='-'.$tmpver[1]; + } } if (empty($includecustom)) { - $tmpverbis=explode('-', $release, 2); - if (empty($tmpverbis[1]) || $tmpver[0] == 'autostable') { - if (DOL_VERSION != $tmpverbis[0] && $savrelease != 'auto') { - print 'Error: When parameter "includecustom" is not set and there is no suffix in release parameter, version declared into filefunc.in.php ('.DOL_VERSION.') must be exact same value than "release" parameter ('.$tmpverbis[0].')'."\n"; - print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n"; - exit -1; - } - } else { - $tmpverter=explode('-', DOL_VERSION, 2); - if ($tmpverter[0] != $tmpverbis[0]) { - print 'Error: When parameter "includecustom" is not set, version declared into filefunc.in.php ('.DOL_VERSION.') must have value without prefix ('.$tmpverter[0].') that is exact same value than "release" parameter ('.$tmpverbis[0].')'."\n"; - print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n"; - exit -1; - } - } + $tmpverbis=explode('-', $release, 2); + if (empty($tmpverbis[1]) || $tmpver[0] == 'autostable') { + if (DOL_VERSION != $tmpverbis[0] && $savrelease != 'auto') { + print 'Error: When parameter "includecustom" is not set and there is no suffix in release parameter, version declared into filefunc.in.php ('.DOL_VERSION.') must be exact same value than "release" parameter ('.$tmpverbis[0].')'."\n"; + print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n"; + exit -1; + } + } else { + $tmpverter=explode('-', DOL_VERSION, 2); + if ($tmpverter[0] != $tmpverbis[0]) { + print 'Error: When parameter "includecustom" is not set, version declared into filefunc.in.php ('.DOL_VERSION.') must have value without prefix ('.$tmpverter[0].') that is exact same value than "release" parameter ('.$tmpverbis[0].')'."\n"; + print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n"; + exit -1; + } + } } else { - if (! preg_match('/'.preg_quote(DOL_VERSION, '/').'-/', $release)) { - print 'Error: When parameter "includecustom" is set, version declared into filefunc.inc.php ('.DOL_VERSION.') must be used with a suffix into "release" parameter (ex: '.DOL_VERSION.'-mydistrib).'."\n"; - print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n"; - exit -1; - } + if (! preg_match('/'.preg_quote(DOL_VERSION, '/').'-/', $release)) { + print 'Error: When parameter "includecustom" is set, version declared into filefunc.inc.php ('.DOL_VERSION.') must be used with a suffix into "release" parameter (ex: '.DOL_VERSION.'-mydistrib).'."\n"; + print "Usage: ".$script_file." release=autostable|auto[-mybuild]|x.y.z[-mybuild] [includecustom=1] [includeconstant=CC:MY_CONF_NAME:value]\n"; + exit -1; + } } print "Working on files into : ".DOL_DOCUMENT_ROOT."\n"; @@ -110,9 +117,9 @@ print "Release : ".$release."\n"; print "Include custom in signature : ".$includecustom."\n"; print "Include constants in signature : "; foreach ($includeconstants as $countrycode => $tmp) { - foreach ($tmp as $constname => $constvalue) { - print $constname.'='.$constvalue." "; - } + foreach ($tmp as $constname => $constvalue) { + print $constname.'='.$constvalue." "; + } } print "\n"; @@ -134,13 +141,13 @@ fputs($fp, ''."\n"); fputs($fp, ''."\n"); foreach ($includeconstants as $countrycode => $tmp) { - fputs($fp, ''."\n"); - foreach ($tmp as $constname => $constvalue) { - $valueforchecksum=(empty($constvalue)?'0':$constvalue); - $checksumconcat[]=$valueforchecksum; - fputs($fp, ' '.$valueforchecksum.''."\n"); - } - fputs($fp, ''."\n"); + fputs($fp, ''."\n"); + foreach ($tmp as $constname => $constvalue) { + $valueforchecksum=(empty($constvalue)?'0':$constvalue); + $checksumconcat[]=$valueforchecksum; + fputs($fp, ' '.$valueforchecksum.''."\n"); + } + fputs($fp, ''."\n"); } fputs($fp, ''."\n"); @@ -151,28 +158,28 @@ $iterator1 = new RecursiveIteratorIterator($dir_iterator1); $files = new RegexIterator($iterator1, '#^(?:[A-Z]:)?(?:/(?!(?:'.($includecustom?'':'custom\/|').'documents\/|conf\/|install\/))[^/]+)+/[^/]+\.(?:php|css|html|js|json|tpl|jpg|png|gif|sql|lang)$#i'); */ $regextoinclude='\.(php|php3|php4|php5|phtml|phps|phar|inc|css|scss|html|xml|js|json|tpl|jpg|jpeg|png|gif|ico|sql|lang|txt|yml|md|mp3|mp4|wav|mkv|z|gz|zip|rar|tar|less|svg|eot|woff|woff2|ttf|manifest)$'; -$regextoexclude='('.($includecustom?'':'custom|').'documents|conf|install|public\/test|sabre\/sabre\/.*\/tests|Shared\/PCLZip|nusoap\/lib\/Mail|php\/example|php\/test|geoip\/sample.*\.php|ckeditor\/samples|ckeditor\/adapters)$'; // Exclude dirs +$regextoexclude='('.($includecustom?'':'custom|').'documents|conf|install|dejavu-fonts-ttf-.*|public\/test|sabre\/sabre\/.*\/tests|Shared\/PCLZip|nusoap\/lib\/Mail|php\/example|php\/test|geoip\/sample.*\.php|ckeditor\/samples|ckeditor\/adapters)$'; // Exclude dirs $files = dol_dir_list(DOL_DOCUMENT_ROOT, 'files', 1, $regextoinclude, $regextoexclude, 'fullname'); $dir=''; $needtoclose=0; foreach ($files as $filetmp) { - $file = $filetmp['fullname']; - //$newdir = str_replace(dirname(__FILE__).'/../htdocs', '', dirname($file)); - $newdir = str_replace(DOL_DOCUMENT_ROOT, '', dirname($file)); - if ($newdir!=$dir) { - if ($needtoclose) { - fputs($fp, ' '."\n"); - } - fputs($fp, ' '."\n"); - $dir = $newdir; - $needtoclose=1; - } - if (filetype($file)=="file") { - $md5=md5_file($file); - $checksumconcat[]=$md5; - fputs($fp, ' '.$md5.''."\n"); - } + $file = $filetmp['fullname']; + //$newdir = str_replace(dirname(__FILE__).'/../htdocs', '', dirname($file)); + $newdir = str_replace(DOL_DOCUMENT_ROOT, '', dirname($file)); + if ($newdir!=$dir) { + if ($needtoclose) { + fputs($fp, ' '."\n"); + } + fputs($fp, ' '."\n"); + $dir = $newdir; + $needtoclose=1; + } + if (filetype($file)=="file") { + $md5=md5_file($file); + $checksumconcat[]=$md5; + fputs($fp, ' '.$md5.''."\n"); + } } fputs($fp, ' '."\n"); fputs($fp, ''."\n"); @@ -200,22 +207,23 @@ $files = dol_dir_list(dirname(__FILE__).'/../scripts/', 'files', 1, $regextoincl $dir=''; $needtoclose=0; foreach ($files as $filetmp) { - $file = $filetmp['fullname']; - //$newdir = str_replace(dirname(__FILE__).'/../scripts', '', dirname($file)); - $newdir = str_replace(DOL_DOCUMENT_ROOT, '', dirname($file)); - $newdir = str_replace(dirname(__FILE__).'/../scripts', '', dirname($file)); - if ($newdir!=$dir) { - if ($needtoclose) - fputs($fp, ' '."\n"); - fputs($fp, ' '."\n"); - $dir = $newdir; - $needtoclose=1; - } - if (filetype($file)=="file") { - $md5=md5_file($file); - $checksumconcat[]=$md5; - fputs($fp, ' '.$md5.''."\n"); - } + $file = $filetmp['fullname']; + //$newdir = str_replace(dirname(__FILE__).'/../scripts', '', dirname($file)); + $newdir = str_replace(DOL_DOCUMENT_ROOT, '', dirname($file)); + $newdir = str_replace(dirname(__FILE__).'/../scripts', '', dirname($file)); + if ($newdir!=$dir) { + if ($needtoclose) { + fputs($fp, ' '."\n"); + } + fputs($fp, ' '."\n"); + $dir = $newdir; + $needtoclose=1; + } + if (filetype($file)=="file") { + $md5=md5_file($file); + $checksumconcat[]=$md5; + fputs($fp, ' '.$md5.''."\n"); + } } fputs($fp, ' '."\n"); fputs($fp, ''."\n"); diff --git a/build/makepack-dolibarr.pl b/build/makepack-dolibarr.pl index 0fe73fd9fb8..906601d94d4 100755 --- a/build/makepack-dolibarr.pl +++ b/build/makepack-dolibarr.pl @@ -390,6 +390,9 @@ if ($nboftargetok) { $olddir=getcwd(); chdir("$SOURCE"); + print "Clean $SOURCE/htdocs\n"; + $ret=`rm -f $SOURCE/htdocs/includes/autoload.php`; + $ret=`git ls-files . --exclude-standard --others`; if ($ret) { @@ -613,7 +616,6 @@ if ($nboftargetok) { $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/nnnick/chartjs/test`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/nusoap/lib/Mail`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/nusoap/samples`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/parsedown/LICENSE.txt`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/php-iban/docs`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/sabre/sabre/*/tests`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/stripe/tests`; @@ -623,7 +625,6 @@ if ($nboftargetok) { $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tecnickcom/tcpdf/fonts/freefont-*`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tecnickcom/tcpdf/fonts/ae_fonts_*`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tecnickcom/tcpdf/fonts/utils`; - $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/tecnickcom/tcpdf/LICENSE.TXT`; $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/tecnickcom/tcpdf/tools`; $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/vendor`; $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/webmozart`; diff --git a/dev/examples/git/pre-commit b/dev/examples/git/pre-commit deleted file mode 100644 index f89d662ae65..00000000000 --- a/dev/examples/git/pre-commit +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/sh - -PROJECT=`php -r "echo dirname(dirname(dirname(realpath('$0'))));"` -STAGED_FILES_CMD=`git diff --cached --name-only --diff-filter=ACMR HEAD | grep \\\\.php` - -# Determine if a file list is passed -if [ "$#" -eq 1 ] -then - oIFS=$IFS - IFS=' - ' - SFILES="$1" - IFS=$oIFS -fi -SFILES=${SFILES:-$STAGED_FILES_CMD} - -echo "Checking PHP Lint..." -for FILE in $SFILES -do - php -l -d display_errors=0 $PROJECT/$FILE - if [ $? != 0 ] - then - echo "Fix the error before commit." - exit 1 - fi - FILES="$FILES $PROJECT/$FILE" -done - -if [ "$FILES" != "" ] -then - echo "Running PHPCS Code Sniffer..." - #~/vendor/bin/phpcs --version - #phpcs --standard=PSR2 --encoding=utf-8 -n -p $FILES - # Check Dolibarr standard - ~/vendor/bin/phpcs -s -p -d memory_limit=-1 --parallel=2 --extensions=php --colors --tab-width=4 --standard=dev/setup/codesniffer/ruleset.xml --encoding=utf-8 --runtime-set ignore_warnings_on_exit true $FILES - # Check your own standard - #~/vendor/bin/phpcs -s -p -d memory_limit=-1 --parallel=2 --extensions=php --colors --tab-width=4 --standard=htdocs/custom/codesniffer/ruleset.xml --encoding=utf-8 --runtime-set ignore_warnings_on_exit true $FILES - - if [ $? != 0 ] - then - # fix standard errors - ~/vendor/bin/phpcbf -s -p -d memory_limit=-1 --extensions=php --colors --tab-width=4 --standard=dev/setup/codesniffer/ruleset.xml --encoding=utf-8 --runtime-set ignore_warnings_on_exit true $FILES - #~/vendor/bin/phpcbf -s -p -d memory_limit=-1 --extensions=php --colors --tab-width=4 --standard=htdocs/custom/codesniffer/ruleset.xml --encoding=utf-8 --runtime-set ignore_warnings_on_exit true $FILES - echo "Fix the error before commit." - exit 1 - fi -fi - -exit $? diff --git a/dev/initdata/dbf/import-dbf.php b/dev/initdata/dbf/import-dbf.php index 0718a472cd6..ba1da9722d6 100644 --- a/dev/initdata/dbf/import-dbf.php +++ b/dev/initdata/dbf/import-dbf.php @@ -30,8 +30,8 @@ $script_file = basename(__FILE__); $path = dirname(__FILE__) . '/'; if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; } // Recupere root dolibarr @@ -62,40 +62,40 @@ $startlinenb = empty($argv[3]) ? 1 : (int) $argv[3]; $endlinenb = empty($argv[4]) ? 0 : (int) $argv[4]; if (empty($filepath)) { - print "Usage: php $script_file myfilepath.dbf [removeChatColumnName] [startlinenb] [endlinenb]\n"; - print "Example: php $script_file myfilepath.dbf 0 2 1002\n"; - print "\n"; - exit(-1); + print "Usage: php $script_file myfilepath.dbf [removeChatColumnName] [startlinenb] [endlinenb]\n"; + print "Example: php $script_file myfilepath.dbf 0 2 1002\n"; + print "\n"; + exit(-1); } if (!file_exists($filepath)) { - print "Error: File " . $filepath . " not found.\n"; - print "\n"; - exit(-1); + print "Error: File " . $filepath . " not found.\n"; + print "\n"; + exit(-1); } $ret = $user->fetch('', 'admin'); if (!$ret > 0) { - print 'A user with login "admin" and all permissions must be created to use this script.' . "\n"; - exit; + print 'A user with login "admin" and all permissions must be created to use this script.' . "\n"; + exit; } $user->getrights(); // Ask confirmation if (!$confirmed) { - print "Hit Enter to continue or CTRL+C to stop...\n"; - $input = trim(fgets(STDIN)); + print "Hit Enter to continue or CTRL+C to stop...\n"; + $input = trim(fgets(STDIN)); } // Open input and output files $fhandle = dbase_open($filepath, 0); if (!$fhandle) { - print 'Error: Failed to open file ' . $filepath . "\n"; - exit(1); + print 'Error: Failed to open file ' . $filepath . "\n"; + exit(1); } $fhandleerr = fopen($filepatherr, 'w'); if (!$fhandleerr) { - print 'Error: Failed to open file ' . $filepatherr . "\n"; - exit(1); + print 'Error: Failed to open file ' . $filepatherr . "\n"; + exit(1); } $langs->setDefaultLang($defaultlang); @@ -105,23 +105,23 @@ $table_name = substr(basename($filepath), 0, strpos(basename($filepath), '.')); print 'Info: ' . $record_numbers . " lines in file \n"; $header = dbase_get_header_info($fhandle); if ($deleteTable) { - $db->query("DROP TABLE IF EXISTS `$table_name`"); + $db->query("DROP TABLE IF EXISTS `$table_name`"); } $sqlCreate = "CREATE TABLE IF NOT EXISTS `$table_name` ( `id` INT(11) NOT NULL AUTO_INCREMENT "; $fieldArray = array("`id`"); foreach ($header as $value) { - $fieldName = substr(str_replace('_', '', $value['name']), $startchar); - $fieldArray[] = "`$fieldName`"; - $sqlCreate .= ", `" . $fieldName . "` VARCHAR({$value['length']}) NULL DEFAULT NULL "; + $fieldName = substr(str_replace('_', '', $value['name']), $startchar); + $fieldArray[] = "`$fieldName`"; + $sqlCreate .= ", `" . $fieldName . "` VARCHAR({$value['length']}) NULL DEFAULT NULL "; } $sqlCreate .= ", PRIMARY KEY (`id`)) ENGINE = InnoDB"; $resql = $db->query($sqlCreate); if ($resql !== false) { - print "Table $table_name created\n"; + print "Table $table_name created\n"; } else { - var_dump($db->errno()); - print "Impossible : " . $sqlCreate . "\n"; - die(); + var_dump($db->errno()); + print "Impossible : " . $sqlCreate . "\n"; + die(); } $i = 0; @@ -131,30 +131,33 @@ $fields = implode(',', $fieldArray); //var_dump($fieldArray);die(); $maxLength = 0; for ($i = 1; $i <= $record_numbers; $i++) { - if ($startlinenb && $i < $startlinenb) - continue; - if ($endlinenb && $i > $endlinenb) - continue; - $row = dbase_get_record_with_names($fhandle, $i); - if ($row === false || (isset($row["deleted"]) && $row["deleted"] == '1')) - continue; - $sqlInsert = "INSERT INTO `$table_name`($fields) VALUES (null,"; - array_shift($row); // remove delete column - foreach ($row as $value) { - $sqlInsert .= "'" . $db->escape(utf8_encode($value)) . "', "; - } - replaceable_echo(implode("\t", $row)); - $sqlInsert = rtrim($sqlInsert, ', '); - $sqlInsert .= ")"; - $resql = $db->query($sqlInsert); - if ($resql === false) { - print "Impossible : " . $sqlInsert . "\n"; - var_dump($row, $db->errno()); - die(); - } + if ($startlinenb && $i < $startlinenb) { + continue; + } + if ($endlinenb && $i > $endlinenb) { + continue; + } + $row = dbase_get_record_with_names($fhandle, $i); + if ($row === false || (isset($row["deleted"]) && $row["deleted"] == '1')) { + continue; + } + $sqlInsert = "INSERT INTO `$table_name`($fields) VALUES (null,"; + array_shift($row); // remove delete column + foreach ($row as $value) { + $sqlInsert .= "'" . $db->escape(utf8_encode($value)) . "', "; + } + replaceable_echo(implode("\t", $row)); + $sqlInsert = rtrim($sqlInsert, ', '); + $sqlInsert .= ")"; + $resql = $db->query($sqlInsert); + if ($resql === false) { + print "Impossible : " . $sqlInsert . "\n"; + var_dump($row, $db->errno()); + die(); + } // $fields = (object) $row; // var_dump($fields); - continue; + continue; } die(); @@ -166,11 +169,11 @@ die(); print "Nb of lines qualified: " . $nboflines . "\n"; print "Nb of errors: " . $error . "\n"; if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) { - print "Rollback any changes.\n"; - $db->rollback(); + print "Rollback any changes.\n"; + $db->rollback(); } else { - print "Commit all changes.\n"; - $db->commit(); + print "Commit all changes.\n"; + $db->commit(); } $db->close(); @@ -189,43 +192,43 @@ exit($error); */ function replaceable_echo($message, $force_clear_lines = null) { - static $last_lines = 0; + static $last_lines = 0; - if (!is_null($force_clear_lines)) { - $last_lines = $force_clear_lines; - } + if (!is_null($force_clear_lines)) { + $last_lines = $force_clear_lines; + } - $toss = array(); - $status = 0; - $term_width = exec('tput cols', $toss, $status); - if ($status) { - $term_width = 64; // Arbitrary fall-back term width. - } + $toss = array(); + $status = 0; + $term_width = exec('tput cols', $toss, $status); + if ($status) { + $term_width = 64; // Arbitrary fall-back term width. + } - $line_count = 0; - foreach (explode("\n", $message) as $line) { - $line_count += count(str_split($line, $term_width)); - } + $line_count = 0; + foreach (explode("\n", $message) as $line) { + $line_count += count(str_split($line, $term_width)); + } - // Erasure MAGIC: Clear as many lines as the last output had. - for ($i = 0; $i < $last_lines; $i++) { - // Return to the beginning of the line - echo "\r"; - // Erase to the end of the line - echo "\033[K"; - // Move cursor Up a line - echo "\033[1A"; - // Return to the beginning of the line - echo "\r"; - // Erase to the end of the line - echo "\033[K"; - // Return to the beginning of the line - echo "\r"; - // Can be consolodated into - // echo "\r\033[K\033[1A\r\033[K\r"; - } + // Erasure MAGIC: Clear as many lines as the last output had. + for ($i = 0; $i < $last_lines; $i++) { + // Return to the beginning of the line + echo "\r"; + // Erase to the end of the line + echo "\033[K"; + // Move cursor Up a line + echo "\033[1A"; + // Return to the beginning of the line + echo "\r"; + // Erase to the end of the line + echo "\033[K"; + // Return to the beginning of the line + echo "\r"; + // Can be consolodated into + // echo "\r\033[K\033[1A\r\033[K\r"; + } - $last_lines = $line_count; + $last_lines = $line_count; - echo $message . "\n"; + echo $message . "\n"; } diff --git a/dev/initdata/dbf/importdb-products.php b/dev/initdata/dbf/importdb-products.php index 2c06c07e103..6da24faee4e 100644 --- a/dev/initdata/dbf/importdb-products.php +++ b/dev/initdata/dbf/importdb-products.php @@ -29,8 +29,8 @@ $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); $path = dirname(__FILE__) . '/'; if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; } // Recupere root dolibarr @@ -50,18 +50,18 @@ $confirmed = 1; $error = 0; $tvas = [ - '1' => "20.00", - '2' => "5.50", - '3' => "0.00", - '4' => "20.60", - '5' => "19.60", + '1' => "20.00", + '2' => "5.50", + '3' => "0.00", + '4' => "20.60", + '5' => "19.60", ]; $tvasD = [ - '1' => "20", - '2' => "5.5", - '3' => "0", - '4' => "20", - '5' => "20", + '1' => "20", + '2' => "5.5", + '3' => "0", + '4' => "20", + '5' => "20", ]; /* @@ -75,159 +75,167 @@ dol_syslog($script_file . " launched with arg " . implode(',', $argv)); $table = $argv[1]; if (empty($argv[1])) { - print "Error: Which table ?\n"; - print "\n"; - exit(-1); + print "Error: Which table ?\n"; + print "\n"; + exit(-1); } $ret = $user->fetch('', 'admin'); if (!$ret > 0) { - print 'A user with login "admin" and all permissions must be created to use this script.' . "\n"; - exit; + print 'A user with login "admin" and all permissions must be created to use this script.' . "\n"; + exit; } $sql = "SELECT * FROM `$table` WHERE 1"; $resql = $db->query($sql); -if ($resql) -while ($fields = $db->fetch_array($resql)) { - $errorrecord = 0; - if ($fields === false) - continue; - $nboflines++; - - $produit = new Product($db); - $produit->type = 0; - $produit->status = 1; - $produit->ref = trim($fields['REF']); - if ($produit->ref == '') - continue; - print "Process line nb " . $j . ", ref " . $produit->ref; - $produit->label = trim($fields['LIBELLE']); - if ($produit->label == '') - $produit->label = $produit->ref; - if (empty($produit->label)) - continue; - //$produit->description = trim($fields[4] . "\n" . ($fields[5] ? $fields[5] . ' x ' . $fields[6] . ' x ' . $fields[7] : '')); - // $produit->volume = price2num($fields[8]); - // $produit->volume_unit = 0; - $produit->weight = price2num($fields['MASSE']); - $produit->weight_units = 0; // -3 = g - //$produit->customcode = $fields[10]; - $produit->barcode = str_pad($fields['CODE'], 12, "0", STR_PAD_LEFT); - $produit->barcode_type = '2'; - $produit->import_key = $fields['CODE']; - - $produit->status = 1; - $produit->status_buy = 1; - - $produit->finished = 1; - - // $produit->multiprices[0] = price2num($fields['TARIF0']); - // $produit->multiprices[1] = price2num($fields['TARIF1']); - // $produit->multiprices[2] = price2num($fields['TARIF2']); - // $produit->multiprices[3] = price2num($fields['TARIF3']); - // $produit->multiprices[4] = price2num($fields['TARIF4']); - // $produit->multiprices[5] = price2num($fields['TARIF5']); - // $produit->multiprices[6] = price2num($fields['TARIF6']); - // $produit->multiprices[7] = price2num($fields['TARIF7']); - // $produit->multiprices[8] = price2num($fields['TARIF8']); - // $produit->multiprices[9] = price2num($fields['TARIF9']); - // $produit->price_min = null; - // $produit->price_min_ttc = null; - // $produit->price = price2num($fields[11]); - // $produit->price_ttc = price2num($fields[12]); - // $produit->price_base_type = 'TTC'; - // $produit->tva_tx = price2num($fields[13]); - $produit->tva_tx = (int) ($tvas[$fields['CODTVA']]); - $produit->tva_npr = 0; - // $produit->cost_price = price2num($fields[16]); - //compta - - $produit->accountancy_code_buy = trim($fields['COMACH']); - $produit->accountancy_code_sell = trim($fields['COMVEN']); - // $produit->accountancy_code_sell_intra=trim($fields['COMVEN']); - // $produit->accountancy_code_sell_export=trim($fields['COMVEN']); - // Extrafields - // $produit->array_options['options_ecotaxdeee'] = price2num($fields[17]); - - $produit->seuil_stock_alerte = $fields['STALERTE']; - $ret = $produit->create($user, 0); - if ($ret < 0) { - print " - Error in create result code = " . $ret . " - " . $produit->errorsToString(); - $errorrecord++; - } else { - print " - Creation OK with ref " . $produit->ref . " - id = " . $ret; - } - - dol_syslog("Add prices"); - - // If we use price level, insert price for each level - if (!$errorrecord && 1) { - //$ret1 = $produit->updatePrice($produit->price_ttc, $produit->price_base_type, $user, $produit->tva_tx, $produit->price_min, 1, $produit->tva_npr, 0, 0, array()); - $ret1 = false; - for ($i = 0; $i < 10; $i++) { - if ($fields['TARIF' . ($i)] == 0) - continue; - $ret1 = $ret1 || $produit->updatePrice(price2num($fields['TARIF' . ($i)]), 'HT', $user, $produit->tva_tx, $produit->price_min, $i + 1, $produit->tva_npr, 0, 0, array()) < 0; +if ($resql) { + while ($fields = $db->fetch_array($resql)) { + $errorrecord = 0; + if ($fields === false) { + continue; } - if ($ret1) { - print " - Error in updatePrice result " . $produit->errorsToString(); + $nboflines++; + + $produit = new Product($db); + $produit->type = 0; + $produit->status = 1; + $produit->ref = trim($fields['REF']); + if ($produit->ref == '') { + continue; + } + print "Process line nb " . $j . ", ref " . $produit->ref; + $produit->label = trim($fields['LIBELLE']); + if ($produit->label == '') { + $produit->label = $produit->ref; + } + if (empty($produit->label)) { + continue; + } + //$produit->description = trim($fields[4] . "\n" . ($fields[5] ? $fields[5] . ' x ' . $fields[6] . ' x ' . $fields[7] : '')); + // $produit->volume = price2num($fields[8]); + // $produit->volume_unit = 0; + $produit->weight = price2num($fields['MASSE']); + $produit->weight_units = 0; // -3 = g + //$produit->customcode = $fields[10]; + $produit->barcode = str_pad($fields['CODE'], 12, "0", STR_PAD_LEFT); + $produit->barcode_type = '2'; + $produit->import_key = $fields['CODE']; + + $produit->status = 1; + $produit->status_buy = 1; + + $produit->finished = 1; + + // $produit->multiprices[0] = price2num($fields['TARIF0']); + // $produit->multiprices[1] = price2num($fields['TARIF1']); + // $produit->multiprices[2] = price2num($fields['TARIF2']); + // $produit->multiprices[3] = price2num($fields['TARIF3']); + // $produit->multiprices[4] = price2num($fields['TARIF4']); + // $produit->multiprices[5] = price2num($fields['TARIF5']); + // $produit->multiprices[6] = price2num($fields['TARIF6']); + // $produit->multiprices[7] = price2num($fields['TARIF7']); + // $produit->multiprices[8] = price2num($fields['TARIF8']); + // $produit->multiprices[9] = price2num($fields['TARIF9']); + // $produit->price_min = null; + // $produit->price_min_ttc = null; + // $produit->price = price2num($fields[11]); + // $produit->price_ttc = price2num($fields[12]); + // $produit->price_base_type = 'TTC'; + // $produit->tva_tx = price2num($fields[13]); + $produit->tva_tx = (int) ($tvas[$fields['CODTVA']]); + $produit->tva_npr = 0; + // $produit->cost_price = price2num($fields[16]); + //compta + + $produit->accountancy_code_buy = trim($fields['COMACH']); + $produit->accountancy_code_sell = trim($fields['COMVEN']); + // $produit->accountancy_code_sell_intra=trim($fields['COMVEN']); + // $produit->accountancy_code_sell_export=trim($fields['COMVEN']); + // Extrafields + // $produit->array_options['options_ecotaxdeee'] = price2num($fields[17]); + + $produit->seuil_stock_alerte = $fields['STALERTE']; + $ret = $produit->create($user, 0); + if ($ret < 0) { + print " - Error in create result code = " . $ret . " - " . $produit->errorsToString(); $errorrecord++; } else { - print " - updatePrice OK"; + print " - Creation OK with ref " . $produit->ref . " - id = " . $ret; } - } + dol_syslog("Add prices"); - // dol_syslog("Add multilangs"); - // Add alternative languages - // if (!$errorrecord && 1) { - // $produit->multilangs['fr_FR'] = array('label' => $produit->label, 'description' => $produit->description, 'note' => $produit->note_private); - // $produit->multilangs['en_US'] = array('label' => $fields[3], 'description' => $produit->description, 'note' => $produit->note_private); - // - // $ret = $produit->setMultiLangs($user); - // if ($ret < 0) { - // print " - Error in setMultiLangs result code = " . $ret . " - " . $produit->errorsToString(); - // $errorrecord++; - // } else { - // print " - setMultiLangs OK"; - // } - // } - - - dol_syslog("Add stocks"); - // stocks - if (!$errorrecord && $fields['STOCK'] != 0) { - $rets = $produit->correct_stock($user, 1, $fields['STOCK'], 0, 'Stock importé'); - if ($rets < 0) { - print " - Error in correct_stock result " . $produit->errorsToString(); - $errorrecord++; - } else { - print " - correct_stock OK"; + // If we use price level, insert price for each level + if (!$errorrecord && 1) { + //$ret1 = $produit->updatePrice($produit->price_ttc, $produit->price_base_type, $user, $produit->tva_tx, $produit->price_min, 1, $produit->tva_npr, 0, 0, array()); + $ret1 = false; + for ($i = 0; $i < 10; $i++) { + if ($fields['TARIF' . ($i)] == 0) { + continue; + } + $ret1 = $ret1 || $produit->updatePrice(price2num($fields['TARIF' . ($i)]), 'HT', $user, $produit->tva_tx, $produit->price_min, $i + 1, $produit->tva_npr, 0, 0, array()) < 0; + } + if ($ret1) { + print " - Error in updatePrice result " . $produit->errorsToString(); + $errorrecord++; + } else { + print " - updatePrice OK"; + } } - } - //update date créa - if (!$errorrecord) { - $date = substr($fields['DATCREA'], 0, 4) . '-' . substr($fields['DATCREA'], 4, 2) . '-' . substr($fields['DATCREA'], 6, 2); - $retd = $db->query("UPDATE `llx_product` SET `datec` = '$date 00:00:00' WHERE `llx_product`.`rowid` = $produit->id"); - if ($retd < 1) { - print " - Error in update date créa result " . $produit->errorsToString(); - $errorrecord++; - } else { - print " - update date créa OK"; + + // dol_syslog("Add multilangs"); + // Add alternative languages + // if (!$errorrecord && 1) { + // $produit->multilangs['fr_FR'] = array('label' => $produit->label, 'description' => $produit->description, 'note' => $produit->note_private); + // $produit->multilangs['en_US'] = array('label' => $fields[3], 'description' => $produit->description, 'note' => $produit->note_private); + // + // $ret = $produit->setMultiLangs($user); + // if ($ret < 0) { + // print " - Error in setMultiLangs result code = " . $ret . " - " . $produit->errorsToString(); + // $errorrecord++; + // } else { + // print " - setMultiLangs OK"; + // } + // } + + + dol_syslog("Add stocks"); + // stocks + if (!$errorrecord && $fields['STOCK'] != 0) { + $rets = $produit->correct_stock($user, 1, $fields['STOCK'], 0, 'Stock importé'); + if ($rets < 0) { + print " - Error in correct_stock result " . $produit->errorsToString(); + $errorrecord++; + } else { + print " - correct_stock OK"; + } } - } - print "\n"; - if ($errorrecord) { - print( 'Error on record nb ' . $i . " - " . $produit->errorsToString() . "\n"); - var_dump($db); - die(); - $error++; // $errorrecord will be reset + //update date créa + if (!$errorrecord) { + $date = substr($fields['DATCREA'], 0, 4) . '-' . substr($fields['DATCREA'], 4, 2) . '-' . substr($fields['DATCREA'], 6, 2); + $retd = $db->query("UPDATE `llx_product` SET `datec` = '$date 00:00:00' WHERE `llx_product`.`rowid` = $produit->id"); + if ($retd < 1) { + print " - Error in update date créa result " . $produit->errorsToString(); + $errorrecord++; + } else { + print " - update date créa OK"; + } + } + print "\n"; + + if ($errorrecord) { + print( 'Error on record nb ' . $i . " - " . $produit->errorsToString() . "\n"); + var_dump($db); + die(); + $error++; // $errorrecord will be reset + } + $j++; } - $j++; -} else die("error : $sql"); +} else { + die("error : $sql"); +} diff --git a/dev/initdata/dbf/importdb-thirdparties.php b/dev/initdata/dbf/importdb-thirdparties.php index a6b2697eed8..ecb1820fad1 100644 --- a/dev/initdata/dbf/importdb-thirdparties.php +++ b/dev/initdata/dbf/importdb-thirdparties.php @@ -29,8 +29,8 @@ $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); $path = dirname(__FILE__) . '/'; if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; } // Recupere root dolibarr @@ -50,73 +50,73 @@ $confirmed = 1; $error = 0; $civilPrivate = array("MLLE", - "MM", - "MM/MADAME", - "MME", - "MME.", - "MME²", - "MMONSIEUR", - "MMR", - "MOBNSIEUR", - "MOMSIEUR", - "MON SIEUR", - "MONDIAL", - "MONIEUR", - "MONJSIEUR", - "MONNSIEUR", - "MONRIEUR", - "MONS", - "MONSIEÕR", - "MONSIER", - "MONSIERU", - "MONSIEU", - "monsieue", - "MONSIEUR", - "Monsieur     \"", - "MONSIEUR    \"", - "MONSIEUR   E", - "MONSIEUR  DENIS", - "MONSIEUR ET MME", - "MONSIEUR!", - "MONSIEUR.", - "MONSIEUR.MADAME", - "MONSIEUR3", - "MONSIEURN", - "MONSIEURT", - "MONSIEUR£", - "MONSIEYR", - "Monsigur", - "MONSIIEUR", - "MONSIUER", - "MONSIZEUR", - "MOPNSIEUR", - "MOSIEUR", - "MR", - "Mr  Mme", - "Mr - MME", - "MR BLANC", - "MR ET MME", - "mr mm", - "MR OU MME", - "Mr.", - "MR/MME", - "MRME", - "MRR", - "Mrs", - "Mademoiselle", - "MADAOME", - "madamme", - "MADAME", - "M0NSIEUR", - "M.et Madame", - "M. ET MR", - "M.", - "M%", - "M MME", - "M ET MME", - "M", - "M CROCE", - "M DIEVART", + "MM", + "MM/MADAME", + "MME", + "MME.", + "MME²", + "MMONSIEUR", + "MMR", + "MOBNSIEUR", + "MOMSIEUR", + "MON SIEUR", + "MONDIAL", + "MONIEUR", + "MONJSIEUR", + "MONNSIEUR", + "MONRIEUR", + "MONS", + "MONSIEÕR", + "MONSIER", + "MONSIERU", + "MONSIEU", + "monsieue", + "MONSIEUR", + "Monsieur     \"", + "MONSIEUR    \"", + "MONSIEUR   E", + "MONSIEUR  DENIS", + "MONSIEUR ET MME", + "MONSIEUR!", + "MONSIEUR.", + "MONSIEUR.MADAME", + "MONSIEUR3", + "MONSIEURN", + "MONSIEURT", + "MONSIEUR£", + "MONSIEYR", + "Monsigur", + "MONSIIEUR", + "MONSIUER", + "MONSIZEUR", + "MOPNSIEUR", + "MOSIEUR", + "MR", + "Mr  Mme", + "Mr - MME", + "MR BLANC", + "MR ET MME", + "mr mm", + "MR OU MME", + "Mr.", + "MR/MME", + "MRME", + "MRR", + "Mrs", + "Mademoiselle", + "MADAOME", + "madamme", + "MADAME", + "M0NSIEUR", + "M.et Madame", + "M. ET MR", + "M.", + "M%", + "M MME", + "M ET MME", + "M", + "M CROCE", + "M DIEVART", ); /* @@ -130,128 +130,134 @@ dol_syslog($script_file . " launched with arg " . implode(',', $argv)); $table = $argv[1]; if (empty($argv[1])) { - print "Error: Quelle table ?\n"; - print "\n"; - exit(-1); + print "Error: Quelle table ?\n"; + print "\n"; + exit(-1); } $ret = $user->fetch('', 'admin'); if (!$ret > 0) { - print 'A user with login "admin" and all permissions must be created to use this script.' . "\n"; - exit; + print 'A user with login "admin" and all permissions must be created to use this script.' . "\n"; + exit; } $sql = "SELECT * FROM `$table` WHERE 1 "; //ORDER BY REMISE DESC,`LCIVIL` DESC"; $resql = $db->query($sql); //$db->begin(); -if ($resql) -while ($fields = $db->fetch_array($resql)) { - $i++; - $errorrecord = 0; +if ($resql) { + while ($fields = $db->fetch_array($resql)) { + $i++; + $errorrecord = 0; - if ($startlinenb && $i < $startlinenb) - continue; - if ($endlinenb && $i > $endlinenb) - continue; - - $nboflines++; - - $object = new Societe($db); - $object->import_key = $fields['CODE']; - $object->state = 1; - $object->client = 3; - $object->fournisseur = 0; - - $object->name = $fields['FCIVIL'] . ' ' . $fields['FNOM']; - //$object->name_alias = $fields[0] != $fields[13] ? trim($fields[0]) : ''; - - $date = $fields['DATCREA'] ? $fields['DATCREA'] : ($fields['DATMOD'] ? $fields['DATMOD'] : '20200101'); - $object->code_client = 'CU' . substr($date, 2, 2) . substr($date, 4, 2) . '-' . str_pad(substr($fields['CODE'], 0, 5), 5, "0", STR_PAD_LEFT); - - - $object->address = trim($fields['FADR1']); - if ($fields['FADR2']) - $object->address .= "\n" . trim($fields['FADR2']); - if ($fields['FADR3']) - $object->address .= "\n" . trim($fields['FADR3']); - - $object->zip = trim($fields['FPOSTE']); - $object->town = trim($fields['FVILLE']); - if ($fields['FPAYS']) - $object->country_id = dol_getIdFromCode($db, trim(ucwords(strtolower($fields['FPAYS']))), 'c_country', 'label', 'rowid'); - else $object->country_id = 1; - $object->phone = trim($fields['FTEL']) ? trim($fields['FTEL']) : trim($fields['FCONTACT']); - $object->phone = substr($object->phone, 0, 20); - $object->fax = trim($fields['FFAX']) ? trim($fields['FFAX']) : trim($fields['FCONTACT']); - $object->fax = substr($object->fax, 0, 20); - $object->email = trim($fields['FMAIL']); - // $object->idprof2 = trim($fields[29]); - $object->tva_intra = str_replace(['.', ' '], '', $fields['TVAINTRA']); - $object->tva_intra = substr($object->tva_intra, 0, 20); - $object->default_lang = 'fr_FR'; - - $object->cond_reglement_id = dol_getIdFromCode($db, 'PT_ORDER', 'c_payment_term', 'code', 'rowid', 1); - $object->multicurrency_code = 'EUR'; - - if ($fields['REMISE'] != '0.00') { - $object->remise_percent = abs($fields['REMISE']); - } - - // $object->code_client = $fields[9]; - // $object->code_fournisseur = $fields[10]; - - - if ($fields['FCIVIL']) { - $labeltype = in_array($fields['FCIVIL'], $civilPrivate) ? 'TE_PRIVATE' : 'TE_SMALL'; - $object->typent_id = dol_getIdFromCode($db, $labeltype, 'c_typent', 'code'); - } - - // Set price level - $object->price_level = $fields['TARIF'] + 1; - // if ($labeltype == 'Revendeur') - // $object->price_level = 2; - - print "Process line nb " . $i . ", code " . $fields['CODE'] . ", name " . $object->name; - - - // Extrafields - $object->array_options['options_banque'] = $fields['BANQUE']; - $object->array_options['options_banque2'] = $fields['BANQUE2']; - $object->array_options['options_banquevalid'] = $fields['VALID']; - - if (!$errorrecord) { - $ret = $object->create($user); - if ($ret < 0) { - print " - Error in create result code = " . $ret . " - " . $object->errorsToString(); - $errorrecord++; - var_dump($object->code_client, $db); - die(); - } else { - print " - Creation OK with name " . $object->name . " - id = " . $ret; + if ($startlinenb && $i < $startlinenb) { + continue; + } + if ($endlinenb && $i > $endlinenb) { + continue; } - } - if (!$errorrecord) { - dol_syslog("Set price level"); - $object->set_price_level($object->price_level, $user); - } - if (!$errorrecord && @$object->remise_percent) { - dol_syslog("Set remise client"); - $object->set_remise_client($object->remise_percent, 'Importé', $user); - } + $nboflines++; - dol_syslog("Add contact"); - // Insert an invoice contact if there is an invoice email != standard email - if (!$errorrecord && ($fields['LCIVIL'] || $fields['LNOM'])) { - $madame = array("MADAME", + $object = new Societe($db); + $object->import_key = $fields['CODE']; + $object->state = 1; + $object->client = 3; + $object->fournisseur = 0; + + $object->name = $fields['FCIVIL'] . ' ' . $fields['FNOM']; + //$object->name_alias = $fields[0] != $fields[13] ? trim($fields[0]) : ''; + + $date = $fields['DATCREA'] ? $fields['DATCREA'] : ($fields['DATMOD'] ? $fields['DATMOD'] : '20200101'); + $object->code_client = 'CU' . substr($date, 2, 2) . substr($date, 4, 2) . '-' . str_pad(substr($fields['CODE'], 0, 5), 5, "0", STR_PAD_LEFT); + + + $object->address = trim($fields['FADR1']); + if ($fields['FADR2']) { + $object->address .= "\n" . trim($fields['FADR2']); + } + if ($fields['FADR3']) { + $object->address .= "\n" . trim($fields['FADR3']); + } + + $object->zip = trim($fields['FPOSTE']); + $object->town = trim($fields['FVILLE']); + if ($fields['FPAYS']) { + $object->country_id = dol_getIdFromCode($db, trim(ucwords(strtolower($fields['FPAYS']))), 'c_country', 'label', 'rowid'); + } else { + $object->country_id = 1; + } + $object->phone = trim($fields['FTEL']) ? trim($fields['FTEL']) : trim($fields['FCONTACT']); + $object->phone = substr($object->phone, 0, 20); + $object->fax = trim($fields['FFAX']) ? trim($fields['FFAX']) : trim($fields['FCONTACT']); + $object->fax = substr($object->fax, 0, 20); + $object->email = trim($fields['FMAIL']); + // $object->idprof2 = trim($fields[29]); + $object->tva_intra = str_replace(['.', ' '], '', $fields['TVAINTRA']); + $object->tva_intra = substr($object->tva_intra, 0, 20); + $object->default_lang = 'fr_FR'; + + $object->cond_reglement_id = dol_getIdFromCode($db, 'PT_ORDER', 'c_payment_term', 'code', 'rowid', 1); + $object->multicurrency_code = 'EUR'; + + if ($fields['REMISE'] != '0.00') { + $object->remise_percent = abs($fields['REMISE']); + } + + // $object->code_client = $fields[9]; + // $object->code_fournisseur = $fields[10]; + + + if ($fields['FCIVIL']) { + $labeltype = in_array($fields['FCIVIL'], $civilPrivate) ? 'TE_PRIVATE' : 'TE_SMALL'; + $object->typent_id = dol_getIdFromCode($db, $labeltype, 'c_typent', 'code'); + } + + // Set price level + $object->price_level = $fields['TARIF'] + 1; + // if ($labeltype == 'Revendeur') + // $object->price_level = 2; + + print "Process line nb " . $i . ", code " . $fields['CODE'] . ", name " . $object->name; + + + // Extrafields + $object->array_options['options_banque'] = $fields['BANQUE']; + $object->array_options['options_banque2'] = $fields['BANQUE2']; + $object->array_options['options_banquevalid'] = $fields['VALID']; + + if (!$errorrecord) { + $ret = $object->create($user); + if ($ret < 0) { + print " - Error in create result code = " . $ret . " - " . $object->errorsToString(); + $errorrecord++; + var_dump($object->code_client, $db); + die(); + } else { + print " - Creation OK with name " . $object->name . " - id = " . $ret; + } + } + + if (!$errorrecord) { + dol_syslog("Set price level"); + $object->set_price_level($object->price_level, $user); + } + if (!$errorrecord && @$object->remise_percent) { + dol_syslog("Set remise client"); + $object->set_remise_client($object->remise_percent, 'Importé', $user); + } + + dol_syslog("Add contact"); + // Insert an invoice contact if there is an invoice email != standard email + if (!$errorrecord && ($fields['LCIVIL'] || $fields['LNOM'])) { + $madame = array("MADAME", "MADEMOISELLE", "MELLE", "MLLE", "MM", "Mme", "MNE", - ); - $monsieur = array("M", + ); + $monsieur = array("M", "M ET MME", "M MME", "M.", @@ -268,77 +274,84 @@ while ($fields = $db->fetch_array($resql)) { "MONSIUER", "MONSKIEUR", "MR", - ); - $ret1 = $ret2 = 0; + ); + $ret1 = $ret2 = 0; - $contact = new Contact($db); - if (in_array($fields['LCIVIL'], $madame)) { - // une dame - $contact->civility_id = 'MME'; - $contact->lastname = $fields['LNOM']; - } elseif (in_array($fields['LCIVIL'], $monsieur)) { - // un monsieur - $contact->civility_id = 'MR'; - $contact->lastname = $fields['LNOM']; - } elseif (in_array($fields['LCIVIL'], ['DOCTEUR'])) { - // un monsieur - $contact->civility_id = 'DR'; - $contact->lastname = $fields['LNOM']; - } else { - // un a rattraper - $contact->lastname = $fields['LCIVIL'] . " " . $fields['LNOM']; - } - $contact->address = trim($fields['LADR1']); - if ($fields['LADR2']) - $contact->address .= "\n" . trim($fields['LADR2']); - if ($fields['LADR3']) - $contact->address .= "\n" . trim($fields['LADR3']); + $contact = new Contact($db); + if (in_array($fields['LCIVIL'], $madame)) { + // une dame + $contact->civility_id = 'MME'; + $contact->lastname = $fields['LNOM']; + } elseif (in_array($fields['LCIVIL'], $monsieur)) { + // un monsieur + $contact->civility_id = 'MR'; + $contact->lastname = $fields['LNOM']; + } elseif (in_array($fields['LCIVIL'], ['DOCTEUR'])) { + // un monsieur + $contact->civility_id = 'DR'; + $contact->lastname = $fields['LNOM']; + } else { + // un a rattraper + $contact->lastname = $fields['LCIVIL'] . " " . $fields['LNOM']; + } + $contact->address = trim($fields['LADR1']); + if ($fields['LADR2']) { + $contact->address .= "\n" . trim($fields['LADR2']); + } + if ($fields['LADR3']) { + $contact->address .= "\n" . trim($fields['LADR3']); + } - $contact->zip = trim($fields['LPOSTE']); - $contact->town = trim($fields['LVILLE']); - if ($fields['FPAYS']) - $contact->country_id = dol_getIdFromCode($db, trim(ucwords(strtolower($fields['LPAYS']))), 'c_country', 'label', 'rowid'); - else $contact->country_id = 1; - $contact->email = $fields['LMAIL']; - $contact->phone = trim($fields['LTEL']) ? trim($fields['LTEL']) : trim($fields['LCONTACT']); - $contact->fax = trim($fields['LFAX']) ? trim($fields['LFAX']) : trim($fields['LCONTACT']); - $contact->socid = $object->id; + $contact->zip = trim($fields['LPOSTE']); + $contact->town = trim($fields['LVILLE']); + if ($fields['FPAYS']) { + $contact->country_id = dol_getIdFromCode($db, trim(ucwords(strtolower($fields['LPAYS']))), 'c_country', 'label', 'rowid'); + } else { + $contact->country_id = 1; + } + $contact->email = $fields['LMAIL']; + $contact->phone = trim($fields['LTEL']) ? trim($fields['LTEL']) : trim($fields['LCONTACT']); + $contact->fax = trim($fields['LFAX']) ? trim($fields['LFAX']) : trim($fields['LCONTACT']); + $contact->socid = $object->id; - $ret1 = $contact->create($user); - if ($ret1 > 0) { - //$ret2=$contact->add_contact($object->id, 'BILLING'); + $ret1 = $contact->create($user); + if ($ret1 > 0) { + //$ret2=$contact->add_contact($object->id, 'BILLING'); + } + if ($ret1 < 0 || $ret2 < 0) { + print " - Error in create contact result code = " . $ret1 . " " . $ret2 . " - " . $contact->errorsToString(); + $errorrecord++; + } else { + print " - create contact OK"; + } } - if ($ret1 < 0 || $ret2 < 0) { - print " - Error in create contact result code = " . $ret1 . " " . $ret2 . " - " . $contact->errorsToString(); - $errorrecord++; - } else { - print " - create contact OK"; + + + //update date créa + if (!$errorrecord) { + $datec = substr($date, 0, 4) . '-' . substr($date, 4, 2) . '-' . substr($date, 6, 2); + $retd = $db->query("UPDATE `llx_societe` SET `datec` = '$datec 00:00:00' WHERE `rowid` = $object->id"); + if ($retd < 1) { + print " - Error in update date créa result " . $object->errorsToString(); + $errorrecord++; + } else { + print " - update date créa OK"; + } } + print "\n"; + + if ($errorrecord) { + print( 'Error on record nb ' . $i . " - " . $object->errorsToString() . "\n"); + var_dump($db, $object, $contact); + // $db->rollback(); + die(); + $error++; // $errorrecord will be reset + } + $j++; } - - - //update date créa - if (!$errorrecord) { - $datec = substr($date, 0, 4) . '-' . substr($date, 4, 2) . '-' . substr($date, 6, 2); - $retd = $db->query("UPDATE `llx_societe` SET `datec` = '$datec 00:00:00' WHERE `rowid` = $object->id"); - if ($retd < 1) { - print " - Error in update date créa result " . $object->errorsToString(); - $errorrecord++; - } else { - print " - update date créa OK"; - } - } - print "\n"; - - if ($errorrecord) { - print( 'Error on record nb ' . $i . " - " . $object->errorsToString() . "\n"); - var_dump($db, $object, $contact); - // $db->rollback(); - die(); - $error++; // $errorrecord will be reset - } - $j++; -} else die("error : $sql"); +} else { + die("error : $sql"); +} $db->commit(); diff --git a/dev/initdata/dbf/includes/dbase.class.php b/dev/initdata/dbf/includes/dbase.class.php index e70f18087c4..a225d67cde9 100644 --- a/dev/initdata/dbf/includes/dbase.class.php +++ b/dev/initdata/dbf/includes/dbase.class.php @@ -18,382 +18,582 @@ define('DBASE_TYPE_FOXPRO', 1); */ class DBase { - private $fd; - private $headerLength = 0; - private $fields = array(); - private $fieldCount = 0; - private $recordLength = 0; - private $recordCount = 0; + private $fd; + private $headerLength = 0; + private $fields = array(); + private $fieldCount = 0; + private $recordLength = 0; + private $recordCount = 0; - //resource dbase_open ( string $filename , int $mode ) - public static function open($filename, $mode) + /** + * resource dbase_open + * @param string $filename filename + * @param int $mode mode + * @return DBase + */ + public static function open($filename, $mode) { - if (!file_exists($filename)) - return false; - $modes = array('r', 'w', 'r+'); - $mode = $modes[$mode]; - $fd = fopen($filename, $mode); - if (!$fd) - return false; - return new DBase($fd); - } + if (!file_exists($filename)) { + return false; + } + $modes = array('r', 'w', 'r+'); + $mode = $modes[$mode]; + $fd = fopen($filename, $mode); + if (!$fd) { + return false; + } + return new DBase($fd); + } - //resource dbase_create ( string $filename , array $fields [, int $type = DBASE_TYPE_DBASE ] ) - public static function create($filename, $fields, $type = DBASE_TYPE_DBASE) + /** + * resource dbase_create + * @param string $filename filename + * @param array $fields fields + * @param int $type DBASE_TYPE_DBASE + * @return DBase + */ + public static function create($filename, $fields, $type = DBASE_TYPE_DBASE) { - if (file_exists($filename)) - return false; - $fd = fopen($filename, 'c+'); - if (!$fd) - return false; - // Byte 0 (1 byte): Valid dBASE for DOS file; bits 0-2 indicate version number, bit 3 - // indicates the presence of a dBASE for DOS memo file, bits 4-6 indicate the - // presence of a SQL table, bit 7 indicates the presence of any memo file - // (either dBASE m PLUS or dBASE for DOS) - self::putChar8($fd, 5); - // Byte 1-3 (3 bytes): Date of last update; formatted as YYMMDD - self::putChar8($fd, date('Y') - 1900); - self::putChar8($fd, date('m')); - self::putChar8($fd, date('d')); - // Byte 4-7 (32-bit number): Number of records in the database file. Currently 0 - self::putInt32($fd, 0); - // Byte 8-9 (16-bit number): Number of bytes in the header. - self::putInt16($fd, 32 + (32 * count($fields)) + 1); - // Byte 10-11 (16-bit number): Number of bytes in record. - // Make sure the include the byte for deleted flag - $len = 1; - foreach ($fields as &$field) - $len += self::length($field); - self::putInt16($fd, $len); - // Byte 12-13 (2 bytes): Reserved, 0 filled. - self::putInt16($fd, 0); - // Byte 14 (1 byte): Flag indicating incomplete transaction - // The ISMARKEDO function checks this flag. BEGIN TRANSACTION sets it to 1, END TRANSACTION and ROLLBACK reset it to 0. - self::putChar8($fd, 0); - // Byte 15 (1 byte): Encryption flag. If this flag is set to 1, the message Database encrypted appears. Changing this flag to 0 removes the message, but does not decrypt the file. - self::putChar8($fd, 0); - // Byte 16-27 (12 bytes): Reserved for dBASE for DOS in a multi-user environment - self::putInt32($fd, 0); - self::putInt32($fd, 0); - self::putInt32($fd, 0); - // Byte 28 (1 byte): Production .mdx file flag; 0x01 if there is a production .mdx file, 0x00 if not - self::putChar8($fd, 0); - // Byte 29 (1 byte): Language driver ID - // (no clue what this is) - self::putChar8($fd, 0); - // Byte 30-31 (2 bytes): Reserved, 0 filled. - self::putInt16($fd, 0); - // Byte 32 - n (32 bytes each): Field descriptor array - foreach ($fields as &$field) { - self::putString($fd, $field[0], 11); // Byte 0 - 10 (11 bytes): Field name in ASCII (zero-filled) - self::putString($fd, $field[1], 1); // Byte 11 (1 byte): Field type in ASCII (C, D, F, L, M, or N) - self::putInt32($fd, 0); // Byte 12 - 15 (4 bytes): Reserved - self::putChar8($fd, self::length($field)); // Byte 16 (1 byte): Field length in binary. The maximum length of a field is 254 (0xFE). - self::putChar8($fd, $field[3]); // Byte 17 (1 byte): Field decimal count in binary - self::putInt16($fd, 0); // Byte 18 - 19 (2 bytes): Work area ID - self::putChar8($fd, 0); // Byte 20 (1 byte): Example (??) - self::putInt32($fd, 0); // Byte 21 - 30 (10 bytes): Reserved - self::putInt32($fd, 0); - self::putInt16($fd, 0); - self::putChar8($fd, 0); // Byte 31 (1 byte): Production MDX field flag; 1 if field has an index tag in the production MDX file, 0 if not - } - // Byte n + 1 (1 byte): 0x0D as the field descriptor array terminator - self::putChar8($fd, 0x0D); - return new DBase($fd); - } + if (file_exists($filename)) { + return false; + } + $fd = fopen($filename, 'c+'); + if (!$fd) { + return false; + } + // Byte 0 (1 byte): Valid dBASE for DOS file; bits 0-2 indicate version number, bit 3 + // indicates the presence of a dBASE for DOS memo file, bits 4-6 indicate the + // presence of a SQL table, bit 7 indicates the presence of any memo file + // (either dBASE m PLUS or dBASE for DOS) + self::putChar8($fd, 5); + // Byte 1-3 (3 bytes): Date of last update; formatted as YYMMDD + self::putChar8($fd, date('Y') - 1900); + self::putChar8($fd, date('m')); + self::putChar8($fd, date('d')); + // Byte 4-7 (32-bit number): Number of records in the database file. Currently 0 + self::putInt32($fd, 0); + // Byte 8-9 (16-bit number): Number of bytes in the header. + self::putInt16($fd, 32 + (32 * count($fields)) + 1); + // Byte 10-11 (16-bit number): Number of bytes in record. + // Make sure the include the byte for deleted flag + $len = 1; + foreach ($fields as &$field) { + $len += self::length($field); + } + self::putInt16($fd, $len); + // Byte 12-13 (2 bytes): Reserved, 0 filled. + self::putInt16($fd, 0); + // Byte 14 (1 byte): Flag indicating incomplete transaction + // The ISMARKEDO function checks this flag. BEGIN TRANSACTION sets it to 1, END TRANSACTION and ROLLBACK reset it to 0. + self::putChar8($fd, 0); + // Byte 15 (1 byte): Encryption flag. If this flag is set to 1, the message Database encrypted appears. Changing this flag to 0 removes the message, but does not decrypt the file. + self::putChar8($fd, 0); + // Byte 16-27 (12 bytes): Reserved for dBASE for DOS in a multi-user environment + self::putInt32($fd, 0); + self::putInt32($fd, 0); + self::putInt32($fd, 0); + // Byte 28 (1 byte): Production .mdx file flag; 0x01 if there is a production .mdx file, 0x00 if not + self::putChar8($fd, 0); + // Byte 29 (1 byte): Language driver ID + // (no clue what this is) + self::putChar8($fd, 0); + // Byte 30-31 (2 bytes): Reserved, 0 filled. + self::putInt16($fd, 0); + // Byte 32 - n (32 bytes each): Field descriptor array + foreach ($fields as &$field) { + self::putString($fd, $field[0], 11); // Byte 0 - 10 (11 bytes): Field name in ASCII (zero-filled) + self::putString($fd, $field[1], 1); // Byte 11 (1 byte): Field type in ASCII (C, D, F, L, M, or N) + self::putInt32($fd, 0); // Byte 12 - 15 (4 bytes): Reserved + self::putChar8($fd, self::length($field)); // Byte 16 (1 byte): Field length in binary. The maximum length of a field is 254 (0xFE). + self::putChar8($fd, $field[3]); // Byte 17 (1 byte): Field decimal count in binary + self::putInt16($fd, 0); // Byte 18 - 19 (2 bytes): Work area ID + self::putChar8($fd, 0); // Byte 20 (1 byte): Example (??) + self::putInt32($fd, 0); // Byte 21 - 30 (10 bytes): Reserved + self::putInt32($fd, 0); + self::putInt16($fd, 0); + self::putChar8($fd, 0); // Byte 31 (1 byte): Production MDX field flag; 1 if field has an index tag in the production MDX file, 0 if not + } + // Byte n + 1 (1 byte): 0x0D as the field descriptor array terminator + self::putChar8($fd, 0x0D); + return new DBase($fd); + } - // Create DBase instance - private function __construct($fd) + /** + * Create DBase instance + * @param mixed $fd file descriptor + * @return void + */ + private function __construct($fd) { - $this->fd = $fd; - // Byte 4-7 (32-bit number): Number of records in the database file. Currently 0 - fseek($this->fd, 4, SEEK_SET); - $this->recordCount = self::getInt32($fd); - // Byte 8-9 (16-bit number): Number of bytes in the header. - fseek($this->fd, 8, SEEK_SET); - $this->headerLength = self::getInt16($fd); - // Number of fields is (headerLength - 33) / 32) - $this->fieldCount = ($this->headerLength - 33) / 32; - // Byte 10-11 (16-bit number): Number of bytes in record. - fseek($this->fd, 10, SEEK_SET); - $this->recordLength = self::getInt16($fd); - // Byte 32 - n (32 bytes each): Field descriptor array - fseek($fd, 32, SEEK_SET); - for ($i = 0; $i < $this->fieldCount; $i++) { - $data = fread($this->fd, 32); - $field = array_map('trim', unpack('a11name/a1type/c4/c1length/c1precision/s1workid/c1example/c10/c1production', $data)); - $this->fields[] = $field; - } - } + $this->fd = $fd; + // Byte 4-7 (32-bit number): Number of records in the database file. Currently 0 + fseek($this->fd, 4, SEEK_SET); + $this->recordCount = self::getInt32($fd); + // Byte 8-9 (16-bit number): Number of bytes in the header. + fseek($this->fd, 8, SEEK_SET); + $this->headerLength = self::getInt16($fd); + // Number of fields is (headerLength - 33) / 32) + $this->fieldCount = ($this->headerLength - 33) / 32; + // Byte 10-11 (16-bit number): Number of bytes in record. + fseek($this->fd, 10, SEEK_SET); + $this->recordLength = self::getInt16($fd); + // Byte 32 - n (32 bytes each): Field descriptor array + fseek($fd, 32, SEEK_SET); + for ($i = 0; $i < $this->fieldCount; $i++) { + $data = fread($this->fd, 32); + $field = array_map('trim', unpack('a11name/a1type/c4/c1length/c1precision/s1workid/c1example/c10/c1production', $data)); + $this->fields[] = $field; + } + } - //bool dbase_close ( resource $dbase_identifier ) - public function close() + /** + * dbase_close + * @return void + */ + public function close() { - fclose($this->fd); - } + fclose($this->fd); + } - //array dbase_get_header_info ( resource $dbase_identifier ) - public function get_header_info() + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * dbase_get_header_info + * @return array + */ + public function get_header_info() { - return $this->fields; - } + // phpcs:disable + return $this->fields; + } - //int dbase_numfields ( resource $dbase_identifier ) - public function numfields() + /** + * dbase_numfields + * @return int + */ + public function numfields() { - return $this->fieldCount; - } + return $this->fieldCount; + } - //int dbase_numrecords ( resource $dbase_identifier ) - public function numrecords() + /** + * dbase_numrecords + * @return int + */ + public function numrecords() { - return $this->recordCount; - } + return $this->recordCount; + } - //bool dbase_add_record ( resource $dbase_identifier , array $record ) - public function add_record($record) + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * dbase_add_record + * @param array $record record + * @return bool + */ + public function add_record($record) { - if (count($record) != $this->fieldCount) - return false; - // Seek to end of file, minus the end of file marker - fseek($this->fd, 0, SEEK_END); - // Put the deleted flag - self::putChar8($this->fd, 0x20); - // Put the record - if (!$this->putRecord($record)) - return false; - // Update the record count - fseek($this->fd, 4); - self::putInt32($this->fd, ++$this->recordCount); - return true; - } + // phpcs:enable + if (count($record) != $this->fieldCount) { + return false; + } + // Seek to end of file, minus the end of file marker + fseek($this->fd, 0, SEEK_END); + // Put the deleted flag + self::putChar8($this->fd, 0x20); + // Put the record + if (!$this->putRecord($record)) { + return false; + } + // Update the record count + fseek($this->fd, 4); + self::putInt32($this->fd, ++$this->recordCount); + return true; + } - //bool dbase_replace_record ( resource $dbase_identifier , array $record , int $record_number ) - public function replace_record($record, $record_number) + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * dbase_replace_record + * @param array $record record + * @param int $record_number record number + * @return bool + */ + public function replace_record($record, $record_number) { - if (count($record) != $this->fieldCount) - return false; - if ($record_number < 1 || $record_number > $this->recordCount) - return false; - // Skip to the record location, plus the 1 byte for the deleted flag - fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1)) + 1); - return $this->putRecord($record); - } + // phpcs:enable + if (count($record) != $this->fieldCount) { + return false; + } + if ($record_number < 1 || $record_number > $this->recordCount) { + return false; + } + // Skip to the record location, plus the 1 byte for the deleted flag + fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1)) + 1); + return $this->putRecord($record); + } - //bool dbase_delete_record ( resource $dbase_identifier , int $record_number ) - public function delete_record($record_number) + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * dbase_delete_record + * @param int $record_number record number + * @return bool + */ + public function delete_record($record_number) { - if ($record_number < 1 || $record_number > $this->recordCount) - return false; - fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1))); - self::putChar8($this->fd, 0x2A); - return true; - } + // phpcs:enable + if ($record_number < 1 || $record_number > $this->recordCount) { + return false; + } + fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1))); + self::putChar8($this->fd, 0x2A); + return true; + } - //array dbase_get_record ( resource $dbase_identifier , int $record_number ) - public function get_record($record_number) + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * dbase_get_record + * @param int $record_number record number + * @return array + */ + public function get_record($record_number) { - if ($record_number < 1 || $record_number > $this->recordCount) - return false; - fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1))); - $record = array( - 'deleted' => self::getChar8($this->fd) == 0x2A ? 1 : 0 - ); - foreach ($this->fields as $i => &$field) { - $value = trim(fread($this->fd, $field['length'])); - if ($field['type'] == 'L') { - $value = strtolower($value); - if ($value == 't' || $value == 'y') - $value = true; - elseif ($value == 'f' || $value == 'n') - $value = false; - else $value = null; - } - $record[$i] = $value; - } - return $record; - } + // phpcs:enable + if ($record_number < 1 || $record_number > $this->recordCount) { + return false; + } + fseek($this->fd, $this->headerLength + ($this->recordLength * ($record_number - 1))); + $record = array( + 'deleted' => self::getChar8($this->fd) == 0x2A ? 1 : 0 + ); + foreach ($this->fields as $i => &$field) { + $value = trim(fread($this->fd, $field['length'])); + if ($field['type'] == 'L') { + $value = strtolower($value); + if ($value == 't' || $value == 'y') { + $value = true; + } elseif ($value == 'f' || $value == 'n') { + $value = false; + } else { + $value = null; + } + } + $record[$i] = $value; + } + return $record; + } - //array dbase_get_record_with_names ( resource $dbase_identifier , int $record_number ) - public function get_record_with_names($record_number) + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * dbase_get_record_with_names + * @param int $record_number record number + * @return array + */ + public function get_record_with_names($record_number) { - if ($record_number < 1 || $record_number > $this->recordCount) - return false; - $record = $this->get_record($record_number); - foreach ($this->fields as $i => &$field) { - $record[$field['name']] = $record[$i]; - unset($record[$i]); - } - return $record; - } + // phpcs:enable + if ($record_number < 1 || $record_number > $this->recordCount) { + return false; + } + $record = $this->get_record($record_number); + foreach ($this->fields as $i => &$field) { + $record[$field['name']] = $record[$i]; + unset($record[$i]); + } + return $record; + } - //bool dbase_pack ( resource $dbase_identifier ) - public function pack() + /** + * dbase_pack + * @return void + */ + public function pack() { - $in_offset = $out_offset = $this->headerLength; - $new_count = 0; - $rec_count = $this->recordCount; - while ($rec_count > 0) { - fseek($this->fd, $in_offset, SEEK_SET); - $record = fread($this->fd, $this->recordLength); - $deleted = substr($record, 0, 1); - if ($deleted != '*') { - fseek($this->fd, $out_offset, SEEK_SET); - fwrite($this->fd, $record); - $out_offset += $this->recordLength; - $new_count++; - } - $in_offset += $this->recordLength; - $rec_count--; - } - ftruncate($this->fd, $out_offset); - // Update the record count - fseek($this->fd, 4); - self::putInt32($this->fd, $new_count); - } + $in_offset = $out_offset = $this->headerLength; + $new_count = 0; + $rec_count = $this->recordCount; + while ($rec_count > 0) { + fseek($this->fd, $in_offset, SEEK_SET); + $record = fread($this->fd, $this->recordLength); + $deleted = substr($record, 0, 1); + if ($deleted != '*') { + fseek($this->fd, $out_offset, SEEK_SET); + fwrite($this->fd, $record); + $out_offset += $this->recordLength; + $new_count++; + } + $in_offset += $this->recordLength; + $rec_count--; + } + ftruncate($this->fd, $out_offset); + // Update the record count + fseek($this->fd, 4); + self::putInt32($this->fd, $new_count); + } - /* - * A few utilitiy functions - */ + /* + * A few utilitiy functions + */ - private static function length($field) + /** + * @param string $field field + * @return int + */ + private static function length($field) { - switch ($field[1]) { - case 'D': // Date: Numbers and a character to separate month, day, and year (stored internally as 8 digits in YYYYMMDD format) - return 8; - case 'T': // DateTime (YYYYMMDDhhmmss.uuu) (FoxPro) - return 18; - case 'M': // Memo (ignored): All ASCII characters (stored internally as 10 digits representing a .dbt block number, right justified, padded with whitespaces) - case 'N': // Number: -.0123456789 (right justified, padded with whitespaces) - case 'F': // Float: -.0123456789 (right justified, padded with whitespaces) - case 'C': // String: All ASCII characters (padded with whitespaces up to the field's length) - return $field[2]; - case 'L': // Boolean: YyNnTtFf? (? when not initialized) - return 1; - } - return 0; - } + switch ($field[1]) { + case 'D': // Date: Numbers and a character to separate month, day, and year (stored internally as 8 digits in YYYYMMDD format) + return 8; + case 'T': // DateTime (YYYYMMDDhhmmss.uuu) (FoxPro) + return 18; + case 'M': // Memo (ignored): All ASCII characters (stored internally as 10 digits representing a .dbt block number, right justified, padded with whitespaces) + case 'N': // Number: -.0123456789 (right justified, padded with whitespaces) + case 'F': // Float: -.0123456789 (right justified, padded with whitespaces) + case 'C': // String: All ASCII characters (padded with whitespaces up to the field's length) + return $field[2]; + case 'L': // Boolean: YyNnTtFf? (? when not initialized) + return 1; + } + return 0; + } - /* - * Functions for reading and writing bytes - */ + /* + * Functions for reading and writing bytes + */ - private static function getChar8($fd) + /** + * getChar8 + * @param mixed $fd file descriptor + * @return int + */ + private static function getChar8($fd) { - return ord(fread($fd, 1)); - } + return ord(fread($fd, 1)); + } - private static function putChar8($fd, $value) + /** + * putChar8 + * @param mixed $fd file descriptor + * @param mixed $value value + * @return bool + */ + private static function putChar8($fd, $value) { - return fwrite($fd, chr($value)); - } + return fwrite($fd, chr($value)); + } - private static function getInt16($fd, $n = 1) + /** + * getInt16 + * @param mixed $fd file descriptor + * @param int $n n + * @return bool + */ + private static function getInt16($fd, $n = 1) { - $data = fread($fd, 2 * $n); - $i = unpack("S$n", $data); - if ($n == 1) - return (int) $i[1]; - else return array_merge($i); - } + $data = fread($fd, 2 * $n); + $i = unpack("S$n", $data); + if ($n == 1) { + return (int) $i[1]; + } else { + return array_merge($i); + } + } - private static function putInt16($fd, $value) + /** + * putInt16 + * @param mixed $fd file descriptor + * @param mixed $value value + * @return bool + */ + private static function putInt16($fd, $value) { - return fwrite($fd, pack('S', $value)); - } + return fwrite($fd, pack('S', $value)); + } - private static function getInt32($fd, $n = 1) + /** + * getInt32 + * @param mixed $fd file descriptor + * @param int $n n + * @return bool + */ + private static function getInt32($fd, $n = 1) { - $data = fread($fd, 4 * $n); - $i = unpack("L$n", $data); - if ($n == 1) - return (int) $i[1]; - else return array_merge($i); - } + $data = fread($fd, 4 * $n); + $i = unpack("L$n", $data); + if ($n == 1) { + return (int) $i[1]; + } else { + return array_merge($i); + } + } - private static function putInt32($fd, $value) + /** + * putint32 + * @param mixed $fd file descriptor + * @param mixed $value value + * @return bool + */ + private static function putInt32($fd, $value) { - return fwrite($fd, pack('L', $value)); - } + return fwrite($fd, pack('L', $value)); + } - private static function putString($fd, $value, $length = 254) + /** + * putString + * @param mixed $fd file descriptor + * @param mixed $value value + * @param int $length length + * @return bool + */ + private static function putString($fd, $value, $length = 254) { - $ret = fwrite($fd, pack('A' . $length, $value)); - } + $ret = fwrite($fd, pack('A' . $length, $value)); + } - private function putRecord($record) + /** + * putRecord + * @param mixed $record record + * @return bool + */ + private function putRecord($record) { - foreach ($this->fields as $i => &$field) { - $value = $record[$i]; - // Number types are right aligned with spaces - if ($field['type'] == 'N' || $field['type'] == 'F' && strlen($value) < $field['length']) { - $value = str_repeat(' ', $field['length'] - strlen($value)) . $value; - } - self::putString($this->fd, $value, $field['length']); - } - return true; - } + foreach ($this->fields as $i => &$field) { + $value = $record[$i]; + // Number types are right aligned with spaces + if ($field['type'] == 'N' || $field['type'] == 'F' && strlen($value) < $field['length']) { + $value = str_repeat(' ', $field['length'] - strlen($value)) . $value; + } + self::putString($this->fd, $value, $field['length']); + } + return true; + } } if (!function_exists('dbase_open')) { - - function dbase_open($filename, $mode) + /** + * dbase_open + * @param string $filename filename + * @param int $mode mode + * @return DBase + */ + function dbase_open($filename, $mode) { - return DBase::open($filename, $mode); - } + return DBase::open($filename, $mode); + } - function dbase_create($filename, $fields, $type = DBASE_TYPE_DBASE) + /** + * dbase_create + * @param string $filename filename + * @param array $fields fields + * @param int $type type + * @return DBase + */ + function dbase_create($filename, $fields, $type = DBASE_TYPE_DBASE) { - return DBase::create($filename, $fields, $type); - } + return DBase::create($filename, $fields, $type); + } - function dbase_close($dbase_identifier) + /** + * dbase_close + * @param Resource $dbase_identifier dbase identifier + * @return bool + */ + function dbase_close($dbase_identifier) { - return $dbase_identifier->close(); - } + return $dbase_identifier->close(); + } - function dbase_get_header_info($dbase_identifier) + /** + * dbase_get_header_info + * @param Resource $dbase_identifier dbase identifier + * @return string + */ + function dbase_get_header_info($dbase_identifier) { - return $dbase_identifier->get_header_info(); - } + return $dbase_identifier->get_header_info(); + } - function dbase_numfields($dbase_identifier) + /** + * dbase_numfields + * @param Resource $dbase_identifier dbase identifier + * @return int + */ + function dbase_numfields($dbase_identifier) { - $dbase_identifier->numfields(); - } + $dbase_identifier->numfields(); + } - function dbase_numrecords($dbase_identifier) + /** + * dbase_numrecords + * @param Resource $dbase_identifier dbase identifier + * @return int + */ + function dbase_numrecords($dbase_identifier) { - return $dbase_identifier->numrecords(); - } + return $dbase_identifier->numrecords(); + } - function dbase_add_record($dbase_identifier, $record) + /** + * dbase_add_record + * @param Resource $dbase_identifier dbase identifier + * @param array $record record + * @return bool + */ + function dbase_add_record($dbase_identifier, $record) { - return $dbase_identifier->add_record($record); - } + return $dbase_identifier->add_record($record); + } - function dbase_delete_record($dbase_identifier, $record_number) + /** + * dbase_delete_record + * @param Resource $dbase_identifier dbase identifier + * @param int $record_number record number + * @return bool + */ + function dbase_delete_record($dbase_identifier, $record_number) { - return $dbase_identifier->delete_record($record_number); - } + return $dbase_identifier->delete_record($record_number); + } - function dbase_replace_record($dbase_identifier, $record, $record_number) + /** + * dbase_replace_record + * @param Resource $dbase_identifier dbase identifier + * @param array $record record + * @param int $record_number record number + * @return bool + */ + function dbase_replace_record($dbase_identifier, $record, $record_number) { - return $dbase_identifier->replace_record($record, $record_number); - } + return $dbase_identifier->replace_record($record, $record_number); + } - function dbase_get_record($dbase_identifier, $record_number) + /** + * dbase_get_record + * @param Resource $dbase_identifier dbase identifier + * @param int $record_number record number + * @return bool + */ + function dbase_get_record($dbase_identifier, $record_number) { - return $dbase_identifier->get_record($record_number); - } + return $dbase_identifier->get_record($record_number); + } - function dbase_get_record_with_names($dbase_identifier, $record_number) + /** + * dbase_get_record_with_names + * @param Resource $dbase_identifier dbase identifier + * @param int $record_number record number + * @return bool + */ + function dbase_get_record_with_names($dbase_identifier, $record_number) { - return $dbase_identifier->get_record_with_names($record_number); - } + return $dbase_identifier->get_record_with_names($record_number); + } - function dbase_pack($dbase_identifier) + /** + * dbase_pack + * @param Resource $dbase_identifier dbase identifier + * @return bool + */ + function dbase_pack($dbase_identifier) { - return $dbase_identifier->pack(); - } + return $dbase_identifier->pack(); + } } diff --git a/dev/initdata/generate-invoice.php b/dev/initdata/generate-invoice.php index c35fe2440ef..4837e5352c7 100755 --- a/dev/initdata/generate-invoice.php +++ b/dev/initdata/generate-invoice.php @@ -48,60 +48,59 @@ require_once DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"; define(GEN_NUMBER_FACTURE, 1); $year = 2016; $dates = array (mktime(12, 0, 0, 1, 3, $year), - mktime(12, 0, 0, 1, 9, $year), - mktime(12, 0, 0, 2, 13, $year), - mktime(12, 0, 0, 2, 23, $year), - mktime(12, 0, 0, 3, 30, $year), - mktime(12, 0, 0, 4, 3, $year), - mktime(12, 0, 0, 4, 3, $year), - mktime(12, 0, 0, 5, 9, $year), - mktime(12, 0, 0, 5, 1, $year), - mktime(12, 0, 0, 5, 13, $year), - mktime(12, 0, 0, 5, 19, $year), - mktime(12, 0, 0, 5, 23, $year), - mktime(12, 0, 0, 6, 3, $year), - mktime(12, 0, 0, 6, 19, $year), - mktime(12, 0, 0, 6, 24, $year), - mktime(12, 0, 0, 7, 3, $year), - mktime(12, 0, 0, 7, 9, $year), - mktime(12, 0, 0, 7, 23, $year), - mktime(12, 0, 0, 7, 30, $year), - mktime(12, 0, 0, 8, 9, $year), - mktime(12, 0, 0, 9, 23, $year), - mktime(12, 0, 0, 10, 3, $year), - mktime(12, 0, 0, 11, 12, $year), - mktime(12, 0, 0, 11, 13, $year), - mktime(12, 0, 0, 1, 3, ($year - 1)), - mktime(12, 0, 0, 1, 9, ($year - 1)), - mktime(12, 0, 0, 2, 13, ($year - 1)), - mktime(12, 0, 0, 2, 23, ($year - 1)), - mktime(12, 0, 0, 3, 30, ($year - 1)), - mktime(12, 0, 0, 4, 3, ($year - 1)), - mktime(12, 0, 0, 4, 3, ($year - 1)), - mktime(12, 0, 0, 5, 9, ($year - 1)), - mktime(12, 0, 0, 5, 1, ($year - 1)), - mktime(12, 0, 0, 5, 13, ($year - 1)), - mktime(12, 0, 0, 5, 19, ($year - 1)), - mktime(12, 0, 0, 5, 23, ($year - 1)), - mktime(12, 0, 0, 6, 3, ($year - 1)), - mktime(12, 0, 0, 6, 19, ($year - 1)), - mktime(12, 0, 0, 6, 24, ($year - 1)), - mktime(12, 0, 0, 7, 3, ($year - 1)), - mktime(12, 0, 0, 7, 9, ($year - 1)), - mktime(12, 0, 0, 7, 23, ($year - 1)), - mktime(12, 0, 0, 7, 30, ($year - 1)), - mktime(12, 0, 0, 8, 9, ($year - 1)), - mktime(12, 0, 0, 9, 23, ($year - 1)), - mktime(12, 0, 0, 10, 3, ($year - 1)), - mktime(12, 0, 0, 11, 12, $year), - mktime(12, 0, 0, 11, 13, $year), - mktime(12, 0, 0, 12, 12, $year), - mktime(12, 0, 0, 12, 13, $year), + mktime(12, 0, 0, 1, 9, $year), + mktime(12, 0, 0, 2, 13, $year), + mktime(12, 0, 0, 2, 23, $year), + mktime(12, 0, 0, 3, 30, $year), + mktime(12, 0, 0, 4, 3, $year), + mktime(12, 0, 0, 4, 3, $year), + mktime(12, 0, 0, 5, 9, $year), + mktime(12, 0, 0, 5, 1, $year), + mktime(12, 0, 0, 5, 13, $year), + mktime(12, 0, 0, 5, 19, $year), + mktime(12, 0, 0, 5, 23, $year), + mktime(12, 0, 0, 6, 3, $year), + mktime(12, 0, 0, 6, 19, $year), + mktime(12, 0, 0, 6, 24, $year), + mktime(12, 0, 0, 7, 3, $year), + mktime(12, 0, 0, 7, 9, $year), + mktime(12, 0, 0, 7, 23, $year), + mktime(12, 0, 0, 7, 30, $year), + mktime(12, 0, 0, 8, 9, $year), + mktime(12, 0, 0, 9, 23, $year), + mktime(12, 0, 0, 10, 3, $year), + mktime(12, 0, 0, 11, 12, $year), + mktime(12, 0, 0, 11, 13, $year), + mktime(12, 0, 0, 1, 3, ($year - 1)), + mktime(12, 0, 0, 1, 9, ($year - 1)), + mktime(12, 0, 0, 2, 13, ($year - 1)), + mktime(12, 0, 0, 2, 23, ($year - 1)), + mktime(12, 0, 0, 3, 30, ($year - 1)), + mktime(12, 0, 0, 4, 3, ($year - 1)), + mktime(12, 0, 0, 4, 3, ($year - 1)), + mktime(12, 0, 0, 5, 9, ($year - 1)), + mktime(12, 0, 0, 5, 1, ($year - 1)), + mktime(12, 0, 0, 5, 13, ($year - 1)), + mktime(12, 0, 0, 5, 19, ($year - 1)), + mktime(12, 0, 0, 5, 23, ($year - 1)), + mktime(12, 0, 0, 6, 3, ($year - 1)), + mktime(12, 0, 0, 6, 19, ($year - 1)), + mktime(12, 0, 0, 6, 24, ($year - 1)), + mktime(12, 0, 0, 7, 3, ($year - 1)), + mktime(12, 0, 0, 7, 9, ($year - 1)), + mktime(12, 0, 0, 7, 23, ($year - 1)), + mktime(12, 0, 0, 7, 30, ($year - 1)), + mktime(12, 0, 0, 8, 9, ($year - 1)), + mktime(12, 0, 0, 9, 23, ($year - 1)), + mktime(12, 0, 0, 10, 3, ($year - 1)), + mktime(12, 0, 0, 11, 12, $year), + mktime(12, 0, 0, 11, 13, $year), + mktime(12, 0, 0, 12, 12, $year), + mktime(12, 0, 0, 12, 13, $year), ); $ret=$user->fetch('', 'admin'); -if (! $ret > 0) -{ +if (! $ret > 0) { print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; exit; } @@ -111,12 +110,10 @@ $user->getrights(); $socids = array(); $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe WHERE client in (1, 3)"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num_thirdparties = $db->num_rows($resql); $i = 0; - while ($i < $num_thirdparties) - { + while ($i < $num_thirdparties) { $i++; $row = $db->fetch_row($resql); $socids[$i] = $row[0]; @@ -126,12 +123,10 @@ if ($resql) $prodids = array(); $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product WHERE tosell=1"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num_prods = $db->num_rows($resql); $i = 0; - while ($i < $num_prods) - { + while ($i < $num_prods) { $i++; $row = $db->fetch_row($resql); $prodids[$i] = $row[0]; @@ -140,8 +135,7 @@ if ($resql) $i=0; $result=0; -while ($i < GEN_NUMBER_FACTURE && $result >= 0) -{ +while ($i < GEN_NUMBER_FACTURE && $result >= 0) { $i++; $socid = mt_rand(1, $num_thirdparties); @@ -153,31 +147,27 @@ while ($i < GEN_NUMBER_FACTURE && $result >= 0) $object->cond_reglement_id = 3; $object->mode_reglement_id = 3; - $fuser = new User($db); - $fuser->fetch(mt_rand(1, 2)); - $fuser->getRights(); + $fuser = new User($db); + $fuser->fetch(mt_rand(1, 2)); + $fuser->getRights(); $result=$object->create($fuser); - if ($result >= 0) - { + if ($result >= 0) { $nbp = mt_rand(2, 5); $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $prodid = mt_rand(1, $num_prods); $product=new Product($db); $result=$product->fetch($prodids[$prodid]); $result=$object->addline($product->description, $product->price, mt_rand(1, 5), 0, 0, 0, $prodids[$prodid], 0, '', '', 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type); - if ($result < 0) - { - dol_print_error($db, $propal->error); - } - $xnbp++; + if ($result < 0) { + dol_print_error($db, $propal->error); + } + $xnbp++; } - $result=$object->validate($fuser); - if ($result) - { + $result=$object->validate($fuser); + if ($result) { print " OK with ref ".$object->ref."\n";; } else { dol_print_error($db, $object->error); diff --git a/dev/initdata/generate-order.php b/dev/initdata/generate-order.php index c421e39ffe3..2c939f8e1d2 100755 --- a/dev/initdata/generate-order.php +++ b/dev/initdata/generate-order.php @@ -31,8 +31,8 @@ $path=dirname(__FILE__).'/'; // Test si mode batch $sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; } // Recupere root dolibarr @@ -54,62 +54,61 @@ require_once DOL_DOCUMENT_ROOT."/commande/class/commande.class.php"; define(GEN_NUMBER_COMMANDE, 10); $year = 2016; $dates = array (mktime(12, 0, 0, 1, 3, $year), - mktime(12, 0, 0, 1, 9, $year), - mktime(12, 0, 0, 2, 13, $year), - mktime(12, 0, 0, 2, 23, $year), - mktime(12, 0, 0, 3, 30, $year), - mktime(12, 0, 0, 4, 3, $year), - mktime(12, 0, 0, 4, 3, $year), - mktime(12, 0, 0, 5, 9, $year), - mktime(12, 0, 0, 5, 1, $year), - mktime(12, 0, 0, 5, 13, $year), - mktime(12, 0, 0, 5, 19, $year), - mktime(12, 0, 0, 5, 23, $year), - mktime(12, 0, 0, 6, 3, $year), - mktime(12, 0, 0, 6, 19, $year), - mktime(12, 0, 0, 6, 24, $year), - mktime(12, 0, 0, 7, 3, $year), - mktime(12, 0, 0, 7, 9, $year), - mktime(12, 0, 0, 7, 23, $year), - mktime(12, 0, 0, 7, 30, $year), - mktime(12, 0, 0, 8, 9, $year), - mktime(12, 0, 0, 9, 23, $year), - mktime(12, 0, 0, 10, 3, $year), - mktime(12, 0, 0, 11, 12, $year), - mktime(12, 0, 0, 11, 13, $year), - mktime(12, 0, 0, 1, 3, ($year - 1)), - mktime(12, 0, 0, 1, 9, ($year - 1)), - mktime(12, 0, 0, 2, 13, ($year - 1)), - mktime(12, 0, 0, 2, 23, ($year - 1)), - mktime(12, 0, 0, 3, 30, ($year - 1)), - mktime(12, 0, 0, 4, 3, ($year - 1)), - mktime(12, 0, 0, 4, 3, ($year - 1)), - mktime(12, 0, 0, 5, 9, ($year - 1)), - mktime(12, 0, 0, 5, 1, ($year - 1)), - mktime(12, 0, 0, 5, 13, ($year - 1)), - mktime(12, 0, 0, 5, 19, ($year - 1)), - mktime(12, 0, 0, 5, 23, ($year - 1)), - mktime(12, 0, 0, 6, 3, ($year - 1)), - mktime(12, 0, 0, 6, 19, ($year - 1)), - mktime(12, 0, 0, 6, 24, ($year - 1)), - mktime(12, 0, 0, 7, 3, ($year - 1)), - mktime(12, 0, 0, 7, 9, ($year - 1)), - mktime(12, 0, 0, 7, 23, ($year - 1)), - mktime(12, 0, 0, 7, 30, ($year - 1)), - mktime(12, 0, 0, 8, 9, ($year - 1)), - mktime(12, 0, 0, 9, 23, ($year - 1)), - mktime(12, 0, 0, 10, 3, ($year - 1)), - mktime(12, 0, 0, 11, 12, $year), - mktime(12, 0, 0, 11, 13, $year), - mktime(12, 0, 0, 12, 12, $year), - mktime(12, 0, 0, 12, 13, $year), + mktime(12, 0, 0, 1, 9, $year), + mktime(12, 0, 0, 2, 13, $year), + mktime(12, 0, 0, 2, 23, $year), + mktime(12, 0, 0, 3, 30, $year), + mktime(12, 0, 0, 4, 3, $year), + mktime(12, 0, 0, 4, 3, $year), + mktime(12, 0, 0, 5, 9, $year), + mktime(12, 0, 0, 5, 1, $year), + mktime(12, 0, 0, 5, 13, $year), + mktime(12, 0, 0, 5, 19, $year), + mktime(12, 0, 0, 5, 23, $year), + mktime(12, 0, 0, 6, 3, $year), + mktime(12, 0, 0, 6, 19, $year), + mktime(12, 0, 0, 6, 24, $year), + mktime(12, 0, 0, 7, 3, $year), + mktime(12, 0, 0, 7, 9, $year), + mktime(12, 0, 0, 7, 23, $year), + mktime(12, 0, 0, 7, 30, $year), + mktime(12, 0, 0, 8, 9, $year), + mktime(12, 0, 0, 9, 23, $year), + mktime(12, 0, 0, 10, 3, $year), + mktime(12, 0, 0, 11, 12, $year), + mktime(12, 0, 0, 11, 13, $year), + mktime(12, 0, 0, 1, 3, ($year - 1)), + mktime(12, 0, 0, 1, 9, ($year - 1)), + mktime(12, 0, 0, 2, 13, ($year - 1)), + mktime(12, 0, 0, 2, 23, ($year - 1)), + mktime(12, 0, 0, 3, 30, ($year - 1)), + mktime(12, 0, 0, 4, 3, ($year - 1)), + mktime(12, 0, 0, 4, 3, ($year - 1)), + mktime(12, 0, 0, 5, 9, ($year - 1)), + mktime(12, 0, 0, 5, 1, ($year - 1)), + mktime(12, 0, 0, 5, 13, ($year - 1)), + mktime(12, 0, 0, 5, 19, ($year - 1)), + mktime(12, 0, 0, 5, 23, ($year - 1)), + mktime(12, 0, 0, 6, 3, ($year - 1)), + mktime(12, 0, 0, 6, 19, ($year - 1)), + mktime(12, 0, 0, 6, 24, ($year - 1)), + mktime(12, 0, 0, 7, 3, ($year - 1)), + mktime(12, 0, 0, 7, 9, ($year - 1)), + mktime(12, 0, 0, 7, 23, ($year - 1)), + mktime(12, 0, 0, 7, 30, ($year - 1)), + mktime(12, 0, 0, 8, 9, ($year - 1)), + mktime(12, 0, 0, 9, 23, ($year - 1)), + mktime(12, 0, 0, 10, 3, ($year - 1)), + mktime(12, 0, 0, 11, 12, $year), + mktime(12, 0, 0, 11, 13, $year), + mktime(12, 0, 0, 12, 12, $year), + mktime(12, 0, 0, 12, 13, $year), ); $ret=$user->fetch('', 'admin'); -if ($ret <= 0) -{ - print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; - exit; +if ($ret <= 0) { + print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; + exit; } $user->getrights(); @@ -117,101 +116,100 @@ $societesid = array(); $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe where client in (1, 3)"; $resql=$db->query($sql); if ($resql) { - $num_thirdparties = $db->num_rows($resql); - $i = 0; - while ($i < $num_thirdparties) { - $i++; - $row = $db->fetch_row($resql); - $societesid[$i] = $row[0]; - } -} else { print "err"; } + $num_thirdparties = $db->num_rows($resql); + $i = 0; + while ($i < $num_thirdparties) { + $i++; + $row = $db->fetch_row($resql); + $societesid[$i] = $row[0]; + } +} else { + print "err"; +} $commandesid = array(); $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande"; $resql=$db->query($sql); if ($resql) { - $num = $db->num_rows($resql); - $i = 0; - while ($i < $num) { - $i++; - $row = $db->fetch_row($resql); - $commandesid[$i] = $row[0]; - } -} else { print "err"; } + $num = $db->num_rows($resql); + $i = 0; + while ($i < $num) { + $i++; + $row = $db->fetch_row($resql); + $commandesid[$i] = $row[0]; + } +} else { + print "err"; +} $prodids = array(); $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product WHERE tosell=1"; $resql = $db->query($sql); if ($resql) { - $num_prods = $db->num_rows($resql); - $i = 0; - while ($i < $num_prods) { - $i++; + $num_prods = $db->num_rows($resql); + $i = 0; + while ($i < $num_prods) { + $i++; - $row = $db->fetch_row($resql); - $prodids[$i] = $row[0]; - } + $row = $db->fetch_row($resql); + $prodids[$i] = $row[0]; + } } print "Build ".GEN_NUMBER_COMMANDE." orders\n"; -for ($s = 0 ; $s < GEN_NUMBER_COMMANDE ; $s++) -{ - print "Process order ".$s."\n"; +for ($s = 0; $s < GEN_NUMBER_COMMANDE; $s++) { + print "Process order ".$s."\n"; - $object = new Commande($db); + $object = new Commande($db); - $object->socid = $societesid[mt_rand(1, $num_thirdparties)]; - $object->date_commande = $dates[mt_rand(1, count($dates)-1)]; - $object->note = 'My small comment about this order. Hum. Nothing.'; - $object->source = 1; - $object->fk_project = 0; - $object->remise_percent = 0; - $object->shipping_method_id = mt_rand(1, 2); - $object->cond_reglement_id = mt_rand(0, 2); - $object->more_reglement_id = mt_rand(0, 7); - $object->availability_id = mt_rand(0, 1); + $object->socid = $societesid[mt_rand(1, $num_thirdparties)]; + $object->date_commande = $dates[mt_rand(1, count($dates)-1)]; + $object->note = 'My small comment about this order. Hum. Nothing.'; + $object->source = 1; + $object->fk_project = 0; + $object->remise_percent = 0; + $object->shipping_method_id = mt_rand(1, 2); + $object->cond_reglement_id = mt_rand(0, 2); + $object->more_reglement_id = mt_rand(0, 7); + $object->availability_id = mt_rand(0, 1); - $listofuserid=array(12,13,16); + $listofuserid=array(12,13,16); - $fuser = new User($db); - $fuser->fetch($listofuserid[mt_rand(0, 2)]); - $fuser->getRights(); + $fuser = new User($db); + $fuser->fetch($listofuserid[mt_rand(0, 2)]); + $fuser->getRights(); - $db->begin(); + $db->begin(); - $result=$object->create($fuser); - if ($result >= 0) - { - $nbp = mt_rand(2, 5); - $xnbp = 0; - while ($xnbp < $nbp) - { - $prodid = mt_rand(1, $num_prods); - $product=new Product($db); - $result=$product->fetch($prodids[$prodid]); - $result=$object->addline($product->description, $product->price, mt_rand(1, 5), 0, 0, 0, $prodids[$prodid], 0, 0, 0, $product->price_base_type, $product->price_ttc, '', '', $product->type); - if ($result <= 0) - { - dol_print_error($db, $object->error); - } - $xnbp++; - } + $result=$object->create($fuser); + if ($result >= 0) { + $nbp = mt_rand(2, 5); + $xnbp = 0; + while ($xnbp < $nbp) { + $prodid = mt_rand(1, $num_prods); + $product=new Product($db); + $result=$product->fetch($prodids[$prodid]); + $result=$object->addline($product->description, $product->price, mt_rand(1, 5), 0, 0, 0, $prodids[$prodid], 0, 0, 0, $product->price_base_type, $product->price_ttc, '', '', $product->type); + if ($result <= 0) { + dol_print_error($db, $object->error); + } + $xnbp++; + } - $result=$object->valid($fuser); - if ($result > 0) - { - $db->commit(); - print " OK with ref ".$object->ref."\n"; - } else { - print " KO\n"; - $db->rollback(); - dol_print_error($db, $object->error); - } - } else { - print " KO\n"; - $db->rollback(); - dol_print_error($db, $object->error); - } + $result=$object->valid($fuser); + if ($result > 0) { + $db->commit(); + print " OK with ref ".$object->ref."\n"; + } else { + print " KO\n"; + $db->rollback(); + dol_print_error($db, $object->error); + } + } else { + print " KO\n"; + $db->rollback(); + dol_print_error($db, $object->error); + } } diff --git a/dev/initdata/generate-product.php b/dev/initdata/generate-product.php index a82c0262360..97b02fa3ac9 100755 --- a/dev/initdata/generate-product.php +++ b/dev/initdata/generate-product.php @@ -31,8 +31,8 @@ $path=dirname(__FILE__).'/'; // Test si mode batch $sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; } // Recupere root dolibarr @@ -54,8 +54,7 @@ define(GEN_NUMBER_PRODUIT, 100000); $ret=$user->fetch('', 'admin'); -if (! $ret > 0) -{ +if (! $ret > 0) { print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; exit; } @@ -65,38 +64,50 @@ $user->getrights(); $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product"; $productsid = array(); $resql=$db->query($sql); if ($resql) { - $num = $db->num_rows($resql); $i = 0; - while ($i < $num) { $row = $db->fetch_row($resql); $productsid[$i] = $row[0]; $i++; } + $num = $db->num_rows($resql); $i = 0; + while ($i < $num) { + $row = $db->fetch_row($resql); $productsid[$i] = $row[0]; $i++; + } } $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe"; $societesid = array(); $resql=$db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) { $row = $db->fetch_row($resql); $societesid[$i] = $row[0]; $i++; } -} else { print "err"; } + while ($i < $num) { + $row = $db->fetch_row($resql); $societesid[$i] = $row[0]; $i++; + } +} else { + print "err"; +} $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande"; $commandesid = array(); $resql=$db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) { $row = $db->fetch_row($resql); $commandesid[$i] = $row[0]; $i++; } -} else { print "err"; } + while ($i < $num) { + $row = $db->fetch_row($resql); $commandesid[$i] = $row[0]; $i++; + } +} else { + print "err"; +} print "Generates ".GEN_NUMBER_PRODUIT." products\n"; -for ($s = 0 ; $s < GEN_NUMBER_PRODUIT ; $s++) -{ - print "Product ".$s; - $produit = new Product($db); - $produit->type = mt_rand(0, 1); - $produit->status = 1; - $produit->ref = ($produit->type?'S':'P').time().$s; - $produit->label = 'Label '.time().$s; - $produit->description = 'Description '.time().$s; - $produit->price = mt_rand(1, 1000); - $produit->tva_tx = "19.6"; - $ret=$produit->create($user); - if ($ret < 0) print "Error $ret - ".$produit->error."\n"; - else print " OK with ref ".$produit->ref."\n"; +for ($s = 0; $s < GEN_NUMBER_PRODUIT; $s++) { + print "Product ".$s; + $produit = new Product($db); + $produit->type = mt_rand(0, 1); + $produit->status = 1; + $produit->ref = ($produit->type?'S':'P').time().$s; + $produit->label = 'Label '.time().$s; + $produit->description = 'Description '.time().$s; + $produit->price = mt_rand(1, 1000); + $produit->tva_tx = "19.6"; + $ret=$produit->create($user); + if ($ret < 0) { + print "Error $ret - ".$produit->error."\n"; + } else { + print " OK with ref ".$produit->ref."\n"; + } } diff --git a/dev/initdata/generate-proposal.php b/dev/initdata/generate-proposal.php index 42c0c4098f2..0b1c24dc139 100755 --- a/dev/initdata/generate-proposal.php +++ b/dev/initdata/generate-proposal.php @@ -50,60 +50,59 @@ require_once DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"; define(GEN_NUMBER_PROPAL, 10); $year = 2016; $dates = array (mktime(12, 0, 0, 1, 3, $year), - mktime(12, 0, 0, 1, 9, $year), - mktime(12, 0, 0, 2, 13, $year), - mktime(12, 0, 0, 2, 23, $year), - mktime(12, 0, 0, 3, 30, $year), - mktime(12, 0, 0, 4, 3, $year), - mktime(12, 0, 0, 4, 3, $year), - mktime(12, 0, 0, 5, 9, $year), - mktime(12, 0, 0, 5, 1, $year), - mktime(12, 0, 0, 5, 13, $year), - mktime(12, 0, 0, 5, 19, $year), - mktime(12, 0, 0, 5, 23, $year), - mktime(12, 0, 0, 6, 3, $year), - mktime(12, 0, 0, 6, 19, $year), - mktime(12, 0, 0, 6, 24, $year), - mktime(12, 0, 0, 7, 3, $year), - mktime(12, 0, 0, 7, 9, $year), - mktime(12, 0, 0, 7, 23, $year), - mktime(12, 0, 0, 7, 30, $year), - mktime(12, 0, 0, 8, 9, $year), - mktime(12, 0, 0, 9, 23, $year), - mktime(12, 0, 0, 10, 3, $year), - mktime(12, 0, 0, 11, 12, $year), - mktime(12, 0, 0, 11, 13, $year), - mktime(12, 0, 0, 1, 3, ($year - 1)), - mktime(12, 0, 0, 1, 9, ($year - 1)), - mktime(12, 0, 0, 2, 13, ($year - 1)), - mktime(12, 0, 0, 2, 23, ($year - 1)), - mktime(12, 0, 0, 3, 30, ($year - 1)), - mktime(12, 0, 0, 4, 3, ($year - 1)), - mktime(12, 0, 0, 4, 3, ($year - 1)), - mktime(12, 0, 0, 5, 9, ($year - 1)), - mktime(12, 0, 0, 5, 1, ($year - 1)), - mktime(12, 0, 0, 5, 13, ($year - 1)), - mktime(12, 0, 0, 5, 19, ($year - 1)), - mktime(12, 0, 0, 5, 23, ($year - 1)), - mktime(12, 0, 0, 6, 3, ($year - 1)), - mktime(12, 0, 0, 6, 19, ($year - 1)), - mktime(12, 0, 0, 6, 24, ($year - 1)), - mktime(12, 0, 0, 7, 3, ($year - 1)), - mktime(12, 0, 0, 7, 9, ($year - 1)), - mktime(12, 0, 0, 7, 23, ($year - 1)), - mktime(12, 0, 0, 7, 30, ($year - 1)), - mktime(12, 0, 0, 8, 9, ($year - 1)), - mktime(12, 0, 0, 9, 23, ($year - 1)), - mktime(12, 0, 0, 10, 3, ($year - 1)), - mktime(12, 0, 0, 11, 12, $year), - mktime(12, 0, 0, 11, 13, $year), - mktime(12, 0, 0, 12, 12, $year), - mktime(12, 0, 0, 12, 13, $year), + mktime(12, 0, 0, 1, 9, $year), + mktime(12, 0, 0, 2, 13, $year), + mktime(12, 0, 0, 2, 23, $year), + mktime(12, 0, 0, 3, 30, $year), + mktime(12, 0, 0, 4, 3, $year), + mktime(12, 0, 0, 4, 3, $year), + mktime(12, 0, 0, 5, 9, $year), + mktime(12, 0, 0, 5, 1, $year), + mktime(12, 0, 0, 5, 13, $year), + mktime(12, 0, 0, 5, 19, $year), + mktime(12, 0, 0, 5, 23, $year), + mktime(12, 0, 0, 6, 3, $year), + mktime(12, 0, 0, 6, 19, $year), + mktime(12, 0, 0, 6, 24, $year), + mktime(12, 0, 0, 7, 3, $year), + mktime(12, 0, 0, 7, 9, $year), + mktime(12, 0, 0, 7, 23, $year), + mktime(12, 0, 0, 7, 30, $year), + mktime(12, 0, 0, 8, 9, $year), + mktime(12, 0, 0, 9, 23, $year), + mktime(12, 0, 0, 10, 3, $year), + mktime(12, 0, 0, 11, 12, $year), + mktime(12, 0, 0, 11, 13, $year), + mktime(12, 0, 0, 1, 3, ($year - 1)), + mktime(12, 0, 0, 1, 9, ($year - 1)), + mktime(12, 0, 0, 2, 13, ($year - 1)), + mktime(12, 0, 0, 2, 23, ($year - 1)), + mktime(12, 0, 0, 3, 30, ($year - 1)), + mktime(12, 0, 0, 4, 3, ($year - 1)), + mktime(12, 0, 0, 4, 3, ($year - 1)), + mktime(12, 0, 0, 5, 9, ($year - 1)), + mktime(12, 0, 0, 5, 1, ($year - 1)), + mktime(12, 0, 0, 5, 13, ($year - 1)), + mktime(12, 0, 0, 5, 19, ($year - 1)), + mktime(12, 0, 0, 5, 23, ($year - 1)), + mktime(12, 0, 0, 6, 3, ($year - 1)), + mktime(12, 0, 0, 6, 19, ($year - 1)), + mktime(12, 0, 0, 6, 24, ($year - 1)), + mktime(12, 0, 0, 7, 3, ($year - 1)), + mktime(12, 0, 0, 7, 9, ($year - 1)), + mktime(12, 0, 0, 7, 23, ($year - 1)), + mktime(12, 0, 0, 7, 30, ($year - 1)), + mktime(12, 0, 0, 8, 9, ($year - 1)), + mktime(12, 0, 0, 9, 23, ($year - 1)), + mktime(12, 0, 0, 10, 3, ($year - 1)), + mktime(12, 0, 0, 11, 12, $year), + mktime(12, 0, 0, 11, 13, $year), + mktime(12, 0, 0, 12, 12, $year), + mktime(12, 0, 0, 12, 13, $year), ); $ret=$user->fetch('', 'admin'); -if (! $ret > 0) -{ +if (! $ret > 0) { print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; exit; } @@ -113,12 +112,10 @@ $user->getrights(); $socids = array(); $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe WHERE client in (1,3)"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num_thirdparties = $db->num_rows($resql); $i = 0; - while ($i < $num_thirdparties) - { + while ($i < $num_thirdparties) { $i++; $row = $db->fetch_row($resql); $socids[$i] = $row[0]; @@ -128,12 +125,10 @@ if ($resql) $contids = array(); $sql = "SELECT rowid, fk_soc FROM ".MAIN_DB_PREFIX."socpeople"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num_conts = $db->num_rows($resql); $i = 0; - while ($i < $num_conts) - { + while ($i < $num_conts) { $i++; $row = $db->fetch_row($resql); $contids[$row[1]][0] = $row[0]; // A ameliorer @@ -143,12 +138,10 @@ if ($resql) $prodids = array(); $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product WHERE tosell=1"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num_prods = $db->num_rows($resql); $i = 0; - while ($i < $num_prods) - { + while ($i < $num_prods) { $i++; $row = $db->fetch_row($resql); $prodids[$i] = $row[0]; @@ -159,15 +152,13 @@ $user->rights->propal->creer=1; $user->rights->propal->propal_advance->validate=1; -if (! empty($conf->global->PROPALE_ADDON) && is_readable(DOL_DOCUMENT_ROOT ."/core/modules/propale/".$conf->global->PROPALE_ADDON.".php")) -{ +if (! empty($conf->global->PROPALE_ADDON) && is_readable(DOL_DOCUMENT_ROOT ."/core/modules/propale/".$conf->global->PROPALE_ADDON.".php")) { require_once DOL_DOCUMENT_ROOT ."/core/modules/propale/".$conf->global->PROPALE_ADDON.".php"; } $i=0; $result=0; -while ($i < GEN_NUMBER_PROPAL && $result >= 0) -{ +while ($i < GEN_NUMBER_PROPAL && $result >= 0) { $i++; $socid = mt_rand(1, $num_thirdparties); print "Proposal ".$i." for socid ".$socid; @@ -177,9 +168,9 @@ while ($i < GEN_NUMBER_PROPAL && $result >= 0) $object = new Propal($db); - $fuser = new User($db); - $fuser->fetch(mt_rand(1, 2)); - $fuser->getRights(); + $fuser = new User($db); + $fuser->fetch(mt_rand(1, 2)); + $fuser->getRights(); $object->contactid = $contids[$socids[$socid]][0]; $object->socid = $socids[$socid]; @@ -188,32 +179,28 @@ while ($i < GEN_NUMBER_PROPAL && $result >= 0) $object->mode_reglement_id = 3; $result=$object->create($fuser); - if ($result >= 0) - { + if ($result >= 0) { $nbp = mt_rand(2, 5); $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $prodid = mt_rand(1, $num_prods); $product=new Product($db); $result=$product->fetch($prodids[$prodid]); $result=$object->addline($product->description, $product->price, mt_rand(1, 5), 0, 0, 0, $prodids[$prodid], 0); - if ($result < 0) - { + if ($result < 0) { dol_print_error($db, $object->error); } $xnbp++; } $result=$object->valid($fuser); - if ($result > 0) - { - $db->commit(); - print " OK with ref ".$object->ref."\n"; + if ($result > 0) { + $db->commit(); + print " OK with ref ".$object->ref."\n"; } else { - print " KO\n"; - $db->rollback(); - dol_print_error($db, $object->error); + print " KO\n"; + $db->rollback(); + dol_print_error($db, $object->error); } } else { dol_print_error($db, $object->error); diff --git a/dev/initdata/generate-thirdparty.php b/dev/initdata/generate-thirdparty.php index a13e2351e9c..f60f34ac168 100755 --- a/dev/initdata/generate-thirdparty.php +++ b/dev/initdata/generate-thirdparty.php @@ -31,8 +31,8 @@ $path=dirname(__FILE__).'/'; // Test si mode batch $sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; } // Recupere root dolibarr @@ -57,8 +57,7 @@ define(GEN_NUMBER_SOCIETE, 10); $ret=$user->fetch('', 'admin'); -if (! $ret > 0) -{ +if (! $ret > 0) { print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; exit; } @@ -68,8 +67,8 @@ $user->getrights(); $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product"; $productsid = array(); $resql=$db->query($sql); if ($resql) { - $num = $db->num_rows($resql); $i = 0; - while ($i < $num) { + $num = $db->num_rows($resql); $i = 0; + while ($i < $num) { $row = $db->fetch_row($resql); $productsid[$i] = $row[0]; $i++; @@ -80,63 +79,65 @@ $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe"; $societesid = array(); $resql=$db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) { + while ($i < $num) { $row = $db->fetch_row($resql); $societesid[$i] = $row[0]; $i++; } -} else { print "err"; } +} else { + print "err"; +} $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande"; $commandesid = array(); $resql=$db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) { + while ($i < $num) { $row = $db->fetch_row($resql); $commandesid[$i] = $row[0]; $i++; } -} else { print "err"; } +} else { + print "err"; +} print "Generates ".GEN_NUMBER_SOCIETE." companies\n"; -for ($s = 0 ; $s < GEN_NUMBER_SOCIETE ; $s++) -{ - print "Company $s\n"; - $soc = new Societe($db); - $soc->name = "Company num ".time()."$s"; - $soc->town = $listoftown[mt_rand(0, count($listoftown)-1)]; - $soc->client = mt_rand(1, 2); // Une societe sur 2 est prospect, l'autre client - $soc->fournisseur = mt_rand(0, 1); // Une societe sur 2 est fournisseur - $soc->code_client='CU'.time()."$s"; - $soc->code_fournisseur='SU'.time()."$s"; - $soc->tva_assuj=1; - $soc->country_id=1; - $soc->country_code='FR'; +for ($s = 0; $s < GEN_NUMBER_SOCIETE; $s++) { + print "Company $s\n"; + $soc = new Societe($db); + $soc->name = "Company num ".time()."$s"; + $soc->town = $listoftown[mt_rand(0, count($listoftown)-1)]; + $soc->client = mt_rand(1, 2); // Une societe sur 2 est prospect, l'autre client + $soc->fournisseur = mt_rand(0, 1); // Une societe sur 2 est fournisseur + $soc->code_client='CU'.time()."$s"; + $soc->code_fournisseur='SU'.time()."$s"; + $soc->tva_assuj=1; + $soc->country_id=1; + $soc->country_code='FR'; // Un client sur 3 a une remise de 5% - $user_remise=mt_rand(1, 3); if ($user_remise==3) $soc->remise_percent=5; + $user_remise=mt_rand(1, 3); if ($user_remise==3) { + $soc->remise_percent=5; + } print "> client=".$soc->client.", fournisseur=".$soc->fournisseur.", remise=".$soc->remise_percent."\n"; - $soc->note_private = 'Company created by the script generate-societe.php'; - $socid = $soc->create(); + $soc->note_private = 'Company created by the script generate-societe.php'; + $socid = $soc->create(); - if ($socid >= 0) - { - $rand = mt_rand(1, 4); - print "> Generates $rand contact(s)\n"; - for ($c = 0 ; $c < $rand ; $c++) - { - $contact = new Contact($db); - $contact->socid = $soc->id; - $contact->lastname = "Lastname".$c; - $contact->firstname = $listoflastname[mt_rand(0, count($listoflastname)-1)]; - if ( $contact->create($user) ) - { - } - } + if ($socid >= 0) { + $rand = mt_rand(1, 4); + print "> Generates $rand contact(s)\n"; + for ($c = 0; $c < $rand; $c++) { + $contact = new Contact($db); + $contact->socid = $soc->id; + $contact->lastname = "Lastname".$c; + $contact->firstname = $listoflastname[mt_rand(0, count($listoflastname)-1)]; + if ($contact->create($user)) { + } + } - print "Company ".$s." created nom=".$soc->name."\n"; - } else { - print "Error: ".$soc->error."\n"; - } + print "Company ".$s." created nom=".$soc->name."\n"; + } else { + print "Error: ".$soc->error."\n"; + } } diff --git a/dev/initdata/import-products.php b/dev/initdata/import-products.php index fb07143f972..d4e06302d56 100755 --- a/dev/initdata/import-products.php +++ b/dev/initdata/import-products.php @@ -30,8 +30,8 @@ $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); $path=dirname(__FILE__).'/'; if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; } // Recupere root dolibarr @@ -67,44 +67,40 @@ $startlinenb = empty($argv[4])?1:$argv[4]; $endlinenb = empty($argv[5])?0:$argv[5]; if (empty($mode) || ! in_array($mode, array('test','confirm','confirmforced')) || empty($filepath)) { - print "Usage: $script_file (test|confirm|confirmforced) filepath.csv [defaultlang] [startlinenb] [endlinenb]\n"; - print "Usage: $script_file test myfilepath.csv fr_FR 2 1002\n"; - print "\n"; - exit(-1); + print "Usage: $script_file (test|confirm|confirmforced) filepath.csv [defaultlang] [startlinenb] [endlinenb]\n"; + print "Usage: $script_file test myfilepath.csv fr_FR 2 1002\n"; + print "\n"; + exit(-1); } if (! file_exists($filepath)) { - print "Error: File ".$filepath." not found.\n"; - print "\n"; - exit(-1); + print "Error: File ".$filepath." not found.\n"; + print "\n"; + exit(-1); } $ret=$user->fetch('', 'admin'); -if (! $ret > 0) -{ +if (! $ret > 0) { print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; exit; } $user->getrights(); // Ask confirmation -if (! $confirmed) -{ - print "Hit Enter to continue or CTRL+C to stop...\n"; - $input = trim(fgets(STDIN)); +if (! $confirmed) { + print "Hit Enter to continue or CTRL+C to stop...\n"; + $input = trim(fgets(STDIN)); } // Open input and output files $fhandle = fopen($filepath, 'r'); -if (! $fhandle) -{ - print 'Error: Failed to open file '.$filepath."\n"; - exit(1); +if (! $fhandle) { + print 'Error: Failed to open file '.$filepath."\n"; + exit(1); } $fhandleerr = fopen($filepatherr, 'w'); -if (! $fhandleerr) -{ - print 'Error: Failed to open file '.$filepatherr."\n"; - exit(1); +if (! $fhandleerr) { + print 'Error: Failed to open file '.$filepatherr."\n"; + exit(1); } $langs->setDefaultLang($defaultlang); @@ -114,99 +110,96 @@ $db->begin(); $i=0; $nboflines++; -while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) -{ - $i++; - $errorrecord=0; +while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) { + $i++; + $errorrecord=0; - if ($startlinenb && $i < $startlinenb) continue; - if ($endlinenb && $i > $endlinenb) continue; + if ($startlinenb && $i < $startlinenb) { + continue; + } + if ($endlinenb && $i > $endlinenb) { + continue; + } - $nboflines++; + $nboflines++; - $produit = new Product($db); - $produit->type = 0; - $produit->status = 1; - $produit->ref = trim($fields[0]); + $produit = new Product($db); + $produit->type = 0; + $produit->status = 1; + $produit->ref = trim($fields[0]); - print "Process line nb ".$i.", ref ".$produit->ref; - $produit->label = trim($fields[2]); - $produit->description = trim($fields[4]."\n".($fields[5] ? $fields[5].' x '.$fields[6].' x '.$fields[7] : '')); - $produit->volume = price2num($fields[8]); - $produit->volume_unit = 0; - $produit->weight = price2num($fields[9]); - $produit->weight_units = 0; // -3 = g + print "Process line nb ".$i.", ref ".$produit->ref; + $produit->label = trim($fields[2]); + $produit->description = trim($fields[4]."\n".($fields[5] ? $fields[5].' x '.$fields[6].' x '.$fields[7] : '')); + $produit->volume = price2num($fields[8]); + $produit->volume_unit = 0; + $produit->weight = price2num($fields[9]); + $produit->weight_units = 0; // -3 = g - $produit->customcode = $fields[10]; - $produit->barcode = $fields[1]; + $produit->customcode = $fields[10]; + $produit->barcode = $fields[1]; - $produit->status = 1; - $produit->status_buy = 1; + $produit->status = 1; + $produit->status_buy = 1; - $produit->finished = 1; + $produit->finished = 1; - $produit->price_min = null; - $produit->price_min_ttc = null; - $produit->price = price2num($fields[11]); - $produit->price_ttc = price2num($fields[12]); - $produit->price_base_type = 'TTC'; - $produit->tva_tx = price2num($fields[13]); - $produit->tva_npr = 0; + $produit->price_min = null; + $produit->price_min_ttc = null; + $produit->price = price2num($fields[11]); + $produit->price_ttc = price2num($fields[12]); + $produit->price_base_type = 'TTC'; + $produit->tva_tx = price2num($fields[13]); + $produit->tva_npr = 0; - $produit->cost_price = price2num($fields[16]); + $produit->cost_price = price2num($fields[16]); - // Extrafields - $produit->array_options['options_ecotaxdeee']=price2num($fields[17]); + // Extrafields + $produit->array_options['options_ecotaxdeee']=price2num($fields[17]); - $ret=$produit->create($user); - if ($ret < 0) - { - print " - Error in create result code = ".$ret." - ".$produit->errorsToString(); - $errorrecord++; - } else { - print " - Creation OK with ref ".$produit->ref." - id = ".$ret; + $ret=$produit->create($user); + if ($ret < 0) { + print " - Error in create result code = ".$ret." - ".$produit->errorsToString(); + $errorrecord++; + } else { + print " - Creation OK with ref ".$produit->ref." - id = ".$ret; } dol_syslog("Add prices"); - // If we use price level, insert price for each level - if (! $errorrecord && 1) - { - $ret1=$produit->updatePrice($produit->price_ttc, $produit->price_base_type, $user, $produit->tva_tx, $produit->price_min, 1, $produit->tva_npr, 0, 0, array()); - $ret2=$produit->updatePrice(price2num($fields[14]), 'HT', $user, $produit->tva_tx, $produit->price_min, 2, $produit->tva_npr, 0, 0, array()); - if ($ret1 < 0 || $ret2 < 0) - { - print " - Error in updatePrice result code = ".$ret1." ".$ret2." - ".$produit->errorsToString(); - $errorrecord++; - } else { - print " - updatePrice OK"; - } + // If we use price level, insert price for each level + if (! $errorrecord && 1) { + $ret1=$produit->updatePrice($produit->price_ttc, $produit->price_base_type, $user, $produit->tva_tx, $produit->price_min, 1, $produit->tva_npr, 0, 0, array()); + $ret2=$produit->updatePrice(price2num($fields[14]), 'HT', $user, $produit->tva_tx, $produit->price_min, 2, $produit->tva_npr, 0, 0, array()); + if ($ret1 < 0 || $ret2 < 0) { + print " - Error in updatePrice result code = ".$ret1." ".$ret2." - ".$produit->errorsToString(); + $errorrecord++; + } else { + print " - updatePrice OK"; + } } dol_syslog("Add multilangs"); // Add alternative languages - if (! $errorrecord && 1) - { - $produit->multilangs['fr_FR']=array('label'=>$produit->label, 'description'=>$produit->description, 'note'=>$produit->note_private); - $produit->multilangs['en_US']=array('label'=>$fields[3], 'description'=>$produit->description, 'note'=>$produit->note_private); + if (! $errorrecord && 1) { + $produit->multilangs['fr_FR']=array('label'=>$produit->label, 'description'=>$produit->description, 'note'=>$produit->note_private); + $produit->multilangs['en_US']=array('label'=>$fields[3], 'description'=>$produit->description, 'note'=>$produit->note_private); - $ret=$produit->setMultiLangs($user); - if ($ret < 0) - { - print " - Error in setMultiLangs result code = ".$ret." - ".$produit->errorsToString(); - $errorrecord++; - } else { - print " - setMultiLangs OK"; - } + $ret=$produit->setMultiLangs($user); + if ($ret < 0) { + print " - Error in setMultiLangs result code = ".$ret." - ".$produit->errorsToString(); + $errorrecord++; + } else { + print " - setMultiLangs OK"; + } } print "\n"; - if ($errorrecord) - { - fwrite($fhandleerr, 'Error on record nb '.$i." - ".$produit->errorsToString()."\n"); - $error++; // $errorrecord will be reset + if ($errorrecord) { + fwrite($fhandleerr, 'Error on record nb '.$i." - ".$produit->errorsToString()."\n"); + $error++; // $errorrecord will be reset } } @@ -217,13 +210,12 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) // commit or rollback print "Nb of lines qualified: ".$nboflines."\n"; print "Nb of errors: ".$error."\n"; -if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) -{ - print "Rollback any changes.\n"; - $db->rollback(); +if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) { + print "Rollback any changes.\n"; + $db->rollback(); } else { - print "Commit all changes.\n"; - $db->commit(); + print "Commit all changes.\n"; + $db->commit(); } $db->close(); diff --git a/dev/initdata/import-thirdparties.php b/dev/initdata/import-thirdparties.php index a0ddaac7674..91f28f11769 100755 --- a/dev/initdata/import-thirdparties.php +++ b/dev/initdata/import-thirdparties.php @@ -30,8 +30,8 @@ $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); $path=dirname(__FILE__).'/'; if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; } // Recupere root dolibarr @@ -67,44 +67,40 @@ $startlinenb = empty($argv[3])?1:$argv[3]; $endlinenb = empty($argv[4])?0:$argv[4]; if (empty($mode) || ! in_array($mode, array('test','confirm','confirmforced')) || empty($filepath)) { - print "Usage: $script_file (test|confirm|confirmforced) filepath.csv [startlinenb] [endlinenb]\n"; - print "Usage: $script_file test myfilepath.csv 2 1002\n"; - print "\n"; - exit(-1); + print "Usage: $script_file (test|confirm|confirmforced) filepath.csv [startlinenb] [endlinenb]\n"; + print "Usage: $script_file test myfilepath.csv 2 1002\n"; + print "\n"; + exit(-1); } if (! file_exists($filepath)) { - print "Error: File ".$filepath." not found.\n"; - print "\n"; - exit(-1); + print "Error: File ".$filepath." not found.\n"; + print "\n"; + exit(-1); } $ret=$user->fetch('', 'admin'); -if (! $ret > 0) -{ +if (! $ret > 0) { print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; exit; } $user->getrights(); // Ask confirmation -if (! $confirmed) -{ - print "Hit Enter to continue or CTRL+C to stop...\n"; - $input = trim(fgets(STDIN)); +if (! $confirmed) { + print "Hit Enter to continue or CTRL+C to stop...\n"; + $input = trim(fgets(STDIN)); } // Open input and output files $fhandle = fopen($filepath, 'r'); -if (! $fhandle) -{ - print 'Error: Failed to open file '.$filepath."\n"; - exit(1); +if (! $fhandle) { + print 'Error: Failed to open file '.$filepath."\n"; + exit(1); } $fhandleerr = fopen($filepatherr, 'w'); -if (! $fhandleerr) -{ - print 'Error: Failed to open file '.$filepatherr."\n"; - exit(1); +if (! $fhandleerr) { + print 'Error: Failed to open file '.$filepatherr."\n"; + exit(1); } //$langs->setDefaultLang($defaultlang); @@ -114,175 +110,173 @@ $db->begin(); $i=0; $nboflines=0; -while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) -{ - $i++; - $errorrecord=0; +while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) { + $i++; + $errorrecord=0; - if ($startlinenb && $i < $startlinenb) continue; - if ($endlinenb && $i > $endlinenb) continue; + if ($startlinenb && $i < $startlinenb) { + continue; + } + if ($endlinenb && $i > $endlinenb) { + continue; + } - $nboflines++; + $nboflines++; - $object = new Societe($db); - $object->state = $fields[6]; - $object->client = $fields[7]; - $object->fournisseur = $fields[8]; + $object = new Societe($db); + $object->state = $fields[6]; + $object->client = $fields[7]; + $object->fournisseur = $fields[8]; - $object->name = $fields[13]?trim($fields[13]):$fields[0]; - $object->name_alias = $fields[0]!=$fields[13]?trim($fields[0]):''; + $object->name = $fields[13]?trim($fields[13]):$fields[0]; + $object->name_alias = $fields[0]!=$fields[13]?trim($fields[0]):''; - $object->address = trim($fields[14]); - $object->zip = trim($fields[15]); - $object->town = trim($fields[16]); - $object->country_id = dol_getIdFromCode($db, trim($fields[21]), 'c_country', 'code', 'rowid'); - $object->phone = trim($fields[22]); - $object->fax = trim($fields[23]); - $object->email = trim($fields[26]); - $object->idprof2 = trim($fields[29]); - $object->tva_intra = trim($fields[34]); - $object->default_lang = trim($fields[43]); + $object->address = trim($fields[14]); + $object->zip = trim($fields[15]); + $object->town = trim($fields[16]); + $object->country_id = dol_getIdFromCode($db, trim($fields[21]), 'c_country', 'code', 'rowid'); + $object->phone = trim($fields[22]); + $object->fax = trim($fields[23]); + $object->email = trim($fields[26]); + $object->idprof2 = trim($fields[29]); + $object->tva_intra = trim($fields[34]); + $object->default_lang = trim($fields[43]); - //$condpayment = dol_string_unaccent(trim($fields[36])); - if ($fields[36]) - { - $condpayment = trim($fields[36]); - if ($condpayment == 'A la commande') $condpayment = 'A réception de commande'; - if ($condpayment == 'A reception facture') $condpayment = 'Réception de facture'; - $object->cond_reglement_id = dol_getIdFromCode($db, $condpayment, 'c_payment_term', 'libelle_facture', 'rowid', 1); - if (empty($object->cond_reglement_id)) - { - print " - Error cant find payment mode for ".$condpayment."\n"; - $errorrecord++; - } - } + //$condpayment = dol_string_unaccent(trim($fields[36])); + if ($fields[36]) { + $condpayment = trim($fields[36]); + if ($condpayment == 'A la commande') { + $condpayment = 'A réception de commande'; + } + if ($condpayment == 'A reception facture') { + $condpayment = 'Réception de facture'; + } + $object->cond_reglement_id = dol_getIdFromCode($db, $condpayment, 'c_payment_term', 'libelle_facture', 'rowid', 1); + if (empty($object->cond_reglement_id)) { + print " - Error cant find payment mode for ".$condpayment."\n"; + $errorrecord++; + } + } - $object->code_client = $fields[9]; - $object->code_fournisseur = $fields[10]; + $object->code_client = $fields[9]; + $object->code_fournisseur = $fields[10]; - $labeltype = trim($fields[1]); - $object->typent_id = dol_getIdFromCode($db, $labeltype, 'c_typent', 'libelle'); + $labeltype = trim($fields[1]); + $object->typent_id = dol_getIdFromCode($db, $labeltype, 'c_typent', 'libelle'); - // Set price level - $object->price_level = 1; - if ($labeltype == 'Revendeur') $object->price_level = 2; + // Set price level + $object->price_level = 1; + if ($labeltype == 'Revendeur') { + $object->price_level = 2; + } - print "Process line nb ".$i.", name ".$object->name; + print "Process line nb ".$i.", name ".$object->name; - // Extrafields - $object->array_options['options_anastate']=price2num($fields[20]); - $object->array_options['options_anaregion']=price2num($fields[17]); + // Extrafields + $object->array_options['options_anastate']=price2num($fields[20]); + $object->array_options['options_anaregion']=price2num($fields[17]); - if (! $errorrecord) - { - $ret=$object->create($user); - if ($ret < 0) - { - print " - Error in create result code = ".$ret." - ".$object->errorsToString(); - $errorrecord++; - } else { - print " - Creation OK with name ".$object->name." - id = ".$ret; - } - } + if (! $errorrecord) { + $ret=$object->create($user); + if ($ret < 0) { + print " - Error in create result code = ".$ret." - ".$object->errorsToString(); + $errorrecord++; + } else { + print " - Creation OK with name ".$object->name." - id = ".$ret; + } + } - if (! $errorrecord) - { - dol_syslog("Set price level"); - $object->set_price_level($object->price_level, $user); - } + if (! $errorrecord) { + dol_syslog("Set price level"); + $object->set_price_level($object->price_level, $user); + } // Assign sales representative - if (! $errorrecord && $fields[3]) - { - $salesrep=new User($db); + if (! $errorrecord && $fields[3]) { + $salesrep=new User($db); - $tmp=explode(' ', $fields[3], 2); - $salesrep->firstname = trim($tmp[0]); - $salesrep->lastname = trim($tmp[1]); - if ($salesrep->lastname) $salesrep->login = strtolower(substr($salesrep->firstname, 0, 1)) . strtolower(substr($salesrep->lastname, 0)); - else $salesrep->login=strtolower($salesrep->firstname); - $salesrep->login=preg_replace('/ /', '', $salesrep->login); - $salesrep->fetch(0, $salesrep->login); + $tmp=explode(' ', $fields[3], 2); + $salesrep->firstname = trim($tmp[0]); + $salesrep->lastname = trim($tmp[1]); + if ($salesrep->lastname) { + $salesrep->login = strtolower(substr($salesrep->firstname, 0, 1)) . strtolower(substr($salesrep->lastname, 0)); + } else { + $salesrep->login=strtolower($salesrep->firstname); + } + $salesrep->login=preg_replace('/ /', '', $salesrep->login); + $salesrep->fetch(0, $salesrep->login); - $result = $object->add_commercial($user, $salesrep->id); - if ($result < 0) - { - print " - Error in create link with sale representative result code = ".$result." - ".$object->errorsToString(); - $errorrecord++; - } else { - print " - create link sale representative OK"; - } + $result = $object->add_commercial($user, $salesrep->id); + if ($result < 0) { + print " - Error in create link with sale representative result code = ".$result." - ".$object->errorsToString(); + $errorrecord++; + } else { + print " - create link sale representative OK"; + } } dol_syslog("Add invoice contacts"); // Insert an invoice contact if there is an invoice email != standard email - if (! $errorrecord && $fields[27] && $fields[26] != $fields[27]) - { - $ret1=$ret2=0; + if (! $errorrecord && $fields[27] && $fields[26] != $fields[27]) { + $ret1=$ret2=0; - $contact = new Contact($db); - $contact->lastname = $object->name; - $contact->address=$object->address; - $contact->zip=$object->zip; - $contact->town=$object->town; - $contact->country_id=$object->country_id; - $contact->email=$fields[27]; - $contact->socid=$object->id; + $contact = new Contact($db); + $contact->lastname = $object->name; + $contact->address=$object->address; + $contact->zip=$object->zip; + $contact->town=$object->town; + $contact->country_id=$object->country_id; + $contact->email=$fields[27]; + $contact->socid=$object->id; - $ret1=$contact->create($user); - if ($ret1 > 0) - { - //$ret2=$contact->add_contact($object->id, 'BILLING'); - } - if ($ret1 < 0 || $ret2 < 0) - { - print " - Error in create contact result code = ".$ret1." ".$ret2." - ".$object->errorsToString(); - $errorrecord++; - } else { - print " - create contact OK"; - } + $ret1=$contact->create($user); + if ($ret1 > 0) { + //$ret2=$contact->add_contact($object->id, 'BILLING'); + } + if ($ret1 < 0 || $ret2 < 0) { + print " - Error in create contact result code = ".$ret1." ".$ret2." - ".$object->errorsToString(); + $errorrecord++; + } else { + print " - create contact OK"; + } } dol_syslog("Add delivery contacts"); // Insert a delivery contact - if (! $errorrecord && $fields[47]) - { - $ret1=$ret2=0; + if (! $errorrecord && $fields[47]) { + $ret1=$ret2=0; - $contact2 = new Contact($db); - $contact2->lastname = 'Service livraison - '.$fields[47]; - $contact2->address = $fields[48]; - $contact2->zip = $fields[50]; - $contact2->town = $fields[51]; - $contact2->country_id=dol_getIdFromCode($db, trim($fields[52]), 'c_country', 'code', 'rowid'); - $contact2->note_public=$fields[54]; - $contact2->socid=$object->id; + $contact2 = new Contact($db); + $contact2->lastname = 'Service livraison - '.$fields[47]; + $contact2->address = $fields[48]; + $contact2->zip = $fields[50]; + $contact2->town = $fields[51]; + $contact2->country_id=dol_getIdFromCode($db, trim($fields[52]), 'c_country', 'code', 'rowid'); + $contact2->note_public=$fields[54]; + $contact2->socid=$object->id; - // Extrafields - $contact2->array_options['options_anazoneliv']=price2num($fields[53]); + // Extrafields + $contact2->array_options['options_anazoneliv']=price2num($fields[53]); - $ret1=$contact2->create($user); - if ($ret1 > 0) - { - //$ret2=$contact2->add_contact($object->id, 'SHIPPING'); - } - if ($ret1 < 0 || $ret2 < 0) - { - print " - Error in create contact result code = ".$ret1." ".$ret2." - ".$object->errorsToString(); - $errorrecord++; - } else { - print " - create contact OK"; - } + $ret1=$contact2->create($user); + if ($ret1 > 0) { + //$ret2=$contact2->add_contact($object->id, 'SHIPPING'); + } + if ($ret1 < 0 || $ret2 < 0) { + print " - Error in create contact result code = ".$ret1." ".$ret2." - ".$object->errorsToString(); + $errorrecord++; + } else { + print " - create contact OK"; + } } print "\n"; - if ($errorrecord) - { - fwrite($fhandleerr, 'Error on record nb '.$i." - ".$object->errorsToString()."\n"); - $error++; // $errorrecord will be reset + if ($errorrecord) { + fwrite($fhandleerr, 'Error on record nb '.$i." - ".$object->errorsToString()."\n"); + $error++; // $errorrecord will be reset } } @@ -293,13 +287,12 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) // commit or rollback print "Nb of lines qualified: ".$nboflines."\n"; print "Nb of errors: ".$error."\n"; -if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) -{ - print "Rollback any changes.\n"; - $db->rollback(); +if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) { + print "Rollback any changes.\n"; + $db->rollback(); } else { - print "Commit all changes.\n"; - $db->commit(); + print "Commit all changes.\n"; + $db->commit(); } $db->close(); diff --git a/dev/initdata/import-users.php b/dev/initdata/import-users.php index 8e4878577a1..3c28493c106 100755 --- a/dev/initdata/import-users.php +++ b/dev/initdata/import-users.php @@ -30,8 +30,8 @@ $sapi_type = php_sapi_name(); $script_file = basename(__FILE__); $path=dirname(__FILE__).'/'; if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; } // Recupere root dolibarr @@ -67,44 +67,40 @@ $startlinenb = empty($argv[3])?1:$argv[3]; $endlinenb = empty($argv[4])?0:$argv[4]; if (empty($mode) || ! in_array($mode, array('test','confirm','confirmforced')) || empty($filepath)) { - print "Usage: $script_file (test|confirm|confirmforced) filepath.csv [startlinenb] [endlinenb]\n"; - print "Usage: $script_file test myfilepath.csv 2 1002\n"; - print "\n"; - exit(-1); + print "Usage: $script_file (test|confirm|confirmforced) filepath.csv [startlinenb] [endlinenb]\n"; + print "Usage: $script_file test myfilepath.csv 2 1002\n"; + print "\n"; + exit(-1); } if (! file_exists($filepath)) { - print "Error: File ".$filepath." not found.\n"; - print "\n"; - exit(-1); + print "Error: File ".$filepath." not found.\n"; + print "\n"; + exit(-1); } $ret=$user->fetch('', 'admin'); -if (! $ret > 0) -{ +if (! $ret > 0) { print 'A user with login "admin" and all permissions must be created to use this script.'."\n"; exit; } $user->getrights(); // Ask confirmation -if (! $confirmed) -{ - print "Hit Enter to continue or CTRL+C to stop...\n"; - $input = trim(fgets(STDIN)); +if (! $confirmed) { + print "Hit Enter to continue or CTRL+C to stop...\n"; + $input = trim(fgets(STDIN)); } // Open input and output files $fhandle = fopen($filepath, 'r'); -if (! $fhandle) -{ - print 'Error: Failed to open file '.$filepath."\n"; - exit(1); +if (! $fhandle) { + print 'Error: Failed to open file '.$filepath."\n"; + exit(1); } $fhandleerr = fopen($filepatherr, 'w'); -if (! $fhandleerr) -{ - print 'Error: Failed to open file '.$filepatherr."\n"; - exit(1); +if (! $fhandleerr) { + print 'Error: Failed to open file '.$filepatherr."\n"; + exit(1); } //$langs->setDefaultLang($defaultlang); @@ -114,44 +110,48 @@ $db->begin(); $i=0; $nboflines=0; -while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) -{ - $i++; - $errorrecord=0; +while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) { + $i++; + $errorrecord=0; - if ($startlinenb && $i < $startlinenb) continue; - if ($endlinenb && $i > $endlinenb) continue; + if ($startlinenb && $i < $startlinenb) { + continue; + } + if ($endlinenb && $i > $endlinenb) { + continue; + } - $nboflines++; + $nboflines++; - $object = new User($db); - $object->statut = 1; + $object = new User($db); + $object->statut = 1; - $tmp=explode(' ', $fields[3], 2); - $object->firstname = trim($tmp[0]); - $object->lastname = trim($tmp[1]); - if ($object->lastname) $object->login = strtolower(substr($object->firstname, 0, 1)) . strtolower(substr($object->lastname, 0)); - else $object->login=strtolower($object->firstname); - $object->login=preg_replace('/ /', '', $object->login); - $object->password = 'init'; + $tmp=explode(' ', $fields[3], 2); + $object->firstname = trim($tmp[0]); + $object->lastname = trim($tmp[1]); + if ($object->lastname) { + $object->login = strtolower(substr($object->firstname, 0, 1)) . strtolower(substr($object->lastname, 0)); + } else { + $object->login=strtolower($object->firstname); + } + $object->login=preg_replace('/ /', '', $object->login); + $object->password = 'init'; - print "Process line nb ".$i.", login ".$object->login; + print "Process line nb ".$i.", login ".$object->login; - $ret=$object->create($user); - if ($ret < 0) - { - print " - Error in create result code = ".$ret." - ".$object->errorsToString(); - $errorrecord++; - } else { - print " - Creation OK with login ".$object->login." - id = ".$ret; + $ret=$object->create($user); + if ($ret < 0) { + print " - Error in create result code = ".$ret." - ".$object->errorsToString(); + $errorrecord++; + } else { + print " - Creation OK with login ".$object->login." - id = ".$ret; } print "\n"; - if ($errorrecord) - { - fwrite($fhandleerr, 'Error on record nb '.$i." - ".$object->errorsToString()."\n"); - $error++; // $errorrecord will be reset + if ($errorrecord) { + fwrite($fhandleerr, 'Error on record nb '.$i." - ".$object->errorsToString()."\n"); + $error++; // $errorrecord will be reset } } @@ -162,13 +162,12 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) // commit or rollback print "Nb of lines qualified: ".$nboflines."\n"; print "Nb of errors: ".$error."\n"; -if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) -{ - print "Rollback any changes.\n"; - $db->rollback(); +if ($mode != 'confirmforced' && ($error || $mode != 'confirm')) { + print "Rollback any changes.\n"; + $db->rollback(); } else { - print "Commit all changes.\n"; - $db->commit(); + print "Commit all changes.\n"; + $db->commit(); } $db->close(); diff --git a/dev/initdata/purge-data.php b/dev/initdata/purge-data.php index 18256c33766..9214f34d810 100755 --- a/dev/initdata/purge-data.php +++ b/dev/initdata/purge-data.php @@ -30,8 +30,8 @@ $path=__DIR__.'/'; // Test si mode batch if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit(-1); + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit(-1); } // Recupere root dolibarr @@ -52,121 +52,121 @@ $error=0; // List of sql to execute $sqls=array( - 'user'=>array( - "DELETE FROM ".MAIN_DB_PREFIX."user_rights WHERE fk_user IN (SELECT rowid FROM ".MAIN_DB_PREFIX."user WHERE admin = 0 and login != 'admin') AND fk_user IN (select rowid FROM ".MAIN_DB_PREFIX."user where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."user WHERE admin = 0 and login != 'admin' AND datec < '__DATE__'", - ), - 'event'=>array( - //"DELETE FROM ".MAIN_DB_PREFIX."actioncomm WHERE lineid IN (SELECT rowid FROM ".MAIN_DB_PREFIX."bank WHERE datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."actioncomm WHERE datec < '__DATE__'", - ), - 'payment'=>array( - "DELETE FROM ".MAIN_DB_PREFIX."paiement_facture where fk_facture IN (select rowid FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."paiement where rowid NOT IN (SELECT fk_paiement FROM ".MAIN_DB_PREFIX."paiement_facture)", - ), - 'supplier_payment'=>array( - "DELETE FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn where fk_facturefourn IN (select rowid FROM ".MAIN_DB_PREFIX."facture_fourn where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."paiementfourn where rowid NOT IN (SELECT fk_paiementfourn FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn)", - ), - 'bank'=>array( - "DELETE FROM ".MAIN_DB_PREFIX."bank_class WHERE lineid IN (SELECT rowid FROM ".MAIN_DB_PREFIX."bank WHERE datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."bank_url WHERE fk_bank IN (SELECT rowid FROM ".MAIN_DB_PREFIX."bank WHERE datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."bank WHERE datec < '__DATE__'", - ), - 'bankaccount'=>array( - "DELETE FROM ".MAIN_DB_PREFIX."bank_account WHERE datec < '__DATE__'", - ), - 'invoice'=>array( - '@payment', - "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except where fk_facture_source IN (select rowid FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except where fk_facture IN (select rowid FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except where fk_facture_line IN (select rowid FROM ".MAIN_DB_PREFIX."facturedet as fd WHERE fd.fk_facture IN (select rowid from ".MAIN_DB_PREFIX."facture where datec < '__DATE__'))", - "DELETE FROM ".MAIN_DB_PREFIX."facture_rec where datec < '__DATE__'", - "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE fk_facture IN (select rowid FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__')", - "UPDATE ".MAIN_DB_PREFIX."facture SET fk_facture_source = NULL WHERE fk_facture_source IN (select f2.rowid FROM (select * from ".MAIN_DB_PREFIX."facture) as f2 where f2.datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__'", - ), - 'accounting'=>array( - "DELETE FROM ".MAIN_DB_PREFIX."accounting_bookkeeping where doc_date < '__DATE__'", - ), - 'proposal'=>array( - "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE fk_propal IN (select rowid FROM ".MAIN_DB_PREFIX."propal where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."propal WHERE datec < '__DATE__'", - ), - "supplier_proposal"=>array( - "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposaldet WHERE fk_supplier_proposal IN (select rowid FROM ".MAIN_DB_PREFIX."propal where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposal where datec < '__DATE__'", - ), - 'order'=>array( - '@shipment', - "DELETE FROM ".MAIN_DB_PREFIX."commandedet WHERE fk_commande IN (select rowid FROM ".MAIN_DB_PREFIX."commande where date_creation < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."commande where date_creation < '__DATE__'", - ), - 'supplier_order'=>array( - "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet WHERE fk_commande IN (select rowid FROM ".MAIN_DB_PREFIX."commande_fournisseur where date_creation < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur where date_creation < '__DATE__'", - ), + 'user'=>array( + "DELETE FROM ".MAIN_DB_PREFIX."user_rights WHERE fk_user IN (SELECT rowid FROM ".MAIN_DB_PREFIX."user WHERE admin = 0 and login != 'admin') AND fk_user IN (select rowid FROM ".MAIN_DB_PREFIX."user where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."user WHERE admin = 0 and login != 'admin' AND datec < '__DATE__'", + ), + 'event'=>array( + //"DELETE FROM ".MAIN_DB_PREFIX."actioncomm WHERE lineid IN (SELECT rowid FROM ".MAIN_DB_PREFIX."bank WHERE datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."actioncomm WHERE datec < '__DATE__'", + ), + 'payment'=>array( + "DELETE FROM ".MAIN_DB_PREFIX."paiement_facture where fk_facture IN (select rowid FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."paiement where rowid NOT IN (SELECT fk_paiement FROM ".MAIN_DB_PREFIX."paiement_facture)", + ), + 'supplier_payment'=>array( + "DELETE FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn where fk_facturefourn IN (select rowid FROM ".MAIN_DB_PREFIX."facture_fourn where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."paiementfourn where rowid NOT IN (SELECT fk_paiementfourn FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn)", + ), + 'bank'=>array( + "DELETE FROM ".MAIN_DB_PREFIX."bank_class WHERE lineid IN (SELECT rowid FROM ".MAIN_DB_PREFIX."bank WHERE datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."bank_url WHERE fk_bank IN (SELECT rowid FROM ".MAIN_DB_PREFIX."bank WHERE datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."bank WHERE datec < '__DATE__'", + ), + 'bankaccount'=>array( + "DELETE FROM ".MAIN_DB_PREFIX."bank_account WHERE datec < '__DATE__'", + ), + 'invoice'=>array( + '@payment', + "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except where fk_facture_source IN (select rowid FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except where fk_facture IN (select rowid FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except where fk_facture_line IN (select rowid FROM ".MAIN_DB_PREFIX."facturedet as fd WHERE fd.fk_facture IN (select rowid from ".MAIN_DB_PREFIX."facture where datec < '__DATE__'))", + "DELETE FROM ".MAIN_DB_PREFIX."facture_rec where datec < '__DATE__'", + "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE fk_facture IN (select rowid FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__')", + "UPDATE ".MAIN_DB_PREFIX."facture SET fk_facture_source = NULL WHERE fk_facture_source IN (select f2.rowid FROM (select * from ".MAIN_DB_PREFIX."facture) as f2 where f2.datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."facture where datec < '__DATE__'", + ), + 'accounting'=>array( + "DELETE FROM ".MAIN_DB_PREFIX."accounting_bookkeeping where doc_date < '__DATE__'", + ), + 'proposal'=>array( + "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE fk_propal IN (select rowid FROM ".MAIN_DB_PREFIX."propal where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."propal WHERE datec < '__DATE__'", + ), + "supplier_proposal"=>array( + "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposaldet WHERE fk_supplier_proposal IN (select rowid FROM ".MAIN_DB_PREFIX."propal where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."supplier_proposal where datec < '__DATE__'", + ), + 'order'=>array( + '@shipment', + "DELETE FROM ".MAIN_DB_PREFIX."commandedet WHERE fk_commande IN (select rowid FROM ".MAIN_DB_PREFIX."commande where date_creation < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."commande where date_creation < '__DATE__'", + ), + 'supplier_order'=>array( + "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet WHERE fk_commande IN (select rowid FROM ".MAIN_DB_PREFIX."commande_fournisseur where date_creation < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur where date_creation < '__DATE__'", + ), 'supplier_invoice'=>array( '@supplier_payment', - "DELETE FROM ".MAIN_DB_PREFIX."facture_fourn_det WHERE fk_facture_fourn IN (select rowid FROM ".MAIN_DB_PREFIX."facture_fourn where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."facture_fourn where datec < '__DATE__'", - ), - 'shipment'=>array( - '@delivery', - "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_batch WHERE fk_expeditiondet IN (select rowid FROM ".MAIN_DB_PREFIX."expeditiondet WHERE fk_expedition IN (select rowid FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__'))", - "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_extrafields WHERE fk_object IN (select rowid FROM ".MAIN_DB_PREFIX."expeditiondet WHERE fk_expedition IN (select rowid FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__'))", - "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet WHERE fk_expedition IN (select rowid FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."expedition_extrafields WHERE fk_object IN (select rowid FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__'", - ), - 'delivery'=>array( - "DELETE FROM ".MAIN_DB_PREFIX."deliverydet WHERE fk_delivery IN (select rowid FROM ".MAIN_DB_PREFIX."delivery where date_creation < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."delivery where date_creation < '__DATE__'", - ), - 'contract'=>array( - "DELETE FROM ".MAIN_DB_PREFIX."contratdet_extrafields WHERE fk_object IN (select rowid FROM ".MAIN_DB_PREFIX."contratdet WHERE fk_contrat IN (select rowid FROM ".MAIN_DB_PREFIX."contrat where datec < '__DATE__'))", - "DELETE FROM ".MAIN_DB_PREFIX."contratdet WHERE fk_contrat IN (select rowid FROM ".MAIN_DB_PREFIX."contrat where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."contrat_extrafields WHERE fk_object IN (select rowid FROM ".MAIN_DB_PREFIX."contrat where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."contrat WHERE datec < '__DATE__'", - ), - 'intervention'=>array( - "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet WHERE fk_fichinter IN (select rowid FROM ".MAIN_DB_PREFIX."fichinter where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."fichinter where datec < '__DATE__'", - ), - 'stock'=>array( - "DELETE FROM ".MAIN_DB_PREFIX."stock_mouvement WHERE datem < '__DATE__'", - ), - 'product'=>array( - "DELETE FROM ".MAIN_DB_PREFIX."categorie_product WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."product_lang WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."product_price_by_qty WHERE fk_product_price IN (select rowid FROM ".MAIN_DB_PREFIX."product_price where fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__'))", - "DELETE FROM ".MAIN_DB_PREFIX."product_price WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."product_batch WHERE fk_product_stock IN (select rowid FROM ".MAIN_DB_PREFIX."product_stock where fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__'))", - "DELETE FROM ".MAIN_DB_PREFIX."product_stock WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."product_lot WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__'", - ), - 'project'=>array( - // TODO set fk_project to null on object that refer to project - "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time WHERE fk_task IN (select rowid FROM ".MAIN_DB_PREFIX."projet_task WHERE fk_projet IN (select rowid FROM ".MAIN_DB_PREFIX."projet where datec < '__DATE__'))", - "DELETE FROM ".MAIN_DB_PREFIX."projet_task WHERE fk_projet IN (select rowid FROM ".MAIN_DB_PREFIX."projet where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."projet where datec < '__DATE__'", - ), - 'contact'=>array( - "DELETE FROM ".MAIN_DB_PREFIX."categorie_contact WHERE fk_socpeople IN (select rowid FROM ".MAIN_DB_PREFIX."socpeople where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."socpeople where datec < '__DATE__'", - ), - 'thirdparty'=>array( - '@contact', - "DELETE FROM ".MAIN_DB_PREFIX."cabinetmed_cons WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')", - "UPDATE ".MAIN_DB_PREFIX."adherent SET fk_soc = NULL WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."categorie_fournisseur WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."categorie_societe WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."societe_rib WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')", - "DELETE FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__'", - ) + "DELETE FROM ".MAIN_DB_PREFIX."facture_fourn_det WHERE fk_facture_fourn IN (select rowid FROM ".MAIN_DB_PREFIX."facture_fourn where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."facture_fourn where datec < '__DATE__'", + ), + 'shipment'=>array( + '@delivery', + "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_batch WHERE fk_expeditiondet IN (select rowid FROM ".MAIN_DB_PREFIX."expeditiondet WHERE fk_expedition IN (select rowid FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__'))", + "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_extrafields WHERE fk_object IN (select rowid FROM ".MAIN_DB_PREFIX."expeditiondet WHERE fk_expedition IN (select rowid FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__'))", + "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet WHERE fk_expedition IN (select rowid FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."expedition_extrafields WHERE fk_object IN (select rowid FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."expedition where date_creation < '__DATE__'", + ), + 'delivery'=>array( + "DELETE FROM ".MAIN_DB_PREFIX."deliverydet WHERE fk_delivery IN (select rowid FROM ".MAIN_DB_PREFIX."delivery where date_creation < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."delivery where date_creation < '__DATE__'", + ), + 'contract'=>array( + "DELETE FROM ".MAIN_DB_PREFIX."contratdet_extrafields WHERE fk_object IN (select rowid FROM ".MAIN_DB_PREFIX."contratdet WHERE fk_contrat IN (select rowid FROM ".MAIN_DB_PREFIX."contrat where datec < '__DATE__'))", + "DELETE FROM ".MAIN_DB_PREFIX."contratdet WHERE fk_contrat IN (select rowid FROM ".MAIN_DB_PREFIX."contrat where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."contrat_extrafields WHERE fk_object IN (select rowid FROM ".MAIN_DB_PREFIX."contrat where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."contrat WHERE datec < '__DATE__'", + ), + 'intervention'=>array( + "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet WHERE fk_fichinter IN (select rowid FROM ".MAIN_DB_PREFIX."fichinter where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."fichinter where datec < '__DATE__'", + ), + 'stock'=>array( + "DELETE FROM ".MAIN_DB_PREFIX."stock_mouvement WHERE datem < '__DATE__'", + ), + 'product'=>array( + "DELETE FROM ".MAIN_DB_PREFIX."categorie_product WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."product_lang WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."product_price_by_qty WHERE fk_product_price IN (select rowid FROM ".MAIN_DB_PREFIX."product_price where fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__'))", + "DELETE FROM ".MAIN_DB_PREFIX."product_price WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."product_batch WHERE fk_product_stock IN (select rowid FROM ".MAIN_DB_PREFIX."product_stock where fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__'))", + "DELETE FROM ".MAIN_DB_PREFIX."product_stock WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."product_lot WHERE fk_product IN (select rowid FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__'", + ), + 'project'=>array( + // TODO set fk_project to null on object that refer to project + "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time WHERE fk_task IN (select rowid FROM ".MAIN_DB_PREFIX."projet_task WHERE fk_projet IN (select rowid FROM ".MAIN_DB_PREFIX."projet where datec < '__DATE__'))", + "DELETE FROM ".MAIN_DB_PREFIX."projet_task WHERE fk_projet IN (select rowid FROM ".MAIN_DB_PREFIX."projet where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."projet where datec < '__DATE__'", + ), + 'contact'=>array( + "DELETE FROM ".MAIN_DB_PREFIX."categorie_contact WHERE fk_socpeople IN (select rowid FROM ".MAIN_DB_PREFIX."socpeople where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."socpeople where datec < '__DATE__'", + ), + 'thirdparty'=>array( + '@contact', + "DELETE FROM ".MAIN_DB_PREFIX."cabinetmed_cons WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')", + "UPDATE ".MAIN_DB_PREFIX."adherent SET fk_soc = NULL WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."categorie_fournisseur WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."categorie_societe WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."societe_rib WHERE fk_soc IN (select rowid FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__')", + "DELETE FROM ".MAIN_DB_PREFIX."societe where datec < '__DATE__'", + ) ); @@ -183,44 +183,42 @@ $option = $argv[2]; $date = $argv[3]; if (empty($mode) || ! in_array($mode, array('test','confirm'))) { - print "Usage: $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n"; - print "\n"; - print "option can be ".implode(',', array_keys($sqls))."\n"; - exit(-1); + print "Usage: $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n"; + print "\n"; + print "option can be ".implode(',', array_keys($sqls))."\n"; + exit(-1); } -if (empty($option)) -{ - print "Usage: $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n"; - print "\n"; - print "option must be defined with a value in list ".implode(',', array_keys($sqls))."\n"; - exit(-1); +if (empty($option)) { + print "Usage: $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n"; + print "\n"; + print "option must be defined with a value in list ".implode(',', array_keys($sqls))."\n"; + exit(-1); } -if ($option != 'all') -{ - $listofoptions=explode(',', $option); - foreach ($listofoptions as $cursoroption) - { - if (! in_array($cursoroption, array_keys($sqls))) { - print "Usage: $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n"; - print "\n"; - print "option '".$cursoroption."' must be in list ".implode(',', array_keys($sqls))."\n"; - exit(-1); - } - } +if ($option != 'all') { + $listofoptions=explode(',', $option); + foreach ($listofoptions as $cursoroption) { + if (! in_array($cursoroption, array_keys($sqls))) { + print "Usage: $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n"; + print "\n"; + print "option '".$cursoroption."' must be in list ".implode(',', array_keys($sqls))."\n"; + exit(-1); + } + } } if (empty($date) || (! preg_match('/\d\d\d\d\-\d\d\-\d\d$/', $date) && $date != 'all')) { - print "Usage: $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n"; - print "\n"; - print "date can be 'all' or 'YYYY-MM-DD' to delete record before YYYY-MM-DD\n"; - exit(-1); + print "Usage: $script_file (test|confirm) (all|option) (all|YYYY-MM-DD) [dbtype dbhost dbuser dbpassword dbname dbport]\n"; + print "\n"; + print "date can be 'all' or 'YYYY-MM-DD' to delete record before YYYY-MM-DD\n"; + exit(-1); } -if ($date == 'all') $date = '2199-01-01'; +if ($date == 'all') { + $date = '2199-01-01'; +} // Replace database handler -if (! empty($argv[4])) -{ +if (! empty($argv[4])) { $db->close(); unset($db); $db=getDoliDBInstance($argv[4], $argv[5], $argv[6], $argv[7], $argv[8], $argv[9]); @@ -229,8 +227,7 @@ if (! empty($argv[4])) //var_dump($user->db->database_name); $ret=$user->fetch('', 'admin'); -if (! $ret > 0) -{ +if (! $ret > 0) { print 'An admin user with login "admin" must exists to use this script.'."\n"; exit; } @@ -245,10 +242,9 @@ print "Database port = ".$db->database_port."\n"; print "User = ".$db->database_user."\n"; print "\n"; -if (! $confirmed) -{ - print "Hit Enter to continue or CTRL+C to stop...\n"; - $input = trim(fgets(STDIN)); +if (! $confirmed) { + print "Hit Enter to continue or CTRL+C to stop...\n"; + $input = trim(fgets(STDIN)); } @@ -261,73 +257,71 @@ if (! $confirmed) */ function processfamily($family, $date) { - global $db, $sqls; + global $db, $sqls; - $error=0; - foreach ($sqls[$family] as $sql) - { - if (preg_match('/^@/', $sql)) - { - $newfamily=preg_replace('/@/', '', $sql); - processfamily($newfamily, $date); - continue; - } + $error=0; + foreach ($sqls[$family] as $sql) { + if (preg_match('/^@/', $sql)) { + $newfamily=preg_replace('/@/', '', $sql); + processfamily($newfamily, $date); + continue; + } - $sql = preg_replace('/__DATE__/', $date, $sql); + $sql = preg_replace('/__DATE__/', $date, $sql); - print "Run sql: ".$sql."\n"; + print "Run sql: ".$sql."\n"; - $resql=$db->query($sql); - if (! $resql) - { - if ($db->errno() != 'DB_ERROR_NOSUCHTABLE') - { - $error++; - } - } + $resql=$db->query($sql); + if (! $resql) { + if ($db->errno() != 'DB_ERROR_NOSUCHTABLE') { + $error++; + } + } - if ($error) - { - print $db->lasterror(); - $error++; - break; - } - } + if ($error) { + print $db->lasterror(); + $error++; + break; + } + } - if ($error) return -1; - else return 1; + if ($error) { + return -1; + } else { + return 1; + } } $db->begin(); $listofoptions=explode(',', $option); -foreach ($listofoptions as $cursoroption) -{ - $oldfamily=''; - foreach ($sqls as $family => $familysql) - { - if ($cursoroption && $cursoroption != 'all' && $cursoroption != $family) continue; +foreach ($listofoptions as $cursoroption) { + $oldfamily=''; + foreach ($sqls as $family => $familysql) { + if ($cursoroption && $cursoroption != 'all' && $cursoroption != $family) { + continue; + } - if ($family != $oldfamily) print "Process action for family ".$family."\n"; - $oldfamily = $family; + if ($family != $oldfamily) { + print "Process action for family ".$family."\n"; + } + $oldfamily = $family; - $result=processfamily($family, $date); - if ($result < 0) - { - $error++; - break; - } - } + $result=processfamily($family, $date); + if ($result < 0) { + $error++; + break; + } + } } -if ($error || $mode != 'confirm') -{ - print "\nRollback any changes.\n"; - $db->rollback(); +if ($error || $mode != 'confirm') { + print "\nRollback any changes.\n"; + $db->rollback(); } else { - print "Commit all changes.\n"; - $db->commit(); + print "Commit all changes.\n"; + $db->commit(); } $db->close(); diff --git a/dev/initdemo/sftpget_and_loaddump.php b/dev/initdemo/sftpget_and_loaddump.php index 4da5ffaad58..7d781fe5b0c 100755 --- a/dev/initdemo/sftpget_and_loaddump.php +++ b/dev/initdemo/sftpget_and_loaddump.php @@ -41,14 +41,30 @@ $passwordbase=isset($argv[6])?$argv[6]:''; // Include Dolibarr environment $res=0; -if (! $res && file_exists($path."../../master.inc.php")) $res=@include $path."../../master.inc.php"; -if (! $res && file_exists($path."../../htdocs/master.inc.php")) $res=@include $path."../../htdocs/master.inc.php"; -if (! $res && file_exists("../master.inc.php")) $res=@include "../master.inc.php"; -if (! $res && file_exists("../../master.inc.php")) $res=@include "../../master.inc.php"; -if (! $res && file_exists("../../../master.inc.php")) $res=@include "../../../master.inc.php"; -if (! $res && preg_match('/\/nltechno([^\/]*)\//', $_SERVER["PHP_SELF"], $reg)) $res=@include $path."../../../dolibarr".$reg[1]."/htdocs/master.inc.php"; // Used on dev env only -if (! $res && preg_match('/\/nltechno([^\/]*)\//', $_SERVER["PHP_SELF"], $reg)) $res=@include "../../../dolibarr".$reg[1]."/htdocs/master.inc.php"; // Used on dev env only -if (! $res) die("Failed to include master.inc.php file\n"); +if (! $res && file_exists($path."../../master.inc.php")) { + $res=@include $path."../../master.inc.php"; +} +if (! $res && file_exists($path."../../htdocs/master.inc.php")) { + $res=@include $path."../../htdocs/master.inc.php"; +} +if (! $res && file_exists("../master.inc.php")) { + $res=@include "../master.inc.php"; +} +if (! $res && file_exists("../../master.inc.php")) { + $res=@include "../../master.inc.php"; +} +if (! $res && file_exists("../../../master.inc.php")) { + $res=@include "../../../master.inc.php"; +} +if (! $res && preg_match('/\/nltechno([^\/]*)\//', $_SERVER["PHP_SELF"], $reg)) { + $res=@include $path."../../../dolibarr".$reg[1]."/htdocs/master.inc.php"; // Used on dev env only +} +if (! $res && preg_match('/\/nltechno([^\/]*)\//', $_SERVER["PHP_SELF"], $reg)) { + $res=@include "../../../dolibarr".$reg[1]."/htdocs/master.inc.php"; // Used on dev env only +} +if (! $res) { + die("Failed to include master.inc.php file\n"); +} include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -58,15 +74,13 @@ include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $login=''; $server=''; -if (preg_match('/^(.*)@(.*):(.*)$/', $sourceserver, $reg)) -{ +if (preg_match('/^(.*)@(.*):(.*)$/', $sourceserver, $reg)) { $login=$reg[1]; $server=$reg[2]; $sourcefile=$reg[3]; $targetfile=basename($sourcefile); } -if (empty($sourceserver) || empty($server) || empty($login) || empty($sourcefile) || empty($password) || empty($database) || empty($loginbase) || empty($passwordbase)) -{ +if (empty($sourceserver) || empty($server) || empty($login) || empty($sourcefile) || empty($password) || empty($database) || empty($loginbase) || empty($passwordbase)) { print "Usage: $script_file login@server:/src/file.(sql|gz|bz2) passssh databaseserver databasename loginbase passbase\n"; print "Return code: 0 if success, <>0 if error\n"; print "Warning, this script may take a long time.\n"; @@ -88,14 +102,11 @@ if (! function_exists("ssh2_connect")) { } $connection = ssh2_connect($server, 22); -if ($connection) -{ - if (! @ssh2_auth_password($connection, $login, $password)) - { +if ($connection) { + if (! @ssh2_auth_password($connection, $login, $password)) { dol_syslog("Could not authenticate with username ".$login." . and password ".preg_replace('/./', '*', $password), LOG_ERR); exit(-5); - } - else { + } else { //$stream = ssh2_exec($connection, '/usr/bin/php -i'); /* print "Generate dump ".$filesys1.'.bz2'."\n"; @@ -111,12 +122,10 @@ if ($connection) ssh2_scp_recv($connection, $sourcefile, $targetdir.$targetfile); $fullcommand="cat ".$targetdir.$targetfile." | mysql -h".$databaseserver." -u".$loginbase." -p".$passwordbase." -D ".$database; - if (preg_match('/\.bz2$/', $targetfile)) - { + if (preg_match('/\.bz2$/', $targetfile)) { $fullcommand="bzip2 -c -d ".$targetdir.$targetfile." | mysql -h".$databaseserver." -u".$loginbase." -p".$passwordbase." -D ".$database; } - if (preg_match('/\.gz$/', $targetfile)) - { + if (preg_match('/\.gz$/', $targetfile)) { $fullcommand="gzip -d ".$targetdir.$targetfile." | mysql -h".$databaseserver." -u".$loginbase." -p".$passwordbase." -D ".$database; } print "Load dump with ".$fullcommand."\n"; @@ -124,13 +133,14 @@ if ($connection) $return_var=0; print strftime("%Y%m%d-%H%M%S").' '.$fullcommand."\n"; exec($fullcommand, $output, $return_var); - foreach ($output as $line) print $line."\n"; + foreach ($output as $line) { + print $line."\n"; + } //ssh2_sftp_unlink($sftp, $fileinstalllock); //print $output; } -} -else { +} else { print 'Failed to connect to ssh2 to '.$server; exit(-6); } diff --git a/dev/initdemo/updatedemo.php b/dev/initdemo/updatedemo.php index 5da0d4a2498..4dd98451823 100755 --- a/dev/initdemo/updatedemo.php +++ b/dev/initdemo/updatedemo.php @@ -36,14 +36,30 @@ $confirm=isset($argv[1])?$argv[1]:''; // Include Dolibarr environment $res=0; -if (! $res && file_exists($path."../../master.inc.php")) $res=@include $path."../../master.inc.php"; -if (! $res && file_exists($path."../../htdocs/master.inc.php")) $res=@include $path."../../htdocs/master.inc.php"; -if (! $res && file_exists("../master.inc.php")) $res=@include "../master.inc.php"; -if (! $res && file_exists("../../master.inc.php")) $res=@include "../../master.inc.php"; -if (! $res && file_exists("../../../master.inc.php")) $res=@include "../../../master.inc.php"; -if (! $res && preg_match('/\/nltechno([^\/]*)\//', $_SERVER["PHP_SELF"], $reg)) $res=@include $path."../../../dolibarr".$reg[1]."/htdocs/master.inc.php"; // Used on dev env only -if (! $res && preg_match('/\/nltechno([^\/]*)\//', $_SERVER["PHP_SELF"], $reg)) $res=@include "../../../dolibarr".$reg[1]."/htdocs/master.inc.php"; // Used on dev env only -if (! $res) die("Failed to include master.inc.php file\n"); +if (! $res && file_exists($path."../../master.inc.php")) { + $res=@include $path."../../master.inc.php"; +} +if (! $res && file_exists($path."../../htdocs/master.inc.php")) { + $res=@include $path."../../htdocs/master.inc.php"; +} +if (! $res && file_exists("../master.inc.php")) { + $res=@include "../master.inc.php"; +} +if (! $res && file_exists("../../master.inc.php")) { + $res=@include "../../master.inc.php"; +} +if (! $res && file_exists("../../../master.inc.php")) { + $res=@include "../../../master.inc.php"; +} +if (! $res && preg_match('/\/nltechno([^\/]*)\//', $_SERVER["PHP_SELF"], $reg)) { + $res=@include $path."../../../dolibarr".$reg[1]."/htdocs/master.inc.php"; // Used on dev env only +} +if (! $res && preg_match('/\/nltechno([^\/]*)\//', $_SERVER["PHP_SELF"], $reg)) { + $res=@include "../../../dolibarr".$reg[1]."/htdocs/master.inc.php"; // Used on dev env only +} +if (! $res) { + die("Failed to include master.inc.php file\n"); +} include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -53,8 +69,7 @@ include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; print "***** ".$script_file." *****\n"; print "Update dates to current year for database name = ".$db->database_name."\n"; -if (empty($confirm)) -{ +if (empty($confirm)) { print "Usage: $script_file confirm\n"; print "Return code: 0 if success, <>0 if error\n"; exit(-1); @@ -65,66 +80,65 @@ $tmp=dol_getdate(dol_now()); $tables=array( - 'propal'=>array(0=>'datep', 1=>'fin_validite', 2=>'date_valid', 3=>'date_cloture'), - 'commande'=>array(0=>'date_commande', 1=>'date_valid', 2=>'date_cloture'), + 'propal'=>array(0=>'datep', 1=>'fin_validite', 2=>'date_valid', 3=>'date_cloture'), + 'commande'=>array(0=>'date_commande', 1=>'date_valid', 2=>'date_cloture'), 'facture'=>array(0=>'datec', 0=>'datef', 1=>'date_valid', 2=>'date_lim_reglement'), - 'paiement'=>array(0=>'datep'), - 'bank'=>array(0=>'datev', 1=>'dateo'), - 'commande_fournisseur'=>array(0=>'date_commande', 1=>'date_valid', 3=>'date_creation', 4=>'date_approve', 5=>'date_approve2', 6=>'date_livraison'), - 'supplier_proposal'=>array(0=>'datec', 1=>'date_valid', 2=>'date_cloture'), + 'paiement'=>array(0=>'datep'), + 'bank'=>array(0=>'datev', 1=>'dateo'), + 'commande_fournisseur'=>array(0=>'date_commande', 1=>'date_valid', 3=>'date_creation', 4=>'date_approve', 5=>'date_approve2', 6=>'date_livraison'), + 'supplier_proposal'=>array(0=>'datec', 1=>'date_valid', 2=>'date_cloture'), 'expensereport'=>array(0=>'date_debut', 1=>'date_fin', 2=>'date_create', 3=>'date_valid', 4=>'date_approve', 5=>'date_refuse', 6=>'date_cancel'), - 'holiday'=>array(0=>'date_debut', 1=>'date_fin', 2=>'date_create', 3=>'date_valid', 5=>'date_refuse', 6=>'date_cancel') + 'holiday'=>array(0=>'date_debut', 1=>'date_fin', 2=>'date_create', 3=>'date_valid', 5=>'date_refuse', 6=>'date_cancel'), + 'ticket'=>array(0=>'datec', 1=>'date_read', 2=>'date_close') ); $year=2010; $currentyear=$tmp['year']; -while ($year <= $currentyear) -{ - //$year=2021; - $delta1=($currentyear - $year); - $delta2=($currentyear - $year - 1); - //$delta=-1; +while ($year <= $currentyear) { + //$year=2021; + $delta1=($currentyear - $year); + $delta2=($currentyear - $year - 1); + //$delta=-1; - if ($delta1) - { - foreach ($tables as $tablekey => $tableval) - { - print "Correct ".$tablekey." for year ".$year." and move them to current year ".$currentyear." "; - $sql="select rowid from ".MAIN_DB_PREFIX.$tablekey." where ".$tableval[0]." between '".$year."-01-01' and '".$year."-12-31' and ".$tableval[0]." < DATE_ADD(NOW(), INTERVAL -1 YEAR)"; - //$sql="select rowid from ".MAIN_DB_PREFIX.$tablekey." where ".$tableval[0]." between '".$year."-01-01' and '".$year."-12-31' and ".$tableval[0]." > NOW()"; - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i=0; - while ($i < $num) - { - $obj=$db->fetch_object($resql); - if ($obj) - { - print "."; - $sql2="UPDATE ".MAIN_DB_PREFIX.$tablekey." set "; - $j=0; - foreach ($tableval as $field) - { - if ($j) $sql2.=", "; - $sql2.= $field." = ".$db->ifsql("DATE_ADD(".$field.", INTERVAL ".$delta1." YEAR) > NOW()", "DATE_ADD(".$field.", INTERVAL ".$delta2." YEAR)", "DATE_ADD(".$field.", INTERVAL ".$delta1." YEAR)"); - $j++; - } - $sql2.=" WHERE rowid = ".$obj->rowid; - //print $sql2."\n"; - $resql2 = $db->query($sql2); - if (! $resql2) dol_print_error($db); - } - $i++; - } - } - else dol_print_error($db); - print "\n"; - } - } + if ($delta1) { + foreach ($tables as $tablekey => $tableval) { + print "Correct ".$tablekey." for year ".$year." and move them to current year ".$currentyear." "; + $sql="select rowid from ".MAIN_DB_PREFIX.$tablekey." where ".$tableval[0]." between '".$year."-01-01' and '".$year."-12-31' and ".$tableval[0]." < DATE_ADD(NOW(), INTERVAL -1 YEAR)"; + //$sql="select rowid from ".MAIN_DB_PREFIX.$tablekey." where ".$tableval[0]." between '".$year."-01-01' and '".$year."-12-31' and ".$tableval[0]." > NOW()"; + $resql = $db->query($sql); + if ($resql) { + $num = $db->num_rows($resql); + $i=0; + while ($i < $num) { + $obj=$db->fetch_object($resql); + if ($obj) { + print "."; + $sql2="UPDATE ".MAIN_DB_PREFIX.$tablekey." set "; + $j=0; + foreach ($tableval as $field) { + if ($j) { + $sql2.=", "; + } + $sql2.= $field." = ".$db->ifsql("DATE_ADD(".$field.", INTERVAL ".$delta1." YEAR) > NOW()", "DATE_ADD(".$field.", INTERVAL ".$delta2." YEAR)", "DATE_ADD(".$field.", INTERVAL ".$delta1." YEAR)"); + $j++; + } + $sql2.=" WHERE rowid = ".$obj->rowid; + //print $sql2."\n"; + $resql2 = $db->query($sql2); + if (! $resql2) { + dol_print_error($db); + } + } + $i++; + } + } else { + dol_print_error($db); + } + print "\n"; + } + } - $year++; + $year++; } print "\n"; diff --git a/dev/setup/codesniffer/ruleset.xml b/dev/setup/codesniffer/ruleset.xml index db4945a654c..e99b8673981 100644 --- a/dev/setup/codesniffer/ruleset.xml +++ b/dev/setup/codesniffer/ruleset.xml @@ -7,7 +7,7 @@ build/html build/aps dev/tools/test/namespacemig - dev/initdata/dbf/includes + documents htdocs/core/class/lessc.class.php htdocs/custom @@ -104,9 +104,9 @@ --> - + @@ -174,8 +174,8 @@ - - + + @@ -214,8 +214,8 @@ - - + + diff --git a/dev/setup/git/hooks/pre-commit b/dev/setup/git/hooks/pre-commit new file mode 100644 index 00000000000..51b7c5cf4e9 --- /dev/null +++ b/dev/setup/git/hooks/pre-commit @@ -0,0 +1,73 @@ +#!/bin/sh +# To install this precommit file: put this file in your local repo in .git/hooks directory and make it executable. +# You may need to set th DIRPHPCS to the path to your phpcs install. +# If phpcs check fail and AUTOFIX is set to 1, then it run phpcbf to fix automaticaly the syntax, and git commit is canceled. +# If you have a multiprocessor computer, you can add to the option --parallel=xx +# When running git commit, it first execute this file checking only modified files, so it is faster than running on all files +# To run the fix manually: cd ~/git/dolibarr; phpcbf -s -p -d memory_limit=-1 --extensions=php --colors --tab-width=4 --standard=dev/setup/codesniffer/ruleset.xml --encoding=utf-8 --runtime-set ignore_warnings_on_exit true "fileordir" + +PROJECT=`php -r "echo dirname(dirname(dirname(realpath('$0'))));"` +STAGED_FILES_CMD=`git diff --cached --name-only --diff-filter=ACMR HEAD | grep \\\\.php` +DIRPHPCS="" +AUTOFIX=1 + +echo "Running precommit hook in .git/hooks/pre-commit" 1>&2; + +# Determine if a file list is passed +if [ "$#" -eq 1 ] +then + oIFS=$IFS + IFS=' + ' + SFILES="$1" + IFS=$oIFS +fi +SFILES=${SFILES:-$STAGED_FILES_CMD} + +echo "Checking PHP Lint with php -l ..." + +for FILE in $SFILES +do + php -l -d display_errors=0 $PROJECT/$FILE + + result1=$? + + if [ "x$result1" != "x0" ] + then + echo "Fix the error before commit." 1>&2; + exit 1 + fi + FILES="$FILES $PROJECT/$FILE" +done + + +if [ "$FILES" != "" ] +then + echo "Running PHPCS Code Sniffer..." + + #~/vendor/bin/phpcs --version + #phpcs --standard=PSR2 --encoding=utf-8 -n -p $FILES + # Check Dolibarr standard + ${DIRPHPCS}phpcs -s -p -d memory_limit=-1 --parallel=2 --extensions=php --colors --tab-width=4 --standard=dev/setup/codesniffer/ruleset.xml --encoding=utf-8 --runtime-set ignore_warnings_on_exit true $FILES + # Check your own standard + #${DIRPHPCS}phpcs -s -p -d memory_limit=-1 --parallel=2 --extensions=php --colors --tab-width=4 --standard=htdocs/custom/codesniffer/ruleset.xml --encoding=utf-8 --runtime-set ignore_warnings_on_exit true $FILES + + result2=$? + + if [ "x$result2" != "x0" ] + then + # Fix standard errors + if [ "x$AUTOFIX" != "x0" ] + then + ${DIRPHPCS}phpcbf -s -p -d memory_limit=-1 --extensions=php --colors --tab-width=4 --standard=dev/setup/codesniffer/ruleset.xml --encoding=utf-8 --runtime-set ignore_warnings_on_exit true $FILES + #${DIRPHPCS}phpcbf -s -p -d memory_limit=-1 --extensions=php --colors --tab-width=4 --standard=htdocs/custom/codesniffer/ruleset.xml --encoding=utf-8 --runtime-set ignore_warnings_on_exit true $FILES + echo "Found some errors in syntax rules. An automatic fix has been applied. Check it before commit." 1>&2; + exit 1 + else + echo "Found some errors in syntax rules. Fix the error(s) before commit." 1>&2; + exit 1 + fi + fi +fi + +exit 0 diff --git a/dev/tools/dolibarr-postgres2mysql.php b/dev/tools/dolibarr-postgres2mysql.php index fd30540c019..1a997ddc63c 100644 --- a/dev/tools/dolibarr-postgres2mysql.php +++ b/dev/tools/dolibarr-postgres2mysql.php @@ -48,8 +48,9 @@ if (! ($argv[1] && $argv[2])) { echo "Usage: php pg2mysql_cli.php [engine]\n"; exit(); } else { - if (isset($argv[3])) + if (isset($argv[3])) { $config['engine'] = $argv[3]; + } pg2mysql_large($argv[1], $argv[2]); echo <<SetKeywords('TCPDF, PDF, example, test, guide'); $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 016', PDF_HEADER_STRING); // set header and footer fonts -$pdf->setHeaderFont(Array('helvetica', '', PDF_FONT_SIZE_MAIN)); -$pdf->setFooterFont(Array('helvetica', '', PDF_FONT_SIZE_DATA)); +$pdf->setHeaderFont(array('helvetica', '', PDF_FONT_SIZE_MAIN)); +$pdf->setFooterFont(array('helvetica', '', PDF_FONT_SIZE_DATA)); // set default monospaced font $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); diff --git a/dev/tools/test/testutf.php b/dev/tools/test/testutf.php index b981257ccb7..9ce8d6a7583 100644 --- a/dev/tools/test/testutf.php +++ b/dev/tools/test/testutf.php @@ -64,8 +64,8 @@ $pdf->SetKeywords('TCPDF, PDF, example, test, guide'); $pdf->SetHeaderData('', PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 038', PDF_HEADER_STRING); // set header and footer fonts -$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); -$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); +$pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); +$pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); // set default monospaced font $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); diff --git a/dev/translation/autotranslator.class.php b/dev/translation/autotranslator.class.php index b51515a42cb..956ad95b9b6 100644 --- a/dev/translation/autotranslator.class.php +++ b/dev/translation/autotranslator.class.php @@ -40,18 +40,18 @@ class autoTranslator const DIR_SEPARATOR = '/'; - /** - * Constructor - * - * @param string $_destlang Destination lang - * @param string $_refLang Ref lang - * @param string $_langDir Dir lang - * @param string $_limittofile Limit to file - * @param string $_apikey Api key - * @return void - */ - public function __construct($_destlang, $_refLang, $_langDir, $_limittofile, $_apikey) - { + /** + * Constructor + * + * @param string $_destlang Destination lang + * @param string $_refLang Ref lang + * @param string $_langDir Dir lang + * @param string $_limittofile Limit to file + * @param string $_apikey Api key + * @return void + */ + public function __construct($_destlang, $_refLang, $_langDir, $_limittofile, $_apikey) + { // Set enviorment variables $this->_destlang = $_destlang; @@ -59,7 +59,7 @@ class autoTranslator $this->_langDir = $_langDir.self::DIR_SEPARATOR; $this->_time = date('Y-m-d H:i:s'); $this->_limittofile = $_limittofile; - $this->_apikey = $_apikey; + $this->_apikey = $_apikey; // Translate //ini_set('default_charset','UTF-8'); @@ -77,9 +77,10 @@ class autoTranslator $files = $this->getTranslationFilesArray($this->_refLang); $counter = 1; - foreach ($files as $file) - { - if ($this->_limittofile && $this->_limittofile != $file) continue; + foreach ($files as $file) { + if ($this->_limittofile && $this->_limittofile != $file) { + continue; + } $counter++; $fileContent = null; $refPath = $this->_langDir.$this->_refLang.self::DIR_SEPARATOR.$file; @@ -88,54 +89,66 @@ class autoTranslator // Define target dirs $targetlangs=array($this->_destlang); - if ($this->_destlang == 'all') - { + if ($this->_destlang == 'all') { $targetlangs=array(); // If we must process all languages $arraytmp=dol_dir_list($this->_langDir, 'directories', 0); - foreach ($arraytmp as $dirtmp) - { - if ($dirtmp['name'] === $this->_refLang) continue; // We discard source language + foreach ($arraytmp as $dirtmp) { + if ($dirtmp['name'] === $this->_refLang) { + continue; // We discard source language + } $tmppart=explode('_', $dirtmp['name']); - if (preg_match('/^en/i', $dirtmp['name'])) continue; // We discard en_* languages - if (preg_match('/^fr/i', $dirtmp['name'])) continue; // We discard fr_* languages - if (preg_match('/^es/i', $dirtmp['name'])) continue; // We discard es_* languages - if (preg_match('/ca_ES/i', $dirtmp['name'])) continue; // We discard es_CA language - if (preg_match('/pt_BR/i', $dirtmp['name'])) continue; // We discard pt_BR language - if (preg_match('/nl_BE/i', $dirtmp['name'])) continue; // We discard nl_BE language - if (preg_match('/^\./i', $dirtmp['name'])) continue; // We discard files .* - if (preg_match('/^CVS/i', $dirtmp['name'])) continue; // We discard CVS + if (preg_match('/^en/i', $dirtmp['name'])) { + continue; // We discard en_* languages + } + if (preg_match('/^fr/i', $dirtmp['name'])) { + continue; // We discard fr_* languages + } + if (preg_match('/^es/i', $dirtmp['name'])) { + continue; // We discard es_* languages + } + if (preg_match('/ca_ES/i', $dirtmp['name'])) { + continue; // We discard es_CA language + } + if (preg_match('/pt_BR/i', $dirtmp['name'])) { + continue; // We discard pt_BR language + } + if (preg_match('/nl_BE/i', $dirtmp['name'])) { + continue; // We discard nl_BE language + } + if (preg_match('/^\./i', $dirtmp['name'])) { + continue; // We discard files .* + } + if (preg_match('/^CVS/i', $dirtmp['name'])) { + continue; // We discard CVS + } $targetlangs[]=$dirtmp['name']; } //var_dump($targetlangs); } // Process translation of source file for each target languages - foreach ($targetlangs as $my_destlang) - { + foreach ($targetlangs as $my_destlang) { $this->_translatedFiles = array(); $destPath = $this->_langDir.$my_destlang.self::DIR_SEPARATOR.$file; // Check destination file presence - if (! file_exists($destPath)) - { + if (! file_exists($destPath)) { // No file present, we generate file echo "File not found: " . $destPath . ". We generate it.
\n"; $this->createTranslationFile($destPath, $my_destlang); - } - else { + } else { echo "Updating file: " . $destPath . "
\n"; } // Translate lines $fileContentDest = file($destPath, FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES); $newlines=0; - foreach ($fileContent as $line){ + foreach ($fileContent as $line) { $key = $this->getLineKey($line); $value = $this->getLineValue($line); - if ($key && $value) - { + if ($key && $value) { $newlines+=$this->translateFileLine($fileContentDest, $file, $key, $value, $my_destlang); } } @@ -159,8 +172,7 @@ class autoTranslator { $this->_time_end = date('Y-m-d H:i:s'); - if (isset($this->_translatedFiles[$file]) && count($this->_translatedFiles[$file])>0) - { + if (isset($this->_translatedFiles[$file]) && count($this->_translatedFiles[$file])>0) { $fp = fopen($destPath, 'a'); fwrite($fp, "\n"); fwrite($fp, "\n"); @@ -213,27 +225,31 @@ class autoTranslator $destValue = $this->getLineValue($line); // If translated return //print "destKey=".$destKey."\n"; - if ( trim($destKey) == trim($key) ) - { // Found already existing translation (key already exits in dest file) + if (trim($destKey) == trim($key)) { // Found already existing translation (key already exits in dest file) return 0; } } if ($key == 'CHARSET') { - $val=$this->_outputpagecode; - } elseif (preg_match('/^Format/', $key)) { - $val=$value; - } elseif ($value=='-') { - $val=$value; - } else { + $val=$this->_outputpagecode; + } elseif (preg_match('/^Format/', $key)) { + $val=$value; + } elseif ($value=='-') { + $val=$value; + } else { // If not translated then translate - if ($this->_outputpagecode == 'UTF-8') $val=$this->translateTexts(array($value), substr($this->_refLang, 0, 2), substr($my_destlang, 0, 2)); - else $val=utf8_decode($this->translateTexts(array($value), substr($this->_refLang, 0, 2), substr($my_destlang, 0, 2))); + if ($this->_outputpagecode == 'UTF-8') { + $val=$this->translateTexts(array($value), substr($this->_refLang, 0, 2), substr($my_destlang, 0, 2)); + } else { + $val=utf8_decode($this->translateTexts(array($value), substr($this->_refLang, 0, 2), substr($my_destlang, 0, 2))); + } } $val=trim($val); - if (empty($val)) return 0; + if (empty($val)) { + return 0; + } $this->_translatedFiles[$file][] = $key . '=' . $val ; return 1; @@ -293,9 +309,13 @@ class autoTranslator { // We want to be sure that src_lang and dest_lang are using 2 chars only $tmp=explode('_', $src_lang); - if (! empty($tmp[1]) && $tmp[0] == $tmp[1]) $src_lang=$tmp[0]; + if (! empty($tmp[1]) && $tmp[0] == $tmp[1]) { + $src_lang=$tmp[0]; + } $tmp=explode('_', $dest_lang); - if (! empty($tmp[1]) && $tmp[0] == $tmp[1]) $dest_lang=$tmp[0]; + if (! empty($tmp[1]) && $tmp[0] == $tmp[1]) { + $dest_lang=$tmp[0]; + } //setting language pair $lang_pair = $src_lang.'|'.$dest_lang; @@ -306,17 +326,16 @@ class autoTranslator // Define GET URL v1 //$url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=".urlencode($src_text_to_translate)."&langpair=".urlencode($lang_pair); // Example: http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=Setup%20area&langpair=en_US|fr_FR - // Define GET URL v2 + // Define GET URL v2 $url = "https://www.googleapis.com/language/translate/v2?key=".$this->_apikey."&q=".urlencode($src_text_to_translate)."&source=".urlencode($src_lang)."&target=".urlencode($dest_lang); // Example: https://www.googleapis.com/language/translate/v2?key=_apikey&q=Setup%20area&source=en_US&target=fr_FR // Send request //print "Url to translate: ".$url."\n"; - if (! function_exists("curl_init")) - { - print "Error, your PHP does not support curl functions.\n"; - die(); + if (! function_exists("curl_init")) { + print "Error, your PHP does not support curl functions.\n"; + die(); } $ch = curl_init(); @@ -331,9 +350,8 @@ class autoTranslator $json = json_decode($body, true); if ((! empty($json['responseStatus']) && $json['responseStatus'] != 200) - || count($json['data']['translations']) == 0) - { - print "Error: ".$json['responseStatus']." ".$url."\n"; + || count($json['data']['translations']) == 0) { + print "Error: ".$json['responseStatus']." ".$url."\n"; return false; } @@ -345,5 +363,5 @@ class autoTranslator //print "OK ".join('',$src_texts).' => '.$rep."\n"; return $rep; - } + } } diff --git a/dev/translation/autotranslator.php b/dev/translation/autotranslator.php index fd02febbdcc..a8f6565b891 100755 --- a/dev/translation/autotranslator.php +++ b/dev/translation/autotranslator.php @@ -32,8 +32,8 @@ $path=dirname(__FILE__).'/'; // Test if batch mode if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; } // Include Dolibarr environment @@ -56,10 +56,10 @@ $dir=DOL_DOCUMENT_ROOT."/langs"; // Check parameters if (! isset($argv[3])) { - print "Usage: ".$script_file." lang_code_src lang_code_dest|all APIKEY [langfile.lang]\n"; - print "Example: ".$script_file." en_US pt_PT 123456\n"; - print "Rem: lang_code to use can be found on https://translate.google.com\n"; - exit; + print "Usage: ".$script_file." lang_code_src lang_code_dest|all APIKEY [langfile.lang]\n"; + print "Example: ".$script_file." en_US pt_PT 123456\n"; + print "Rem: lang_code to use can be found on https://translate.google.com\n"; + exit; } // Show parameters @@ -67,21 +67,17 @@ print 'Argument 1='.$argv[1]."\n"; print 'Argument 2='.$argv[2]."\n"; print 'Argument 3='.$argv[3]."\n"; $file=''; -if (isset($argv[4])) -{ +if (isset($argv[4])) { $file=$argv[4]; print 'Argument 4='.$argv[4]."\n"; } print 'Files will be generated/updated in directory '.$dir."\n"; -if ($argv[2] != 'all') -{ - if (! is_dir($dir.'/'.$argv[2])) - { +if ($argv[2] != 'all') { + if (! is_dir($dir.'/'.$argv[2])) { print 'Create directory '.$dir.'/'.$argv[2]."\n"; $result=mkdir($dir.'/'.$argv[2]); - if (! $result) - { + if (! $result) { $db->close(); return -1; } diff --git a/dev/translation/sanity_check_en_langfiles.php b/dev/translation/sanity_check_en_langfiles.php index 0268fc94ed8..39db0a55764 100755 --- a/dev/translation/sanity_check_en_langfiles.php +++ b/dev/translation/sanity_check_en_langfiles.php @@ -25,18 +25,16 @@ $path=dirname(__FILE__).'/'; $web=0; // Test if batch mode -if (substr($sapi_type, 0, 3) == 'cgi') -{ - $web=1; +if (substr($sapi_type, 0, 3) == 'cgi') { + $web=1; } -if ($web) -{ - echo ""; - echo ""; +if ($web) { + echo ""; + echo ""; - echo ""; - echo ""; + echo ""; } echo "If you call this with argument \"unused=true\" it searches for the translation strings that exist in en_US but are never used.\n"; -if ($web) print "
"; +if ($web) { + print "
"; +} echo "IMPORTANT: that can take quite a lot of time (up to 10 minutes), you need to tune the max_execution_time on your php.ini accordingly.\n"; -if ($web) print "
"; +if ($web) { + print "
"; +} @@ -105,8 +107,7 @@ $workdir = $htdocs."langs/en_US/"; $files = scandir($workdir); -if (empty($files)) -{ +if (empty($files)) { echo "Can't scan workdir = ".$workdir; exit; } @@ -115,18 +116,17 @@ $dups=array(); $exludefiles = array('.','..','README'); $files = array_diff($files, $exludefiles); // To force a file: $files=array('myfile.lang'); -if (isset($argv[2])) -{ - $files = array($argv[2]); +if (isset($argv[2])) { + $files = array($argv[2]); } $langstrings_3d = array(); $langstrings_full = array(); -foreach ($files AS $file) { +foreach ($files as $file) { $path_file = pathinfo($file); // we're only interested in .lang files if ($path_file['extension']=='lang') { $content = file($workdir.$file); - foreach ($content AS $line => $row) { + foreach ($content as $line => $row) { // don't want comment lines if (substr($row, 0, 1) !== '#') { // don't want lines without the separator (why should those even be here, anyway...) @@ -142,29 +142,29 @@ foreach ($files AS $file) { } } -foreach ($langstrings_3d AS $filename => $file) -{ - foreach ($file AS $linenum => $value) - { +foreach ($langstrings_3d as $filename => $file) { + foreach ($file as $linenum => $value) { $keys = array_keys($langstrings_full, $value); - if (count($keys)>1) - { - foreach ($keys AS $key) { + if (count($keys)>1) { + foreach ($keys as $key) { $dups[$value][$filename][$linenum] = trim($langstrings_3dtrans[$filename][$linenum]); } } } } -if ($web) print "

"; +if ($web) { + print "

"; +} print "Duplicate strings in lang files in $workdir - ".count($dups)." found\n"; -if ($web) print "

"; +if ($web) { + print ""; +} -if ($web) -{ - echo ''."\n"; - echo "\n"; - echo "\n"; +if ($web) { + echo '
#StringFile and lines
'."\n"; + echo "\n"; + echo "\n"; } $sduplicateinsamefile=''; @@ -173,216 +173,419 @@ $sininstallandadmin=''; $sother=''; $count = 0; -foreach ($dups as $string => $pages) -{ +foreach ($dups as $string => $pages) { $count++; $s=''; // Keyword $string - if ($web) $s.=""; - if ($web) $s.=""; - if ($web) $s.=""; + } + if ($web) { + $s.=""; + } + if ($web) { + $s.=""; - if ($web) $s.=""; + } + if ($web) { + $s.=""; } - if ($web) $s.=""; $s.="\n"; - if ($duplicateinsamefile) $sduplicateinsamefile .= $s; - elseif ($inmain) $sinmainandother .= $s; - elseif ($inadmin) $sininstallandadmin .= $s; - else $sother .= $s; + if ($duplicateinsamefile) { + $sduplicateinsamefile .= $s; + } elseif ($inmain) { + $sinmainandother .= $s; + } elseif ($inadmin) { + $sininstallandadmin .= $s; + } else { + $sother .= $s; + } } -if (! $web) print "\n***** Entries duplicated in same file\n"; +if (! $web) { + print "\n***** Entries duplicated in same file\n"; +} print $sduplicateinsamefile; -if (! $web && empty($sduplicateinsamefile)) print "None\n"; -if (! $web) print "\n"; +if (! $web && empty($sduplicateinsamefile)) { + print "None\n"; +} +if (! $web) { + print "\n"; +} -if (! $web) print "***** Entries in main and another (keep only entry in main)\n"; +if (! $web) { + print "***** Entries in main and another (keep only entry in main)\n"; +} print $sinmainandother; -if (! $web && empty($sinmainandother)) print "None\n"; -if (! $web) print "\n"; +if (! $web && empty($sinmainandother)) { + print "None\n"; +} +if (! $web) { + print "\n"; +} -if (! $web) print "***** Entries in admin and another\n"; +if (! $web) { + print "***** Entries in admin and another\n"; +} print $sininstallandadmin; -if (! $web && empty($sininstallandadmin)) print "None\n"; -if (! $web) print "\n"; +if (! $web && empty($sininstallandadmin)) { + print "None\n"; +} +if (! $web) { + print "\n"; +} -if (! $web) print "***** Other\n"; +if (! $web) { + print "***** Other\n"; +} print $sother; -if (! $web && empty($sother)) print "None\n"; -if (! $web) print "\n"; +if (! $web && empty($sother)) { + print "None\n"; +} +if (! $web) { + print "\n"; +} -if ($web) -{ - echo "\n"; - echo "
#StringFile and lines
"; - if ($web) $s.=$count; - if ($web) $s.=""; + if ($web) { + $s.="
"; + } + if ($web) { + $s.=$count; + } + if ($web) { + $s.=""; + } $s.=$string; - if ($web) $s.=""; - if (! $web) $s.= ' : '; + if ($web) { + $s.=""; + } + if (! $web) { + $s.= ' : '; + } // Loop on each files keyword was found - $duplicateinsamefile=0; + $duplicateinsamefile=0; $inmain=0; - $inadmin=0; - foreach ($pages AS $file => $lines) - { - if ($file == 'main.lang') { $inmain=1; $inadmin=0; } - if ($file == 'admin.lang' && ! $inmain) { $inadmin=1; } + $inadmin=0; + foreach ($pages as $file => $lines) { + if ($file == 'main.lang') { + $inmain=1; $inadmin=0; + } + if ($file == 'admin.lang' && ! $inmain) { + $inadmin=1; + } - $s.=$file." "; + $s.=$file." "; - // Loop on each line keword was found into file. - $listoffilesforthisentry=array(); - foreach ($lines as $line => $translatedvalue) - { - if (! empty($listoffilesforthisentry[$file])) $duplicateinsamefile=1; - $listoffilesforthisentry[$file]=1; + // Loop on each line keword was found into file. + $listoffilesforthisentry=array(); + foreach ($lines as $line => $translatedvalue) { + if (! empty($listoffilesforthisentry[$file])) { + $duplicateinsamefile=1; + } + $listoffilesforthisentry[$file]=1; $s.= "(".$line." - ".htmlentities($translatedvalue).") "; } - if ($web) $s.="
"; + if ($web) { + $s.="
"; + } + } + if ($web) { + $s.="
\n"; +if ($web) { + echo "\n"; + echo "\n"; } // STEP 2 - Search key not used -if ((! empty($_REQUEST['unused']) && $_REQUEST['unused'] == 'true') || (isset($argv[1]) && $argv[1]=='unused=true')) -{ - print "***** Strings in en_US that are never used:\n"; +if ((! empty($_REQUEST['unused']) && $_REQUEST['unused'] == 'true') || (isset($argv[1]) && $argv[1]=='unused=true')) { + print "***** Strings in en_US that are never used:\n"; - $unused=array(); - foreach ($langstrings_dist AS $value => $line) - { - $qualifiedforclean=1; - // Check if we must keep this key to be into file for removal - if (preg_match('/^Module\d+/', $value)) $qualifiedforclean=0; - if (preg_match('/^Permission\d+/', $value)) $qualifiedforclean=0; - if (preg_match('/^PermissionAdvanced\d+/', $value)) $qualifiedforclean=0; - if (preg_match('/^ProfId\d+/', $value)) $qualifiedforclean=0; - if (preg_match('/^Delays_/', $value)) $qualifiedforclean=0; - if (preg_match('/^BarcodeDesc/', $value)) $qualifiedforclean=0; - if (preg_match('/^Extrafield/', $value)) $qualifiedforclean=0; - if (preg_match('/^LocalTax/', $value)) $qualifiedforclean=0; - if (preg_match('/^Country/', $value)) $qualifiedforclean=0; - if (preg_match('/^Civility/', $value)) $qualifiedforclean=0; - if (preg_match('/^Currency/', $value)) $qualifiedforclean=0; - if (preg_match('/^DemandReasonTypeSRC/', $value)) $qualifiedforclean=0; - if (preg_match('/^PaperFormat/', $value)) $qualifiedforclean=0; - if (preg_match('/^Duration/', $value)) $qualifiedforclean=0; - if (preg_match('/^AmountLT/', $value)) $qualifiedforclean=0; - if (preg_match('/^TotalLT/', $value)) $qualifiedforclean=0; - if (preg_match('/^Month/', $value)) $qualifiedforclean=0; - if (preg_match('/^MonthShort/', $value)) $qualifiedforclean=0; - if (preg_match('/^Day\d/', $value)) $qualifiedforclean=0; - if (preg_match('/^Short/', $value)) $qualifiedforclean=0; - if (preg_match('/^ExportDataset_/', $value)) $qualifiedforclean=0; - if (preg_match('/^ImportDataset_/', $value)) $qualifiedforclean=0; - if (preg_match('/^ActionAC_/', $value)) $qualifiedforclean=0; - if (preg_match('/^TypeLocaltax/', $value)) $qualifiedforclean=0; - if (preg_match('/^StatusProspect/', $value)) $qualifiedforclean=0; - if (preg_match('/^PL_/', $value)) $qualifiedforclean=0; - if (preg_match('/^TE_/', $value)) $qualifiedforclean=0; - if (preg_match('/^JuridicalStatus/', $value)) $qualifiedforclean=0; - if (preg_match('/^CalcMode/', $value)) $qualifiedforclean=0; - if (preg_match('/^newLT/', $value)) $qualifiedforclean=0; - if (preg_match('/^LT[0-9]/', $value)) $qualifiedforclean=0; - if (preg_match('/^TypeContact_contrat_/', $value)) $qualifiedforclean=0; - if (preg_match('/^ErrorPriceExpression/', $value)) $qualifiedforclean=0; - if (preg_match('/^Language_/', $value)) $qualifiedforclean=0; - if (preg_match('/^DescADHERENT_/', $value)) $qualifiedforclean=0; - if (preg_match('/^SubmitTranslation/', $value)) $qualifiedforclean=0; - if (preg_match('/^ModuleCompanyCode/', $value)) $qualifiedforclean=0; - if (preg_match('/InDolibarr$/', $value)) $qualifiedforclean=0; - // admin.lang - if (preg_match('/^DAV_ALLOW_PUBLIC_DIR/i', $value)) $qualifiedforclean=0; - if (preg_match('/^DAV_ALLOW_ECM_DIR/i', $value)) $qualifiedforclean=0; - // boxes.lang - if (preg_match('/^BoxTitleLast/', $value)) $qualifiedforclean=0; - if (preg_match('/^BoxTitleLatest/', $value)) $qualifiedforclean=0; - // install.lang - if (preg_match('/^KeepDefaultValues/', $value)) $qualifiedforclean=0; + $unused=array(); + foreach ($langstrings_dist as $value => $line) { + $qualifiedforclean=1; + // Check if we must keep this key to be into file for removal + if (preg_match('/^Module\d+/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^Permission\d+/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^PermissionAdvanced\d+/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^ProfId\d+/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^Delays_/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^BarcodeDesc/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^Extrafield/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^LocalTax/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^Country/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^Civility/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^Currency/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^DemandReasonTypeSRC/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^PaperFormat/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^Duration/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^AmountLT/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^TotalLT/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^Month/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^MonthShort/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^Day\d/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^Short/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^ExportDataset_/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^ImportDataset_/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^ActionAC_/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^TypeLocaltax/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^StatusProspect/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^PL_/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^TE_/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^JuridicalStatus/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^CalcMode/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^newLT/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^LT[0-9]/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^TypeContact_contrat_/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^ErrorPriceExpression/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^Language_/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^DescADHERENT_/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^SubmitTranslation/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^ModuleCompanyCode/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/InDolibarr$/', $value)) { + $qualifiedforclean=0; + } + // admin.lang + if (preg_match('/^DAV_ALLOW_PUBLIC_DIR/i', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^DAV_ALLOW_ECM_DIR/i', $value)) { + $qualifiedforclean=0; + } + // boxes.lang + if (preg_match('/^BoxTitleLast/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^BoxTitleLatest/', $value)) { + $qualifiedforclean=0; + } + // install.lang + if (preg_match('/^KeepDefaultValues/', $value)) { + $qualifiedforclean=0; + } // mail.lang - if (preg_match('/MailingModuleDesc/i', $value)) $qualifiedforclean=0; - // main.lang - if (preg_match('/^Duration/', $value)) $qualifiedforclean=0; - if (preg_match('/^FormatDate/', $value)) $qualifiedforclean=0; - if (preg_match('/^DateFormat/', $value)) $qualifiedforclean=0; - if (preg_match('/^.b$/', $value)) $qualifiedforclean=0; - if (preg_match('/^.*Bytes$/', $value)) $qualifiedforclean=0; - if (preg_match('/^NoteSomeFeaturesAreDisabled/', $value)) $qualifiedforclean=0; - if (preg_match('/^(DoTest|Under|Limits|Cards|CurrentValue|DateLimit|DateAndHour|NbOfLines|NbOfObjects|NbOfReferes|TotalTTCShort|VATs)/', $value)) $qualifiedforclean=0; + if (preg_match('/MailingModuleDesc/i', $value)) { + $qualifiedforclean=0; + } + // main.lang + if (preg_match('/^Duration/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^FormatDate/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^DateFormat/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^.b$/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^.*Bytes$/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^NoteSomeFeaturesAreDisabled/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^(DoTest|Under|Limits|Cards|CurrentValue|DateLimit|DateAndHour|NbOfLines|NbOfObjects|NbOfReferes|TotalTTCShort|VATs)/', $value)) { + $qualifiedforclean=0; + } // modulebuilder - if (preg_match('/^ModuleBuilderDesc/', $value)) $qualifiedforclean=0; - // orders - if (preg_match('/^OrderSource/', $value)) $qualifiedforclean=0; - if (preg_match('/^TypeContact_/', $value)) $qualifiedforclean=0; - // other.lang - if (preg_match('/^Notify_/', $value)) $qualifiedforclean=0; - if (preg_match('/^PredefinedMail/', $value)) $qualifiedforclean=0; - if (preg_match('/^DemoCompany/', $value)) $qualifiedforclean=0; - if (preg_match('/^WeightUnit/', $value)) $qualifiedforclean=0; - if (preg_match('/^LengthUnit/', $value)) $qualifiedforclean=0; - if (preg_match('/^SurfaceUnit/', $value)) $qualifiedforclean=0; - if (preg_match('/^VolumeUnit/', $value)) $qualifiedforclean=0; - if (preg_match('/^SizeUnit/', $value)) $qualifiedforclean=0; - if (preg_match('/^EMailText/', $value)) $qualifiedforclean=0; - if (preg_match('/ById$/', $value)) $qualifiedforclean=0; - if (preg_match('/ByLogin$/', $value)) $qualifiedforclean=0; - // printing - if (preg_match('/PrintingDriverDesc$/', $value)) $qualifiedforclean=0; - if (preg_match('/PrintTestDesc$/', $value)) $qualifiedforclean=0; - // products - if (preg_match('/GlobalVariableUpdaterType$/', $value)) $qualifiedforclean=0; - if (preg_match('/GlobalVariableUpdaterHelp$/', $value)) $qualifiedforclean=0; - if (preg_match('/OppStatus/', $value)) $qualifiedforclean=0; - if (preg_match('/AvailabilityType/', $value)) $qualifiedforclean=0; - if (preg_match('/CardProduct/', $value)) $qualifiedforclean=0; + if (preg_match('/^ModuleBuilderDesc/', $value)) { + $qualifiedforclean=0; + } + // orders + if (preg_match('/^OrderSource/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^TypeContact_/', $value)) { + $qualifiedforclean=0; + } + // other.lang + if (preg_match('/^Notify_/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^PredefinedMail/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^DemoCompany/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^WeightUnit/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^LengthUnit/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^SurfaceUnit/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^VolumeUnit/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^SizeUnit/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/^EMailText/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/ById$/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/ByLogin$/', $value)) { + $qualifiedforclean=0; + } + // printing + if (preg_match('/PrintingDriverDesc$/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/PrintTestDesc$/', $value)) { + $qualifiedforclean=0; + } + // products + if (preg_match('/GlobalVariableUpdaterType$/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/GlobalVariableUpdaterHelp$/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/OppStatus/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/AvailabilityType/', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/CardProduct/', $value)) { + $qualifiedforclean=0; + } - if (preg_match('/sms/i', $value)) $qualifiedforclean=0; - if (preg_match('/TF_/i', $value)) $qualifiedforclean=0; - if (preg_match('/WithBankUsing/i', $value)) $qualifiedforclean=0; - if (preg_match('/descWORKFLOW_/i', $value)) $qualifiedforclean=0; + if (preg_match('/sms/i', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/TF_/i', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/WithBankUsing/i', $value)) { + $qualifiedforclean=0; + } + if (preg_match('/descWORKFLOW_/i', $value)) { + $qualifiedforclean=0; + } - if (! $qualifiedforclean) - { - continue; - } + if (! $qualifiedforclean) { + continue; + } - //$search = '\'trans("'.$value.'")\''; - $search = '-e "\''.$value.'\'" -e \'"'.$value.'"\' -e "('.$value.')" -e "('.$value.',"'; + //$search = '\'trans("'.$value.'")\''; + $search = '-e "\''.$value.'\'" -e \'"'.$value.'"\' -e "('.$value.')" -e "('.$value.',"'; $string = 'grep -R -m 1 -F --exclude=includes/* --include=*.php '.$search.' '.$htdocs.'* '.$scripts.'*'; //print $string."
\n"; exec($string, $output); if (empty($output)) { - $unused[$value] = $line; - echo $line; // $trad contains the \n - } - else { - unset($output); - //print 'X'.$output.'Y'; + $unused[$value] = $line; + echo $line; // $trad contains the \n + } else { + unset($output); + //print 'X'.$output.'Y'; } } - if (empty($unused)) print "No string not used found.\n"; - else { - $filetosave='/tmp/'.($argv[2]?$argv[2]:"").'notused.lang'; - print "Strings in en_US that are never used are saved into file ".$filetosave.":\n"; - file_put_contents($filetosave, implode("", $unused)); - print "To remove from original file, run command :\n"; - if (($argv[2]?$argv[2]:"")) print 'cd htdocs/langs/en_US; mv '.($argv[2]?$argv[2]:"")." ".($argv[2]?$argv[2]:"").".tmp; "; - print "diff ".($argv[2]?$argv[2]:"").".tmp ".$filetosave." | grep \< | cut -b 3- > ".($argv[2]?$argv[2]:""); - if (($argv[2]?$argv[2]:"")) print "; rm ".($argv[2]?$argv[2]:"").".tmp;\n"; + if (empty($unused)) { + print "No string not used found.\n"; + } else { + $filetosave='/tmp/'.($argv[2]?$argv[2]:"").'notused.lang'; + print "Strings in en_US that are never used are saved into file ".$filetosave.":\n"; + file_put_contents($filetosave, implode("", $unused)); + print "To remove from original file, run command :\n"; + if (($argv[2]?$argv[2]:"")) { + print 'cd htdocs/langs/en_US; mv '.($argv[2]?$argv[2]:"")." ".($argv[2]?$argv[2]:"").".tmp; "; + } + print "diff ".($argv[2]?$argv[2]:"").".tmp ".$filetosave." | grep \< | cut -b 3- > ".($argv[2]?$argv[2]:""); + if (($argv[2]?$argv[2]:"")) { + print "; rm ".($argv[2]?$argv[2]:"").".tmp;\n"; + } } } echo "\n"; -if ($web) -{ - echo "\n"; - echo "\n"; +if ($web) { + echo "\n"; + echo "\n"; } exit; diff --git a/dev/translation/strip_language_file.php b/dev/translation/strip_language_file.php index adc5a706d06..f3287db6128 100755 --- a/dev/translation/strip_language_file.php +++ b/dev/translation/strip_language_file.php @@ -63,8 +63,7 @@ $lSecondary = isset($argv[2])?$argv[2]:''; $lEnglish = 'en_US'; $filesToProcess = isset($argv[3])?$argv[3]:''; -if (empty($lPrimary) || empty($lSecondary) || empty($filesToProcess)) -{ +if (empty($lPrimary) || empty($lSecondary) || empty($filesToProcess)) { $rc = 1; $msg = '***** Script to clean language files *****'."\n"; $msg.= 'Usage: ./dev/translation/strip_language_file.php xx_XX xx_YY [file.lang|all]'."\n"; @@ -77,8 +76,7 @@ $aSecondary = array(); $aEnglish = array(); // Define array $filesToProcess -if ($filesToProcess == 'all') -{ +if ($filesToProcess == 'all') { $dir = new DirectoryIterator('htdocs/langs/'.$lPrimary); while ($dir->valid()) { if (!$dir->isDot() && $dir->isFile() && ! preg_match('/^\./', $dir->getFilename())) { @@ -87,15 +85,15 @@ if ($filesToProcess == 'all') $dir->next(); } $filesToProcess=$files; +} else { + $filesToProcess=explode(',', $filesToProcess); } -else $filesToProcess=explode(',', $filesToProcess); // Arguments should be OK here. // Loop on each file -foreach ($filesToProcess as $fileToProcess) -{ +foreach ($filesToProcess as $fileToProcess) { $lPrimaryFile = 'htdocs/langs/'.$lPrimary.'/'.$fileToProcess; $lSecondaryFile = 'htdocs/langs/'.$lSecondary.'/'.$fileToProcess; $lEnglishFile = 'htdocs/langs/'.$lEnglish.'/'.$fileToProcess; @@ -103,21 +101,21 @@ foreach ($filesToProcess as $fileToProcess) print "---- Process language file ".$lSecondaryFile."\n"; - if ( ! is_readable($lPrimaryFile) ) { + if (! is_readable($lPrimaryFile)) { $rc = 2; $msg = "Cannot read primary language file $lPrimaryFile."; print $msg . " (rc=$rc).\n"; exit($rc); } - if ( ! is_readable($lSecondaryFile) ) { + if (! is_readable($lSecondaryFile)) { $rc = 3; $msg = "Cannot read secondary language file $lSecondaryFile. We discard this file."; print $msg . "\n"; continue; } - if ( ! is_readable($lEnglishFile) ) { + if (! is_readable($lEnglishFile)) { $rc = 3; $msg = "Cannot read english language file $lEnglishFile. We discard this file."; print $msg . "\n"; @@ -126,25 +124,23 @@ foreach ($filesToProcess as $fileToProcess) // Start reading and parsing Secondary - if ( $handle = fopen($lSecondaryFile, 'r') ) - { + if ($handle = fopen($lSecondaryFile, 'r')) { print "Read Secondary File $lSecondaryFile:\n"; $cnt = 0; - while (($line = fgets($handle)) !== false) - { + while (($line = fgets($handle)) !== false) { $cnt++; // strip comments - if ( preg_match("/^\w*#/", $line) ) { + if (preg_match("/^\w*#/", $line)) { continue; } // strip empty lines - if ( preg_match("/^\w*$/", $line) ) { + if (preg_match("/^\w*$/", $line)) { continue; } $a = mb_split('=', trim($line), 2); - if ( count($a) != 2 ) { + if (count($a) != 2) { print "ERROR in file $lSecondaryFile, line $cnt: " . trim($line) . "\n"; continue; } @@ -152,29 +148,27 @@ foreach ($filesToProcess as $fileToProcess) list($key, $value) = $a; // key is redundant - if ( array_key_exists($key, $aSecondary) ) { + if (array_key_exists($key, $aSecondary)) { print "Key $key is redundant in file $lSecondaryFile (line: $cnt).\n"; continue; } // String has no value - if ( $value == '' ) { + if ($value == '') { print "Key $key has no value in file $lSecondaryFile (line: $cnt).\n"; continue; } $aSecondary[$key] = trim($value); } - if ( ! feof($handle) ) - { + if (! feof($handle)) { $rc = 5; $msg = "Unexpected fgets() fail"; print $msg . " (rc=$rc).\n"; exit($rc); } fclose($handle); - } - else { + } else { $rc = 6; $msg = "Cannot open file $lSecondaryFile"; print $msg . " (rc=$rc).\n"; @@ -184,25 +178,23 @@ foreach ($filesToProcess as $fileToProcess) // Start reading and parsing English - if ( $handle = fopen($lEnglishFile, 'r') ) - { + if ($handle = fopen($lEnglishFile, 'r')) { print "Read English File $lEnglishFile:\n"; $cnt = 0; - while (($line = fgets($handle)) !== false) - { + while (($line = fgets($handle)) !== false) { $cnt++; // strip comments - if ( preg_match("/^\w*#/", $line) ) { + if (preg_match("/^\w*#/", $line)) { continue; } // strip empty lines - if ( preg_match("/^\w*$/", $line) ) { + if (preg_match("/^\w*$/", $line)) { continue; } $a = mb_split('=', trim($line), 2); - if ( count($a) != 2 ) { + if (count($a) != 2) { print "ERROR in file $lEnglishFile, line $cnt: " . trim($line) . "\n"; continue; } @@ -210,29 +202,27 @@ foreach ($filesToProcess as $fileToProcess) list($key, $value) = $a; // key is redundant - if ( array_key_exists($key, $aEnglish) ) { + if (array_key_exists($key, $aEnglish)) { print "Key $key is redundant in file $lEnglishFile (line: $cnt).\n"; continue; } // String has no value - if ( $value == '' ) { + if ($value == '') { print "Key $key has no value in file $lEnglishFile (line: $cnt).\n"; continue; } $aEnglish[$key] = trim($value); } - if ( ! feof($handle) ) - { + if (! feof($handle)) { $rc = 5; $msg = "Unexpected fgets() fail"; print $msg . " (rc=$rc).\n"; exit($rc); } fclose($handle); - } - else { + } else { $rc = 6; $msg = "Cannot open file $lEnglishFile"; print $msg . " (rc=$rc).\n"; @@ -246,10 +236,8 @@ foreach ($filesToProcess as $fileToProcess) $arrayofkeytoalwayskeep=array('DIRECTION','FONTFORPDF','FONTSIZEFORPDF','SeparatorDecimal','SeparatorThousand'); - if ( $handle = fopen($lPrimaryFile, 'r') ) - { - if ( ! $oh = fopen($output, 'w') ) - { + if ($handle = fopen($lPrimaryFile, 'r')) { + if (! $oh = fopen($output, 'w')) { print "ERROR in writing to file ".$output."\n"; exit; } @@ -259,21 +247,20 @@ foreach ($filesToProcess as $fileToProcess) fwrite($oh, "# Dolibarr language file - Source file is en_US - ".(preg_replace('/\.lang$/', '', $fileToProcess))."\n"); $cnt = 0; - while (($line = fgets($handle)) !== false) - { + while (($line = fgets($handle)) !== false) { $cnt++; // strip comments - if ( preg_match("/^\w*#/", $line) ) { + if (preg_match("/^\w*#/", $line)) { continue; } // strip empty lines - if ( preg_match("/^\w*$/", $line) ) { + if (preg_match("/^\w*$/", $line)) { continue; } $a = mb_split('=', trim($line), 2); - if ( count($a) != 2 ) { + if (count($a) != 2) { print "ERROR in file $lPrimaryFile, line $cnt: " . trim($line) . "\n"; continue; } @@ -281,17 +268,16 @@ foreach ($filesToProcess as $fileToProcess) list($key, $value) = $a; // key is redundant - if ( array_key_exists($key, $aPrimary) ) { + if (array_key_exists($key, $aPrimary)) { print "Key $key is redundant in file $lPrimaryFile (line: $cnt) - Already found into ".$fileFirstFound[$key]." (line: ".$lineFirstFound[$key].").\n"; continue; - } - else { + } else { $fileFirstFound[$key] = $fileToProcess; $lineFirstFound[$key] = $cnt; } // String has no value - if ( $value == '' ) { + if ($value == '') { print "Key $key has no value in file $lPrimaryFile (line: $cnt).\n"; continue; } @@ -305,28 +291,23 @@ foreach ($filesToProcess as $fileToProcess) //print "Found primary key = ".$key."\n"; // Key not in other file - if (in_array($key, $arrayofkeytoalwayskeep) || preg_match('/^FormatDate/', $key) || preg_match('/^FormatHour/', $key)) - { + if (in_array($key, $arrayofkeytoalwayskeep) || preg_match('/^FormatDate/', $key) || preg_match('/^FormatHour/', $key)) { //print "Key $key is a key we always want to see into secondary file (line: $cnt).\n"; - } - elseif ( ! array_key_exists($key, $aSecondary)) - { + } elseif (! array_key_exists($key, $aSecondary)) { //print "Key $key does NOT exist in secondary language (line: $cnt).\n"; continue; } // String exists in both files and value into alternative language differs from main language but also from english files - if ( - (! empty($aSecondary[$key]) && $aSecondary[$key] != $aPrimary[$key] - && ! empty($aEnglish[$key]) && $aSecondary[$key] != $aEnglish[$key]) + if ((! empty($aSecondary[$key]) && $aSecondary[$key] != $aPrimary[$key] + && ! empty($aEnglish[$key]) && $aSecondary[$key] != $aEnglish[$key]) || in_array($key, $arrayofkeytoalwayskeep) || preg_match('/^FormatDate/', $key) || preg_match('/^FormatHour/', $key) - ) - { + ) { //print "Key $key differs (aSecondary=".$aSecondary[$key].", aPrimary=".$aPrimary[$key].", aEnglish=".$aEnglish[$key].") so we add it into new secondary language (line: $cnt).\n"; fwrite($oh, $key."=".(empty($aSecondary[$key])?$aPrimary[$key]:$aSecondary[$key])."\n"); } } - if ( ! feof($handle) ) { + if (! feof($handle)) { $rc = 7; $msg = "Unexpected fgets() fail"; print $msg . " (rc=$rc).\n"; @@ -334,8 +315,7 @@ foreach ($filesToProcess as $fileToProcess) } fclose($oh); fclose($handle); - } - else { + } else { $rc = 8; $msg = "Cannot open file $lPrimaryFile"; print $msg . " (rc=$rc).\n"; diff --git a/htdocs/accountancy/admin/account.php b/htdocs/accountancy/admin/account.php index d84f546fb01..faf55427786 100644 --- a/htdocs/accountancy/admin/account.php +++ b/htdocs/accountancy/admin/account.php @@ -147,6 +147,7 @@ if (empty($reshook)) { // and pass CCCNNNNN + (num of company * 100 000 000) as offset to the run_sql as a new parameter to say to update sql on the fly to add offset to rowid and account_parent value. // This is to be sure there is no conflict for each chart of account, whatever is country, whatever is company when multicompany is used. $tmp = file_get_contents($sqlfile); + $reg = array(); if (preg_match('/-- ADD (\d+) to rowid/ims', $tmp, $reg)) { $offsetforchartofaccount += $reg[1]; } @@ -342,7 +343,7 @@ if ($resql) { // Box to select active chart of account print $langs->trans("Selectchartofaccounts")." : "; - print ''; $sql = "SELECT a.rowid, a.pcg_version, a.label, a.active, c.code as country_code"; $sql .= " FROM ".MAIN_DB_PREFIX."accounting_system as a"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON a.fk_country = c.rowid AND c.active = 1"; @@ -353,6 +354,7 @@ if ($resql) { if ($resqlchart) { $numbis = $db->num_rows($resqlchart); $i = 0; + print ''; while ($i < $numbis) { $obj = $db->fetch_object($resqlchart); diff --git a/htdocs/accountancy/admin/subaccount.php b/htdocs/accountancy/admin/subaccount.php index 4b7d4d029b5..341fddf113c 100644 --- a/htdocs/accountancy/admin/subaccount.php +++ b/htdocs/accountancy/admin/subaccount.php @@ -118,9 +118,10 @@ if (empty($reshook)) { $form = new Form($db); +$help_url = ''; $title = $langs->trans('ChartOfIndividualAccountsOfSubsidiaryLedger'); -llxHeader('', $title); +llxHeader('', $title, $help_url); // Customer $sql = "SELECT sa.rowid, sa.nom as label, sa.code_compta as subaccount, '1' as type, sa.entity"; @@ -314,7 +315,7 @@ if ($resql) { print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, '', '', $limit, 0, 0, 1); - print '
'.$langs->trans("WarningCreateSubAccounts").'
'; + print '
'.$langs->trans("WarningCreateSubAccounts").'
'; $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php b/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php index a2192d5ea60..fa5302919d5 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php @@ -128,7 +128,7 @@ $form = new Form($db); $formaccounting = new FormAccounting($db); $title = $object->name." - ".$langs->trans('TabLetteringCustomer'); -$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; +$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas|DE:Modul_Geschäftspartner'; llxHeader('', $title, $help_url); $head = societe_prepare_head($object); diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php b/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php index f8167846aff..e31479f10cd 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php @@ -127,7 +127,7 @@ $form = new Form($db); $formaccounting = new FormAccounting($db); $title = $object->name." - ".$langs->trans('TabLetteringSupplier'); -$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; +$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas|DE:Modul_Geschäftspartner'; llxHeader('', $title, $help_url); $head = societe_prepare_head($object); diff --git a/htdocs/accountancy/class/accountancycategory.class.php b/htdocs/accountancy/class/accountancycategory.class.php index 95d88c80c87..292fb55a29f 100644 --- a/htdocs/accountancy/class/accountancycategory.class.php +++ b/htdocs/accountancy/class/accountancycategory.class.php @@ -261,7 +261,7 @@ class AccountancyCategory // extends CommonObject $sql .= " t.active"; $sql .= " FROM ".MAIN_DB_PREFIX."c_accounting_category as t"; if ($id) { - $sql .= " WHERE t.rowid = ".$id; + $sql .= " WHERE t.rowid = ".((int) $id); } else { $sql .= " WHERE t.entity IN (".getEntity('c_accounting_category').")"; // Dont't use entity if you use rowid if ($code) { @@ -354,7 +354,7 @@ class AccountancyCategory // extends CommonObject $sql .= " position=".(isset($this->position) ? $this->position : "null").","; $sql .= " fk_country=".(isset($this->fk_country) ? $this->fk_country : "null").","; $sql .= " active=".(isset($this->active) ? $this->active : "null").""; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); @@ -392,7 +392,7 @@ class AccountancyCategory // extends CommonObject $error = 0; $sql = "DELETE FROM ".MAIN_DB_PREFIX."c_accounting_category"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); diff --git a/htdocs/accountancy/class/accountancyexport.class.php b/htdocs/accountancy/class/accountancyexport.class.php index 4467844b04e..ac8c3db644b 100644 --- a/htdocs/accountancy/class/accountancyexport.class.php +++ b/htdocs/accountancy/class/accountancyexport.class.php @@ -542,17 +542,17 @@ class AccountancyExport // Credit invoice - invert sens /* - if ($data->montant < 0) { - if ($data->sens == 'C') { - $Tab['sens'] = 'D'; - } else { - $Tab['sens'] = 'C'; - } - $Tab['signe_montant'] = '-'; - } else { - $Tab['sens'] = $data->sens; // C or D - $Tab['signe_montant'] = '+'; - }*/ + if ($data->montant < 0) { + if ($data->sens == 'C') { + $Tab['sens'] = 'D'; + } else { + $Tab['sens'] = 'C'; + } + $Tab['signe_montant'] = '-'; + } else { + $Tab['sens'] = $data->sens; // C or D + $Tab['signe_montant'] = '+'; + }*/ $Tab['sens'] = $data->sens; // C or D $Tab['signe_montant'] = '+'; @@ -856,8 +856,8 @@ class AccountancyExport foreach ($objectLines as $line) { if ($line->debit == 0 && $line->credit == 0) { - //unset($array[$line]); - } else { + //unset($array[$line]); + } else { $date_creation = dol_print_date($line->date_creation, '%Y%m%d'); $date_document = dol_print_date($line->doc_date, '%Y%m%d'); $date_lettering = dol_print_date($line->date_lettering, '%Y%m%d'); diff --git a/htdocs/accountancy/class/accountingaccount.class.php b/htdocs/accountancy/class/accountingaccount.class.php index d5fad9b8f60..a7d89c45294 100644 --- a/htdocs/accountancy/class/accountingaccount.class.php +++ b/htdocs/accountancy/class/accountingaccount.class.php @@ -414,7 +414,7 @@ class AccountingAccount extends CommonObject if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."accounting_account"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::delete sql=".$sql); $resql = $this->db->query($sql); @@ -553,7 +553,7 @@ class AccountingAccount extends CommonObject { $sql = 'SELECT a.rowid, a.datec, a.fk_user_author, a.fk_user_modif, a.tms'; $sql .= ' FROM '.MAIN_DB_PREFIX.'accounting_account as a'; - $sql .= ' WHERE a.rowid = '.$id; + $sql .= ' WHERE a.rowid = '.((int) $id); dol_syslog(get_class($this).'::info sql='.$sql); $result = $this->db->query($sql); diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 27a84270e95..7286e954d0e 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -729,7 +729,7 @@ class BookKeeping extends CommonObject if (null !== $ref) { $sql .= " AND t.ref = '".$this->db->escape($ref)."'"; } else { - $sql .= ' AND t.rowid = '.$id; + $sql .= ' AND t.rowid = '.((int) $id); } $resql = $this->db->query($sql); @@ -1262,7 +1262,7 @@ class BookKeeping extends CommonObject $sql .= ' code_journal = '.(isset($this->code_journal) ? "'".$this->db->escape($this->code_journal)."'" : "null").','; $sql .= ' journal_label = '.(isset($this->journal_label) ? "'".$this->db->escape($this->journal_label)."'" : "null").','; $sql .= ' piece_num = '.(isset($this->piece_num) ? $this->piece_num : "null"); - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); $this->db->begin(); @@ -1359,7 +1359,7 @@ class BookKeeping extends CommonObject if (!$error) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.$mode; - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); $resql = $this->db->query($sql); if (!$resql) { diff --git a/htdocs/accountancy/customer/card.php b/htdocs/accountancy/customer/card.php index 9807922c43f..1209576ddba 100644 --- a/htdocs/accountancy/customer/card.php +++ b/htdocs/accountancy/customer/card.php @@ -55,7 +55,7 @@ if ($action == 'ventil' && $user->rights->accounting->bind->write) { $sql = " UPDATE ".MAIN_DB_PREFIX."facturedet"; $sql .= " SET fk_code_ventilation = ".$codeventil; - $sql .= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".((int) $id); $resql = $db->query($sql); if (!$resql) { @@ -99,7 +99,7 @@ if (!empty($id)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = l.fk_product"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON l.fk_code_ventilation = aa.rowid"; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = l.fk_facture"; - $sql .= " WHERE f.fk_statut > 0 AND l.rowid = ".$id; + $sql .= " WHERE f.fk_statut > 0 AND l.rowid = ".((int) $id); $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy dol_syslog("/accounting/customer/card.php sql=".$sql, LOG_DEBUG); diff --git a/htdocs/accountancy/expensereport/card.php b/htdocs/accountancy/expensereport/card.php index d68326ad68e..f997f666e6e 100644 --- a/htdocs/accountancy/expensereport/card.php +++ b/htdocs/accountancy/expensereport/card.php @@ -59,7 +59,7 @@ if ($action == 'ventil' && $user->rights->accounting->bind->write) { $sql = " UPDATE ".MAIN_DB_PREFIX."expensereport_det"; $sql .= " SET fk_code_ventilation = ".$codeventil; - $sql .= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".((int) $id); $resql = $db->query($sql); if (!$resql) { @@ -101,7 +101,7 @@ if (!empty($id)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_fees as f ON f.id = erd.fk_c_type_fees"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON erd.fk_code_ventilation = aa.rowid"; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."expensereport as er ON er.rowid = erd.fk_expensereport"; - $sql .= " WHERE er.fk_statut > 0 AND erd.rowid = ".$id; + $sql .= " WHERE er.fk_statut > 0 AND erd.rowid = ".((int) $id); $sql .= " AND er.entity IN (".getEntity('expensereport', 0).")"; // We don't share object for accountancy dol_syslog("/accounting/expensereport/card.php sql=".$sql, LOG_DEBUG); diff --git a/htdocs/accountancy/index.php b/htdocs/accountancy/index.php index 5b2f807fcd7..242fc71d80c 100644 --- a/htdocs/accountancy/index.php +++ b/htdocs/accountancy/index.php @@ -1,7 +1,7 @@ * Copyright (C) 2016-2019 Alexandre Spangaro - * Copyright (C) 2019 Frédéric France + * Copyright (C) 2019-2021 Frédéric France * * 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 @@ -220,7 +220,7 @@ if ($conf->accounting->enabled) { /* * Show boxes */ - $boxlist .= '
'; + $boxlist = '
'; $boxlist .= '
'; diff --git a/htdocs/accountancy/journal/bankjournal.php b/htdocs/accountancy/journal/bankjournal.php index 71839ecf08a..b79b8433c03 100644 --- a/htdocs/accountancy/journal/bankjournal.php +++ b/htdocs/accountancy/journal/bankjournal.php @@ -10,6 +10,7 @@ * Copyright (C) 2017-2020 Frédéric France * Copyright (C) 2018 Ferran Marcet * Copyright (C) 2018 Eric Seigne + * Copyright (C) 2021 Gauthier VERDOL * * 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 @@ -945,7 +946,7 @@ if (empty($action) || $action == 'view') { $vatstatic = new Tva($db); $donationstatic = new Don($db); $loanstatic = new Loan($db); - $salarystatic = new PaymentSalary($db); + $salarystatic = new Salary($db); $variousstatic = new PaymentVarious($db); llxHeader('', $langs->trans("FinanceJournal")); diff --git a/htdocs/accountancy/supplier/card.php b/htdocs/accountancy/supplier/card.php index 25a3fc04ca4..0d86b928a26 100644 --- a/htdocs/accountancy/supplier/card.php +++ b/htdocs/accountancy/supplier/card.php @@ -59,7 +59,7 @@ if ($action == 'ventil' && $user->rights->accounting->bind->write) { $sql = " UPDATE ".MAIN_DB_PREFIX."facture_fourn_det"; $sql .= " SET fk_code_ventilation = ".$codeventil; - $sql .= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".((int) $id); $resql = $db->query($sql); if (!$resql) { @@ -101,7 +101,7 @@ if (!empty($id)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = l.fk_product"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON l.fk_code_ventilation = aa.rowid"; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."facture_fourn as f ON f.rowid = l.fk_facture_fourn "; - $sql .= " WHERE f.fk_statut > 0 AND l.rowid = ".$id; + $sql .= " WHERE f.fk_statut > 0 AND l.rowid = ".((int) $id); $sql .= " AND f.entity IN (".getEntity('facture_fourn', 0).")"; // We don't share object for accountancy dol_syslog("/accounting/supplier/card.php sql=".$sql, LOG_DEBUG); diff --git a/htdocs/adherents/admin/adherent.php b/htdocs/adherents/admin/adherent.php index fef3bd53177..092d9b0de38 100644 --- a/htdocs/adherents/admin/adherent.php +++ b/htdocs/adherents/admin/adherent.php @@ -37,7 +37,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "members")); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $choices = array('yesno', 'texte', 'chaine'); @@ -126,17 +128,24 @@ if ($action == 'update' || $action == 'add') { $constname = GETPOST('constname', 'alpha'); $constvalue = (GETPOST('constvalue_'.$constname) ? GETPOST('constvalue_'.$constname) : GETPOST('constvalue')); - if (($constname == 'ADHERENT_CARD_TYPE' || $constname == 'ADHERENT_ETIQUETTE_TYPE' || $constname == 'ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS') && $constvalue == -1) $constvalue = ''; + if (($constname == 'ADHERENT_CARD_TYPE' || $constname == 'ADHERENT_ETIQUETTE_TYPE' || $constname == 'ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS') && $constvalue == -1) { + $constvalue = ''; + } if ($constname == 'ADHERENT_LOGIN_NOT_REQUIRED') { // Invert choice - if ($constvalue) $constvalue = 0; - else $constvalue = 1; + if ($constvalue) { + $constvalue = 0; + } else { + $constvalue = 1; + } } $consttype = GETPOST('consttype', 'alpha'); $constnote = GETPOST('constnote'); $res = dolibarr_set_const($db, $constname, $constvalue, $choices[$consttype], 0, $constnote, $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); @@ -169,7 +178,7 @@ if ($action == 'unset') { $form = new Form($db); -$help_url = 'EN:Module_Foundations|FR:Module_Adhérents|ES:Módulo_Miembros'; +$help_url = 'EN:Module_Foundations|FR:Module_Adhérents|ES:Módulo_Miembros|DE:Modul_Mitglieder'; llxHeader('', $langs->trans("MembersSetup"), $help_url); @@ -211,9 +220,15 @@ print "\n"; // Insert subscription into bank account print ''.$langs->trans("MoreActionsOnSubscription").''; $arraychoices = array('0'=>$langs->trans("None")); -if (!empty($conf->banque->enabled)) $arraychoices['bankdirect'] = $langs->trans("MoreActionBankDirect"); -if (!empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) $arraychoices['invoiceonly'] = $langs->trans("MoreActionInvoiceOnly"); -if (!empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) $arraychoices['bankviainvoice'] = $langs->trans("MoreActionBankViaInvoice"); +if (!empty($conf->banque->enabled)) { + $arraychoices['bankdirect'] = $langs->trans("MoreActionBankDirect"); +} +if (!empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) { + $arraychoices['invoiceonly'] = $langs->trans("MoreActionInvoiceOnly"); +} +if (!empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) { + $arraychoices['bankviainvoice'] = $langs->trans("MoreActionBankViaInvoice"); +} print ''; print $form->selectarray('ADHERENT_BANK_USE', $arraychoices, $conf->global->ADHERENT_BANK_USE, 0); if ($conf->global->ADHERENT_BANK_USE == 'bankdirect' || $conf->global->ADHERENT_BANK_USE == 'bankviainvoice') { @@ -349,7 +364,9 @@ foreach ($dirmodels as $reldir) { $module = new $classname($db); $modulequalified = 1; - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) { + $modulequalified = 0; + } if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) { $modulequalified = 0; } @@ -404,8 +421,7 @@ foreach ($dirmodels as $reldir) { // Preview print ''; - if ($module->type == 'pdf') - { + if ($module->type == 'pdf') { print ''.img_object($langs->trans("Preview"), 'contract').''; } else { print img_object($langs->trans("PreviewNotAvailable"), 'generic'); diff --git a/htdocs/adherents/admin/adherent_emails.php b/htdocs/adherents/admin/adherent_emails.php index 21ce5037ef5..e1867285930 100644 --- a/htdocs/adherents/admin/adherent_emails.php +++ b/htdocs/adherents/admin/adherent_emails.php @@ -36,7 +36,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "members")); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $oldtypetonewone = array('texte'=>'text', 'chaine'=>'string'); // old type to new ones @@ -92,7 +94,9 @@ if ($action == 'update' || $action == 'add') { $res = dolibarr_set_const($db, $constname, $constvalue, $typetouse, 0, $constnote, $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); diff --git a/htdocs/adherents/admin/adherent_extrafields.php b/htdocs/adherents/admin/adherent_extrafields.php index a391770fdd5..0465b7eee4f 100644 --- a/htdocs/adherents/admin/adherent_extrafields.php +++ b/htdocs/adherents/admin/adherent_extrafields.php @@ -37,13 +37,17 @@ $form = new Form($db); // List of supported format $tmptype2label = ExtraFields::$type2label; $type2label = array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); +foreach ($tmptype2label as $key => $val) { + $type2label[$key] = $langs->transnoentitiesnoconv($val); +} $action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'adherent'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* diff --git a/htdocs/adherents/admin/adherent_type_extrafields.php b/htdocs/adherents/admin/adherent_type_extrafields.php index 92b5ed990e3..c33ee5a4739 100644 --- a/htdocs/adherents/admin/adherent_type_extrafields.php +++ b/htdocs/adherents/admin/adherent_type_extrafields.php @@ -40,13 +40,17 @@ $form = new Form($db); // List of supported format $tmptype2label = ExtraFields::$type2label; $type2label = array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); +foreach ($tmptype2label as $key => $val) { + $type2label[$key] = $langs->transnoentitiesnoconv($val); +} $action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'adherent_type'; //Must be the $table_element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* diff --git a/htdocs/adherents/admin/website.php b/htdocs/adherents/admin/website.php index 56d6ec996e4..d13b4a27c43 100644 --- a/htdocs/adherents/admin/website.php +++ b/htdocs/adherents/admin/website.php @@ -35,7 +35,9 @@ $langs->loadLangs(array("admin", "members")); $action = GETPOST('action', 'aZ09'); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -43,8 +45,11 @@ if (!$user->admin) accessforbidden(); */ if ($action == 'setMEMBER_ENABLE_PUBLIC') { - if (GETPOST('value')) dolibarr_set_const($db, 'MEMBER_ENABLE_PUBLIC', 1, 'chaine', 0, '', $conf->entity); - else dolibarr_set_const($db, 'MEMBER_ENABLE_PUBLIC', 0, 'chaine', 0, '', $conf->entity); + if (GETPOST('value')) { + dolibarr_set_const($db, 'MEMBER_ENABLE_PUBLIC', 1, 'chaine', 0, '', $conf->entity); + } else { + dolibarr_set_const($db, 'MEMBER_ENABLE_PUBLIC', 0, 'chaine', 0, '', $conf->entity); + } } if ($action == 'update') { @@ -58,14 +63,17 @@ if ($action == 'update') { $res = dolibarr_set_const($db, "MEMBER_NEWFORM_AMOUNT", $amount, 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "MEMBER_NEWFORM_EDITAMOUNT", $editamount, 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "MEMBER_NEWFORM_PAYONLINE", $payonline, 'chaine', 0, '', $conf->entity); - if ($forcetype < 0) $res = dolibarr_del_const($db, "MEMBER_NEWFORM_FORCETYPE", $conf->entity); - else { + if ($forcetype < 0) { + $res = dolibarr_del_const($db, "MEMBER_NEWFORM_FORCETYPE", $conf->entity); + } else { $res = dolibarr_set_const($db, "MEMBER_NEWFORM_FORCETYPE", $forcetype, 'chaine', 0, '', $conf->entity); } - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } - if (!$error) { + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); @@ -195,9 +203,15 @@ if (!empty($conf->global->MEMBER_ENABLE_PUBLIC)) { $listofval = array(); $listofval['-1'] = $langs->trans('No'); $listofval['all'] = $langs->trans('Yes').' ('.$langs->trans("VisitorCanChooseItsPaymentMode").')'; - if (!empty($conf->paybox->enabled)) $listofval['paybox'] = 'Paybox'; - if (!empty($conf->paypal->enabled)) $listofval['paypal'] = 'PayPal'; - if (!empty($conf->stripe->enabled)) $listofval['stripe'] = 'Stripe'; + if (!empty($conf->paybox->enabled)) { + $listofval['paybox'] = 'Paybox'; + } + if (!empty($conf->paypal->enabled)) { + $listofval['paypal'] = 'PayPal'; + } + if (!empty($conf->stripe->enabled)) { + $listofval['stripe'] = 'Stripe'; + } print $form->selectarray("MEMBER_NEWFORM_PAYONLINE", $listofval, (!empty($conf->global->MEMBER_NEWFORM_PAYONLINE) ? $conf->global->MEMBER_NEWFORM_PAYONLINE : ''), 0); print "\n"; diff --git a/htdocs/adherents/agenda.php b/htdocs/adherents/agenda.php index 2e74fdde9be..edb2e9ba4dc 100644 --- a/htdocs/adherents/agenda.php +++ b/htdocs/adherents/agenda.php @@ -42,16 +42,24 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = 'a.datep,a.id'; -if (!$sortorder) $sortorder = 'DESC'; +if (!$sortfield) { + $sortfield = 'a.datep,a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC'; +} if (GETPOST('actioncode', 'array')) { $actioncode = GETPOST('actioncode', 'array', 3); - if (!count($actioncode)) $actioncode = '0'; + if (!count($actioncode)) { + $actioncode = '0'; + } } else { $actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)); } @@ -76,7 +84,9 @@ if ($result > 0) { $parameters = array('id'=>$id, 'objcanvas'=>$objcanvas); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} if (empty($reshook)) { // Cancel @@ -115,7 +125,9 @@ if ($object->id > 0) { $helpurl = "EN:Module_Foundations|FR:Module_Adhérents|ES:Módulo_Miembros"; llxHeader("", $title, $helpurl); - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = member_prepare_head($object); print dol_get_fiche_head($head, 'agenda', $langs->trans("Member"), -1, 'user'); @@ -149,8 +161,12 @@ if ($object->id > 0) { print '
'; $param = '&id='.$id; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.$contextpage; + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.$limit; + } print_barre_liste($langs->trans("ActionsOnMember"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', '', $newcardbutton, '', 0, 1, 1); diff --git a/htdocs/adherents/canvas/actions_adherentcard_common.class.php b/htdocs/adherents/canvas/actions_adherentcard_common.class.php index 46c4b07b57c..970609fce65 100644 --- a/htdocs/adherents/canvas/actions_adherentcard_common.class.php +++ b/htdocs/adherents/canvas/actions_adherentcard_common.class.php @@ -64,13 +64,15 @@ abstract class ActionsAdherentCardCommon //$ret = $this->getInstanceDao(); /*if (is_object($this->object) && method_exists($this->object,'fetch')) - { - if (! empty($id)) $this->object->fetch($id); - } - else - {*/ + { + if (! empty($id)) $this->object->fetch($id); + } + else + {*/ $object = new Adherent($this->db); - if (!empty($id)) $object->fetch($id); + if (!empty($id)) { + $object->fetch($id); + } $this->object = $object; //} } @@ -89,7 +91,9 @@ abstract class ActionsAdherentCardCommon global $conf, $langs, $user, $canvas; global $form, $formcompany, $objsoc; - if ($action == 'add' || $action == 'update') $this->assign_post(); + if ($action == 'add' || $action == 'update') { + $this->assign_post(); + } foreach ($this->object as $key => $value) { $this->tpl[$key] = $value; @@ -123,12 +127,24 @@ abstract class ActionsAdherentCardCommon // Predefined with third party if ((isset($objsoc->typent_code) && $objsoc->typent_code == 'TE_PRIVATE')) { - if (dol_strlen(trim($this->object->address)) == 0) $this->tpl['address'] = $objsoc->address; - if (dol_strlen(trim($this->object->zip)) == 0) $this->object->zip = $objsoc->zip; - if (dol_strlen(trim($this->object->town)) == 0) $this->object->town = $objsoc->town; - if (dol_strlen(trim($this->object->phone_perso)) == 0) $this->object->phone_perso = $objsoc->phone; - if (dol_strlen(trim($this->object->phone_mobile)) == 0) $this->object->phone_mobile = $objsoc->phone_mobile; - if (dol_strlen(trim($this->object->email)) == 0) $this->object->email = $objsoc->email; + if (dol_strlen(trim($this->object->address)) == 0) { + $this->tpl['address'] = $objsoc->address; + } + if (dol_strlen(trim($this->object->zip)) == 0) { + $this->object->zip = $objsoc->zip; + } + if (dol_strlen(trim($this->object->town)) == 0) { + $this->object->town = $objsoc->town; + } + if (dol_strlen(trim($this->object->phone_perso)) == 0) { + $this->object->phone_perso = $objsoc->phone; + } + if (dol_strlen(trim($this->object->phone_mobile)) == 0) { + $this->object->phone_mobile = $objsoc->phone_mobile; + } + if (dol_strlen(trim($this->object->email)) == 0) { + $this->object->email = $objsoc->email; + } } // Zip @@ -137,17 +153,24 @@ abstract class ActionsAdherentCardCommon // Town $this->tpl['select_town'] = $formcompany->select_ziptown($this->object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id')); - if (dol_strlen(trim($this->object->country_id)) == 0) $this->object->country_id = $objsoc->country_id; + if (dol_strlen(trim($this->object->country_id)) == 0) { + $this->object->country_id = $objsoc->country_id; + } // Country $this->tpl['select_country'] = $form->select_country($this->object->country_id, 'country_id'); $countrynotdefined = $langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')'; - if ($user->admin) $this->tpl['info_admin'] = info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + $this->tpl['info_admin'] = info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } // State - if ($this->object->country_id) $this->tpl['select_state'] = $formcompany->select_state($this->object->state_id, $this->object->country_code); - else $this->tpl['select_state'] = $countrynotdefined; + if ($this->object->country_id) { + $this->tpl['select_state'] = $formcompany->select_state($this->object->state_id, $this->object->country_code); + } else { + $this->tpl['select_state'] = $countrynotdefined; + } // Physical or Moral $selectarray = array('0'=>$langs->trans("Physical"), '1'=>$langs->trans("Moral")); @@ -166,7 +189,9 @@ abstract class ActionsAdherentCardCommon $dolibarr_user = new User($this->db); $result = $dolibarr_user->fetch($this->object->user_id); $this->tpl['dolibarr_user'] = $dolibarr_user->getLoginUrl(1); - } else $this->tpl['dolibarr_user'] = $langs->trans("NoDolibarrAccess"); + } else { + $this->tpl['dolibarr_user'] = $langs->trans("NoDolibarrAccess"); + } } if ($action == 'view' || $action == 'delete') { @@ -205,7 +230,7 @@ abstract class ActionsAdherentCardCommon require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; $login = dol_buildlogin($this->object->lastname, $this->object->firstname); - $generated_password = getRandomPassword(false); + $generated_password = getRandomPassword(false); $password = $generated_password; // Create a form array diff --git a/htdocs/adherents/canvas/default/actions_adherentcard_default.class.php b/htdocs/adherents/canvas/default/actions_adherentcard_default.class.php index 43d6622f8c9..c79143ab345 100644 --- a/htdocs/adherents/canvas/default/actions_adherentcard_default.class.php +++ b/htdocs/adherents/canvas/default/actions_adherentcard_default.class.php @@ -60,9 +60,15 @@ class ActionsAdherentCardDefault extends ActionsAdherentCardCommon $out = ''; - if ($action == 'view') $out .= (!empty($conf->global->ADHERENT_ADDRESSES_MANAGEMENT) ? $langs->trans("Adherent") : $langs->trans("ContactAddress")); - if ($action == 'edit') $out .= (!empty($conf->global->ADHERENT_ADDRESSES_MANAGEMENT) ? $langs->trans("EditAdherent") : $langs->trans("EditAdherentAddress")); - if ($action == 'create') $out .= (!empty($conf->global->ADHERENT_ADDRESSES_MANAGEMENT) ? $langs->trans("NewAdherent") : $langs->trans("NewAdherentAddress")); + if ($action == 'view') { + $out .= (!empty($conf->global->ADHERENT_ADDRESSES_MANAGEMENT) ? $langs->trans("Adherent") : $langs->trans("ContactAddress")); + } + if ($action == 'edit') { + $out .= (!empty($conf->global->ADHERENT_ADDRESSES_MANAGEMENT) ? $langs->trans("EditAdherent") : $langs->trans("EditAdherentAddress")); + } + if ($action == 'create') { + $out .= (!empty($conf->global->ADHERENT_ADDRESSES_MANAGEMENT) ? $langs->trans("NewAdherent") : $langs->trans("NewAdherentAddress")); + } return $out; } diff --git a/htdocs/adherents/canvas/default/tpl/adherentcard_view.tpl.php b/htdocs/adherents/canvas/default/tpl/adherentcard_view.tpl.php index 539e174681f..16e9dc1886a 100644 --- a/htdocs/adherents/canvas/default/tpl/adherentcard_view.tpl.php +++ b/htdocs/adherents/canvas/default/tpl/adherentcard_view.tpl.php @@ -29,8 +29,12 @@ echo "\n"; echo $this->control->tpl['showhead']; dol_htmloutput_errors($this->control->tpl['error'], $this->control->tpl['errors']); -if (!empty($this->control->tpl['action_create_user'])) echo $this->control->tpl['action_create_user']; -if (!empty($this->control->tpl['action_delete'])) echo $this->control->tpl['action_delete']; ?> +if (!empty($this->control->tpl['action_create_user'])) { + echo $this->control->tpl['action_create_user']; +} +if (!empty($this->control->tpl['action_delete'])) { + echo $this->control->tpl['action_delete']; +} ?> diff --git a/htdocs/adherents/card.php b/htdocs/adherents/card.php index 8f2ea3f0706..7e72058092a 100644 --- a/htdocs/adherents/card.php +++ b/htdocs/adherents/card.php @@ -118,7 +118,9 @@ if ($id) { $parameters = array('id'=>$id, 'rowid'=>$id, 'objcanvas'=>$objcanvas, 'confirm'=>$confirm); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} if (empty($reshook)) { if ($cancel) { @@ -141,7 +143,9 @@ if (empty($reshook)) { if (!$error) { if ($userid != $object->user_id) { // If link differs from currently in database $result = $object->setUserId($userid); - if ($result < 0) dol_print_error($object->db, $object->error); + if ($result < 0) { + dol_print_error($object->db, $object->error); + } $action = ''; } } @@ -169,7 +173,9 @@ if (empty($reshook)) { if (!$error) { $result = $object->setThirdPartyId($socid); - if ($result < 0) dol_print_error($object->db, $object->error); + if ($result < 0) { + dol_print_error($object->db, $object->error); + } $action = ''; } } @@ -221,8 +227,7 @@ if (empty($reshook)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $birthdate = ''; - if (GETPOST("birthday", 'int') && GETPOST("birthmonth", 'int') && GETPOST("birthyear", 'int')) - { + if (GETPOST("birthday", 'int') && GETPOST("birthmonth", 'int') && GETPOST("birthyear", 'int')) { $birthdate = dol_mktime(12, 0, 0, GETPOST("birthmonth", 'int'), GETPOST("birthday", 'int'), GETPOST("birthyear", 'int')); } $lastname = GETPOST("lastname", 'alphanohtml'); @@ -294,8 +299,11 @@ if (empty($reshook)) { //$object->note = trim(GETPOST("comment","alpha")); $object->morphy = GETPOST("morphy", 'alpha'); - if (GETPOST('deletephoto', 'alpha')) $object->photo = ''; - elseif (!empty($_FILES['photo']['name'])) $object->photo = dol_sanitizeFileName($_FILES['photo']['name']); + if (GETPOST('deletephoto', 'alpha')) { + $object->photo = ''; + } elseif (!empty($_FILES['photo']['name'])) { + $object->photo = dol_sanitizeFileName($_FILES['photo']['name']); + } // Get status and public property $object->statut = GETPOST("statut", 'alpha'); @@ -303,18 +311,24 @@ if (empty($reshook)) { // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } // Check if we need to also synchronize user information $nosyncuser = 0; if ($object->user_id) { // If linked to a user - if ($user->id != $object->user_id && empty($user->rights->user->user->creer)) $nosyncuser = 1; // Disable synchronizing + if ($user->id != $object->user_id && empty($user->rights->user->user->creer)) { + $nosyncuser = 1; // Disable synchronizing + } } // Check if we need to also synchronize password information $nosyncuserpass = 0; if ($object->user_id) { // If linked to a user - if ($user->id != $object->user_id && empty($user->rights->user->user->password)) $nosyncuserpass = 1; // Disable synchronizing + if ($user->id != $object->user_id && empty($user->rights->user->user->password)) { + $nosyncuserpass = 1; // Disable synchronizing + } } $result = $object->update($user, 0, $nosyncuser, $nosyncuserpass); @@ -380,7 +394,9 @@ if (empty($reshook)) { } if ($action == 'add' && $user->rights->adherent->creer) { - if ($canvas) $object->canvas = $canvas; + if ($canvas) { + $object->canvas = $canvas; + } $birthdate = ''; if (GETPOSTISSET("birthday") && GETPOST("birthday") && GETPOSTISSET("birthmonth") && GETPOST("birthmonth") && GETPOSTISSET("birthyear") && GETPOST("birthyear")) { $birthdate = dol_mktime(12, 0, 0, GETPOST("birthmonth", 'int'), GETPOST("birthday", 'int'), GETPOST("birthyear", 'int')); @@ -461,7 +477,9 @@ if (empty($reshook)) { // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } // Check parameters if (empty($morphy) || $morphy == "-1") { @@ -515,7 +533,9 @@ if (empty($reshook)) { setEventMessages($langs->trans("ErrorBadEMail", $email), null, 'errors'); } $public = 0; - if (isset($public)) $public = 1; + if (isset($public)) { + $public = 1; + } if (!$error) { $db->begin(); @@ -590,7 +610,9 @@ if (empty($reshook)) { $arraydefaultmessage = null; $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_MEMBER_VALIDATION; - if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse); + if (!empty($labeltouse)) { + $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse); + } if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { $subject = $arraydefaultmessage->topic; @@ -659,7 +681,9 @@ if (empty($reshook)) { $arraydefaultmessage = null; $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_CANCELATION; - if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse); + if (!empty($labeltouse)) { + $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse); + } if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { $subject = $arraydefaultmessage->topic; @@ -745,7 +769,7 @@ $formfile = new FormFile($db); $formcompany = new FormCompany($db); $title = $langs->trans("Member")." - ".$langs->trans("Card"); -$help_url = 'EN:Module_Foundations|FR:Module_Adhérents|ES:Módulo_Miembros'; +$help_url = 'EN:Module_Foundations|FR:Module_Adhérents|ES:Módulo_Miembros|DE:Modul_Mitglieder'; llxHeader('', $title, $help_url); $countrynotdefined = $langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')'; @@ -757,9 +781,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { if (empty($object->error) && $id) { $object = new Adherent($db); $result = $object->fetch($id); - if ($result <= 0) dol_print_error('', $object->error); + if ($result <= 0) { + dol_print_error('', $object->error); + } } - $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates + $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates $objcanvas->display_canvas($action); // Show template } else { // ----------------------------------------- @@ -785,7 +811,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { if (!empty($socid)) { $object = new Societe($db); - if ($socid > 0) $object->fetch($socid); + if ($socid > 0) { + $object->fetch($socid); + } if (!($object->id > 0)) { $langs->load("errors"); @@ -832,7 +860,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { print ''; print ''; print ''; - if ($backtopage) print ''; + if ($backtopage) { + print ''; + } print dol_get_fiche_head(''); @@ -913,7 +943,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { $object->country_id = $object->country_id ? $object->country_id : $mysoc->country_id; print ''; // State @@ -941,7 +973,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { - if (!$value['active']) break; + if (!$value['active']) { + break; + } print ''; } } @@ -1057,7 +1091,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { print ''; print ''; print ''; - if ($backtopage) print ''; + if ($backtopage) { + print ''; + } print dol_get_fiche_head($head, 'general', $langs->trans("Member"), 0, 'user'); @@ -1121,9 +1157,13 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { print ''; // State @@ -1174,7 +1216,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { - if (!$value['active']) break; + if (!$value['active']) { + break; + } print ''; } } @@ -1223,7 +1267,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { print ''; // Other attributes. Fields from hook formObjectOptions and Extrafields. @@ -1279,7 +1325,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $login = dol_buildlogin($object->lastname, $object->firstname); } - if (empty($login)) $login = strtolower(substr($object->firstname, 0, 4)).strtolower(substr($object->lastname, 0, 4)); + if (empty($login)) { + $login = strtolower(substr($object->firstname, 0, 4)).strtolower(substr($object->lastname, 0, 4)); + } // Create a form array $formquestion = array( @@ -1304,10 +1352,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { if ($object->morphy == 'mor') { $companyname = $object->company; - if (!empty($fullname)) $companyalias = $fullname; + if (!empty($fullname)) { + $companyalias = $fullname; + } } else { $companyname = $fullname; - if (!empty($object->company)) $companyalias = $object->company; + if (!empty($object->company)) { + $companyalias = $object->company; + } } // Create a form array @@ -1341,7 +1393,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { $arraydefaultmessage = null; $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_MEMBER_VALIDATION; - if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse); + if (!empty($labeltouse)) { + $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse); + } if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { $subject = $arraydefaultmessage->topic; @@ -1368,7 +1422,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { // Create form popup $formquestion = array(); - if ($object->email) $formquestion[] = array('type' => 'checkbox', 'name' => 'send_mail', 'label' => $label, 'value' => ($conf->global->ADHERENT_DEFAULT_SENDINFOBYMAIL ?true:false)); + if ($object->email) { + $formquestion[] = array('type' => 'checkbox', 'name' => 'send_mail', 'label' => $label, 'value' => ($conf->global->ADHERENT_DEFAULT_SENDINFOBYMAIL ?true:false)); + } if (!empty($conf->mailman->enabled) && !empty($conf->global->ADHERENT_USE_MAILMAN)) { $formquestion[] = array('type'=>'other', 'label'=>$langs->transnoentitiesnoconv("SynchroMailManEnabled"), 'value'=>''); } @@ -1400,7 +1456,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { $arraydefaultmessage = null; $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_CANCELATION; - if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse); + if (!empty($labeltouse)) { + $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse); + } if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { $subject = $arraydefaultmessage->topic; @@ -1427,15 +1485,21 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { // Create an array $formquestion = array(); - if ($object->email) $formquestion[] = array('type' => 'checkbox', 'name' => 'send_mail', 'label' => $label, 'value' => (!empty($conf->global->ADHERENT_DEFAULT_SENDINFOBYMAIL) ? 'true' : 'false')); - if ($backtopage) $formquestion[] = array('type' => 'hidden', 'name' => 'backtopage', 'value' => ($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"])); + if ($object->email) { + $formquestion[] = array('type' => 'checkbox', 'name' => 'send_mail', 'label' => $label, 'value' => (!empty($conf->global->ADHERENT_DEFAULT_SENDINFOBYMAIL) ? 'true' : 'false')); + } + if ($backtopage) { + $formquestion[] = array('type' => 'hidden', 'name' => 'backtopage', 'value' => ($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"])); + } print $form->formconfirm("card.php?rowid=".$id, $langs->trans("ResiliateMember"), $langs->trans("ConfirmResiliateMember"), "confirm_resign", $formquestion, 'no', 1, 240); } // Confirm remove member if ($action == 'delete') { $formquestion = array(); - if ($backtopage) $formquestion[] = array('type' => 'hidden', 'name' => 'backtopage', 'value' => ($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"])); + if ($backtopage) { + $formquestion[] = array('type' => 'hidden', 'name' => 'backtopage', 'value' => ($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"])); + } print $form->formconfirm("card.php?rowid=".$id, $langs->trans("DeleteMember"), $langs->trans("ConfirmDeleteMember"), "confirm_delete", $formquestion, 'no', 1); } @@ -1449,8 +1513,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { } $rowspan = 17; - if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) $rowspan++; - if (!empty($conf->societe->enabled)) $rowspan++; + if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { + $rowspan++; + } + if (!empty($conf->societe->enabled)) { + $rowspan++; + } $linkback = ''.$langs->trans("BackToList").''; @@ -1474,10 +1542,6 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { print ''; print ''; - // Gender - print ''; - print ''; // Company @@ -1490,10 +1554,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { // Password if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { print ''; + print '
'.$langs->trans('Country').''; print $form->select_country(GETPOSTISSET('country_id') ? GETPOST('country_id', 'alpha') : $object->country_id, 'country_id'); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print '
'.$langs->trans($value['label']).'
'; print $form->showphoto('memberphoto', $object)."\n"; if ($caneditfieldmember) { - if ($object->photo) print "
\n"; + if ($object->photo) { + print "
\n"; + } print ''; - if ($object->photo) print ''; + if ($object->photo) { + print ''; + } print ''; print ''; print '
'.$langs->trans("Delete").'

'.$langs->trans("Delete").'

'.$langs->trans("PhotoFile").'
'; @@ -1150,7 +1190,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { //$object->country_id=$object->country_id?$object->country_id:$mysoc->country_id; // In edit mode we don't force to company country if not defined print '
'.$langs->trans('Country').''; print $form->select_country(GETPOSTISSET("country_id") ? GETPOST("country_id", "alpha") : $object->country_id, 'country_id'); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } print '
'.$langs->trans($value['label']).'
'.$langs->trans("LinkedToDolibarrUser").''; if ($object->user_id) { $form->form_users($_SERVER['PHP_SELF'].'?rowid='.$object->id, $object->user_id, 'none'); - } else print $langs->trans("NoDolibarrAccess"); + } else { + print $langs->trans("NoDolibarrAccess"); + } print '
'.$langs->trans("MemberNature").''.$object->getmorphylib().'
'.$langs->trans("Gender").''; - if ($object->gender) print $langs->trans("Gender".$object->gender); print '
'.$langs->trans("Password").''.preg_replace('/./i', '*', $object->pass); - if ($object->pass) print preg_replace('/./i', '*', $object->pass); - else { - if ($user->admin) print $langs->trans("Crypted").': '.$object->pass_indatabase_crypted; - else print $langs->trans("Hidden"); + if ($object->pass) { + print preg_replace('/./i', '*', $object->pass); + } else { + if ($user->admin) { + print $langs->trans("Crypted").': '.$object->pass_indatabase_crypted; + } else { + print $langs->trans("Hidden"); + } } if ((!empty($object->pass) || !empty($object->pass_crypted)) && empty($object->user_id)) { $langs->load("errors"); @@ -1515,14 +1583,44 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { print $langs->trans("SubscriptionNotNeeded"); } elseif (!$adht->subscription) { print $langs->trans("SubscriptionNotRecorded"); - if ($object->statut > 0) print " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated + if ($object->statut > 0) { + print " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated + } } else { print $langs->trans("SubscriptionNotReceived"); - if ($object->statut > 0) print " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated + if ($object->statut > 0) { + print " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated + } } } print '
'; + + print '
'; + + print '
'; + print '
'; + + print ''; + + // Birth Date + print ''; + + // Public + print ''; + + // Categories + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { + print ''; + print ''; + } + + // Other attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; + // Third party Dolibarr if (!empty($conf->societe->enabled)) { print ''; - print '
'.$langs->trans("DateOfBirth").''.dol_print_date($object->birth, 'day').'
'.$langs->trans("Public").''.yn($object->public).'
'.$langs->trans("Categories").''; + print $form->showCategories($object->id, Categorie::TYPE_MEMBER, 1); + print '
'; @@ -1566,34 +1664,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { $linkeduser->fetch($object->user_id); print $linkeduser->getNomUrl(-1); } else { - print $langs->trans("NoDolibarrAccess"); + print ''.$langs->trans("NoDolibarrAccess").''; } } print '
'; - - print '
'; - - print '
'; - print '
'; - - print ''; - - // Birth Date - print ''; - - // Public - print ''; - - // Categories - if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { - print ''; - print ''; - } - //VCard print ''; - // Other attributes - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; - print "
'.$langs->trans("DateOfBirth").''.dol_print_date($object->birth, 'day').'
'.$langs->trans("Public").''.yn($object->public).'
'.$langs->trans("Categories").''; - print $form->showCategories($object->id, Categorie::TYPE_MEMBER, 1); - print '
'; print $langs->trans("VCard").''; @@ -1603,9 +1678,6 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { print ''; print '
\n"; print "
\n"; @@ -1687,8 +1759,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { // Create third party if (!empty($conf->societe->enabled) && !$object->socid) { if ($user->rights->societe->creer) { - if ($object->statut != -1) print ''; - else print ''; + if ($object->statut != -1) { + print ''; + } else { + print ''; + } } else { print '
'.$langs->trans("CreateDolibarrThirdParty")."
"; } @@ -1697,8 +1772,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { // Create user if (!$user->socid && !$object->user_id) { if ($user->rights->user->user->creer) { - if ($object->statut != -1) print ''; - else print ''; + if ($object->statut != -1) { + print ''; + } else { + print ''; + } } else { print '
'.$langs->trans("CreateDolibarrLogin")."
"; } diff --git a/htdocs/adherents/cartes/carte.php b/htdocs/adherents/cartes/carte.php index e70248a455e..9d403d88320 100644 --- a/htdocs/adherents/cartes/carte.php +++ b/htdocs/adherents/cartes/carte.php @@ -80,8 +80,12 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) { } $sql .= " WHERE d.fk_adherent_type = t.rowid AND d.statut = 1"; $sql .= " AND d.entity IN (".getEntity('adherent').")"; - if (is_numeric($foruserid)) $sql .= " AND d.rowid=".(int) $foruserid; - if ($foruserlogin) $sql .= " AND d.login='".$db->escape($foruserlogin)."'"; + if (is_numeric($foruserid)) { + $sql .= " AND d.rowid=".(int) $foruserid; + } + if ($foruserlogin) { + $sql .= " AND d.login='".$db->escape($foruserlogin)."'"; + } $sql .= " ORDER BY d.rowid ASC"; dol_syslog("Search members", LOG_DEBUG); @@ -92,7 +96,9 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) { while ($i < $num) { $objp = $db->fetch_object($result); - if ($objp->country == '-') $objp->country = ''; + if ($objp->country == '-') { + $objp->country = ''; + } $adherentstatic->id = $objp->rowid; $adherentstatic->ref = $objp->ref; @@ -147,7 +153,9 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) { if (is_numeric($foruserid) || $foruserlogin) { $nb = $_Avery_Labels[$model]['NX'] * $_Avery_Labels[$model]['NY']; - if ($nb <= 0) $nb = 1; // Protection to avoid empty page + if ($nb <= 0) { + $nb = 1; // Protection to avoid empty page + } for ($j = 0; $j < $nb; $j++) { $arrayofmembers[] = array( @@ -175,7 +183,9 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) { // For labels if ($mode == 'label') { - if (empty($conf->global->ADHERENT_ETIQUETTE_TEXT)) $conf->global->ADHERENT_ETIQUETTE_TEXT = "__FULLNAME__\n__ADDRESS__\n__ZIP__ __TOWN__\n__COUNTRY__"; + if (empty($conf->global->ADHERENT_ETIQUETTE_TEXT)) { + $conf->global->ADHERENT_ETIQUETTE_TEXT = "__FULLNAME__\n__ADDRESS__\n__ZIP__ __TOWN__\n__COUNTRY__"; + } $textleft = make_substitutions($conf->global->ADHERENT_ETIQUETTE_TEXT, $substitutionarray); $textheader = ''; $textfooter = ''; @@ -203,7 +213,9 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) { if (empty($model) || $model == '-1') { $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DescADHERENT_CARD_TYPE")); } - if (!$mesg) $result = members_card_pdf_create($db, $arrayofmembers, $model, $outputlangs); + if (!$mesg) { + $result = members_card_pdf_create($db, $arrayofmembers, $model, $outputlangs); + } } elseif ($mode == 'label') { if (!count($arrayofmembers)) { $mesg = $langs->trans("ErrorRecordNotFound"); @@ -211,7 +223,9 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) { if (empty($modellabel) || $modellabel == '-1') { $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DescADHERENT_ETIQUETTE_TYPE")); } - if (!$mesg) $result = doc_label_pdf_create($db, $arrayofmembers, $modellabel, $outputlangs); + if (!$mesg) { + $result = doc_label_pdf_create($db, $arrayofmembers, $modellabel, $outputlangs); + } } if ($result <= 0) { diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index 8e5cdbe8067..6429f86311a 100644 --- a/htdocs/adherents/class/adherent.class.php +++ b/htdocs/adherents/class/adherent.class.php @@ -373,18 +373,24 @@ class Adherent extends CommonObject // Detect if message is HTML if ($msgishtml == -1) { $msgishtml = 0; - if (dol_textishtml($text, 0)) $msgishtml = 1; + if (dol_textishtml($text, 0)) { + $msgishtml = 1; + } } dol_syslog('send_an_email msgishtml='.$msgishtml); $texttosend = $this->makeSubstitution($text); $subjecttosend = $this->makeSubstitution($subject); - if ($msgishtml) $texttosend = dol_htmlentitiesbr($texttosend); + if ($msgishtml) { + $texttosend = dol_htmlentitiesbr($texttosend); + } // Envoi mail confirmation $from = $conf->email_from; - if (!empty($conf->global->ADHERENT_MAIL_FROM)) $from = $conf->global->ADHERENT_MAIL_FROM; + if (!empty($conf->global->ADHERENT_MAIL_FROM)) { + $from = $conf->global->ADHERENT_MAIL_FROM; + } $trackid = 'mem'.$this->id; @@ -413,10 +419,14 @@ class Adherent extends CommonObject $birthday = dol_print_date($this->birth, 'day'); $msgishtml = 0; - if (dol_textishtml($text, 1)) $msgishtml = 1; + if (dol_textishtml($text, 1)) { + $msgishtml = 1; + } $infos = ''; - if ($this->civility_id) $infos .= $langs->transnoentities("UserTitle").": ".$this->getCivilityLabel()."\n"; + if ($this->civility_id) { + $infos .= $langs->transnoentities("UserTitle").": ".$this->getCivilityLabel()."\n"; + } $infos .= $langs->transnoentities("id").": ".$this->id."\n"; $infos .= $langs->transnoentities("ref").": ".$this->ref."\n"; $infos .= $langs->transnoentities("Lastname").": ".$this->lastname."\n"; @@ -514,7 +524,9 @@ class Adherent extends CommonObject $this->error = $langs->trans("ErrorBadEMail", $this->email); return -1; } - if (!$this->datec) $this->datec = $now; + if (!$this->datec) { + $this->datec = $now; + } if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { if (empty($this->login)) { $this->error = $langs->trans("ErrorWrongValueForParameterX", "Login"); @@ -669,9 +681,15 @@ class Adherent extends CommonObject $sql .= ", fk_adherent_type = ".$this->db->escape($this->typeid); $sql .= ", morphy = '".$this->db->escape($this->morphy)."'"; $sql .= ", birth = ".($this->birth ? "'".$this->db->idate($this->birth)."'" : "null"); - if ($this->socid) $sql .= ", fk_soc = '".$this->db->escape($this->socid)."'"; // Must be modified only when creating from a third-party - if ($this->datefin) $sql .= ", datefin = '".$this->db->idate($this->datefin)."'"; // Must be modified only when deleting a subscription - if ($this->datevalid) $sql .= ", datevalid = '".$this->db->idate($this->datevalid)."'"; // Must be modified only when validating a member + if ($this->socid) { + $sql .= ", fk_soc = '".$this->db->escape($this->socid)."'"; // Must be modified only when creating from a third-party + } + if ($this->datefin) { + $sql .= ", datefin = '".$this->db->idate($this->datefin)."'"; // Must be modified only when deleting a subscription + } + if ($this->datevalid) { + $sql .= ", datevalid = '".$this->db->idate($this->datevalid)."'"; // Must be modified only when validating a member + } $sql .= ", fk_user_mod = ".($user->id > 0 ? $user->id : 'null'); // Can be null because member can be create by a guest $sql .= " WHERE rowid = ".$this->id; @@ -716,7 +734,9 @@ class Adherent extends CommonObject // If password to set differs from the one found into database $result = $this->setPassword($user, $this->pass, $isencrypted, $notrigger, $nosyncuserpass); - if (!$nbrowsaffected) $nbrowsaffected++; + if (!$nbrowsaffected) { + $nbrowsaffected++; + } } } @@ -759,7 +779,9 @@ class Adherent extends CommonObject //var_dump($this->login);exit; // If option ADHERENT_LOGIN_NOT_REQUIRED is on, there is no login of member, so we do not overwrite user login to keep existing one. - if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) $luser->login = $this->login; + if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { + $luser->login = $this->login; + } $luser->ref = $this->ref; $luser->civility_id = $this->civility_id; @@ -925,14 +947,18 @@ class Adherent extends CommonObject $errorflag = 0; // Check parameters - if (empty($rowid)) $rowid = $this->id; + if (empty($rowid)) { + $rowid = $this->id; + } $this->db->begin(); if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('MEMBER_DELETE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } @@ -1474,7 +1500,9 @@ class Adherent extends CommonObject $error = 0; // Clean parameters - if (!$amount) $amount = 0; + if (!$amount) { + $amount = 0; + } $this->db->begin(); @@ -1605,10 +1633,14 @@ class Adherent extends CommonObject if ($this->morphy == 'mor') { $companyname = $this->company; - if (!empty($fullname)) $companyalias = $fullname; + if (!empty($fullname)) { + $companyalias = $fullname; + } } else { $companyname = $fullname; - if (!empty($this->company)) $companyalias = $this->company; + if (!empty($this->company)) { + $companyalias = $this->company; + } } $result = $customer->create_from_member($this, $companyname, $companyalias); @@ -1671,7 +1703,9 @@ class Adherent extends CommonObject if (!$error) { // Add line to draft invoice $idprodsubscription = 0; - if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) $idprodsubscription = $conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS; + if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) { + $idprodsubscription = $conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS; + } $vattouse = 0; if (isset($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) && $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS == 'defaultforfoundationcountry') { @@ -1758,8 +1792,12 @@ class Adherent extends CommonObject $outputlangs = $langs; $newlang = ''; $lang_id = GETPOST('lang_id'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && !empty($lang_id)) $newlang = $lang_id; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $customer->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && !empty($lang_id)) { + $newlang = $lang_id; + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $customer->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -1901,7 +1939,9 @@ class Adherent extends CommonObject $result = $mailmanspip->add_to_mailman($this); if ($result < 0) { - if (!empty($mailmanspip->error)) $this->errors[] = $mailmanspip->error; + if (!empty($mailmanspip->error)) { + $this->errors[] = $mailmanspip->error; + } $err += 1; } foreach ($mailmanspip->mladded_ko as $tmplist => $tmpemail) { @@ -1950,7 +1990,9 @@ class Adherent extends CommonObject if (!empty($conf->global->ADHERENT_USE_MAILMAN)) { $result = $mailmanspip->del_to_mailman($this); if ($result < 0) { - if (!empty($mailmanspip->error)) $this->errors[] = $mailmanspip->error; + if (!empty($mailmanspip->error)) { + $this->errors[] = $mailmanspip->error; + } $err += 1; } @@ -1991,7 +2033,9 @@ class Adherent extends CommonObject $langs->load("dict"); $code = (empty($this->civility_id) ? '' : $this->civility_id); - if (empty($code)) return ''; + if (empty($code)) { + return ''; + } return $langs->getLabelFromKey($this->db, "Civility".$code, "c_civility", "code", "label", $code); } @@ -2012,7 +2056,9 @@ class Adherent extends CommonObject { global $conf, $langs; - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpictoimg) $withpictoimg = 0; + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpictoimg) { + $withpictoimg = 0; + } $result = ''; $label = ''; @@ -2028,21 +2074,31 @@ class Adherent extends CommonObject $label .= '
'; $label .= img_picto('', $this->picto).' '.$langs->trans("Member").''; $label .= ' '.$this->getLibStatut(4); - if (!empty($this->ref)) $label .= '
'.$langs->trans('Ref').': '.$this->ref; - if (!empty($this->firstname) || !empty($this->lastname)) $label .= '
'.$langs->trans('Name').': '.$this->getFullName($langs); - if (!empty($this->company)) $label .= '
'.$langs->trans('Company').': '.$this->company; + if (!empty($this->ref)) { + $label .= '
'.$langs->trans('Ref').': '.$this->ref; + } + if (!empty($this->firstname) || !empty($this->lastname)) { + $label .= '
'.$langs->trans('Name').': '.$this->getFullName($langs); + } + if (!empty($this->company)) { + $label .= '
'.$langs->trans('Company').': '.$this->company; + } $label .= '
'; - $url = DOL_URL_ROOT.'/adherents/card.php?rowid='.$this->id; + $url = DOL_URL_ROOT.'/adherents/card.php?rowid='.((int) $this->id); if ($option == 'subscription') { - $url = DOL_URL_ROOT.'/adherents/subscription.php?rowid='.$this->id; + $url = DOL_URL_ROOT.'/adherents/subscription.php?rowid='.((int) $this->id); } if ($option != 'nolink') { // Add param to save lastsearch_values or not $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } } $linkstart .= ' 0) + if ($withpictoimg > 0) { $picto = ''. img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).''; - // Picto must be a photo - else { + } else { + // Picto must be a photo $picto = ''; $picto .= Form::showphoto('memberphoto', $this, 0, 0, 0, 'userphoto'.($withpictoimg == -3 ? 'small' : ''), 'mini', 0, 1); $picto .= ''; @@ -2078,8 +2138,10 @@ class Adherent extends CommonObject $result .= $picto; } if ($withpictoimg > -2 && $withpictoimg != 2) { - if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $result .= 'statut) || $this->statut) ? '' : ' strikefordisabled'). ($morecss ? ' usertext'.$morecss : '').'">'; + } if ($mode == 'login') { $result .= dol_trunc($this->login, $maxlen); } elseif ($mode == 'ref') { @@ -2087,9 +2149,13 @@ class Adherent extends CommonObject } else { $result .= $this->getFullName($langs, '', ($mode == 'firstname' ? 2 : ($mode == 'lastname' ? 4 : -1)), $maxlen); } - if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $result .= ''; + if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $result .= ''; + } + } + if ($withpictoimg) { + $result .= '
'; } - if ($withpictoimg) $result .= '
'; $result .= $linkend; if ($addlinktonotes) { @@ -2150,7 +2216,7 @@ class Adherent extends CommonObject $statusType = 'status1'; $labelStatus = $langs->trans("MemberStatusActive"); $labelStatusShort = $langs->trans("MemberStatusActiveShort"); - } elseif ($date_end_subscription < time()) { + } elseif ($date_end_subscription < dol_now()) { $statusType = 'status3'; $labelStatus = $langs->trans("MemberStatusActiveLate"); $labelStatusShort = $langs->trans("MemberStatusActiveLateShort"); @@ -2214,7 +2280,9 @@ class Adherent extends CommonObject // phpcs:enable global $conf, $langs; - if ($user->socid) return -1; // protection pour eviter appel par utilisateur externe + if ($user->socid) { + return -1; // protection pour eviter appel par utilisateur externe + } $now = dol_now(); @@ -2398,9 +2466,15 @@ class Adherent extends CommonObject // phpcs:enable global $conf; $dn = ''; - if ($mode == 0) $dn = $conf->global->LDAP_KEY_MEMBERS."=".$info[$conf->global->LDAP_KEY_MEMBERS].",".$conf->global->LDAP_MEMBER_DN; - if ($mode == 1) $dn = $conf->global->LDAP_MEMBER_DN; - if ($mode == 2) $dn = $conf->global->LDAP_KEY_MEMBERS."=".$info[$conf->global->LDAP_KEY_MEMBERS]; + if ($mode == 0) { + $dn = $conf->global->LDAP_KEY_MEMBERS."=".$info[$conf->global->LDAP_KEY_MEMBERS].",".$conf->global->LDAP_MEMBER_DN; + } + if ($mode == 1) { + $dn = $conf->global->LDAP_MEMBER_DN; + } + if ($mode == 2) { + $dn = $conf->global->LDAP_KEY_MEMBERS."=".$info[$conf->global->LDAP_KEY_MEMBERS]; + } return $dn; } @@ -2448,31 +2522,65 @@ class Adherent extends CommonObject // Check if it is the LDAP key and if its value has been changed if (!empty($conf->global->LDAP_KEY_MEMBERS) && $conf->global->LDAP_KEY_MEMBERS == $conf->global->$constname) { - if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) $keymodified = true; // For check if LDAP key has been modified + if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) { + $keymodified = true; // For check if LDAP key has been modified + } } } } - if ($this->firstname && !empty($conf->global->LDAP_MEMBER_FIELD_FIRSTNAME)) $info[$conf->global->LDAP_MEMBER_FIELD_FIRSTNAME] = $this->firstname; - if ($this->poste && !empty($conf->global->LDAP_MEMBER_FIELD_TITLE)) $info[$conf->global->LDAP_MEMBER_FIELD_TITLE] = $this->poste; - if ($this->company && !empty($conf->global->LDAP_MEMBER_FIELD_COMPANY)) $info[$conf->global->LDAP_MEMBER_FIELD_COMPANY] = $this->company; - if ($this->address && !empty($conf->global->LDAP_MEMBER_FIELD_ADDRESS)) $info[$conf->global->LDAP_MEMBER_FIELD_ADDRESS] = $this->address; - if ($this->zip && !empty($conf->global->LDAP_MEMBER_FIELD_ZIP)) $info[$conf->global->LDAP_MEMBER_FIELD_ZIP] = $this->zip; - if ($this->town && !empty($conf->global->LDAP_MEMBER_FIELD_TOWN)) $info[$conf->global->LDAP_MEMBER_FIELD_TOWN] = $this->town; - if ($this->country_code && !empty($conf->global->LDAP_MEMBER_FIELD_COUNTRY)) $info[$conf->global->LDAP_MEMBER_FIELD_COUNTRY] = $this->country_code; + if ($this->firstname && !empty($conf->global->LDAP_MEMBER_FIELD_FIRSTNAME)) { + $info[$conf->global->LDAP_MEMBER_FIELD_FIRSTNAME] = $this->firstname; + } + if ($this->poste && !empty($conf->global->LDAP_MEMBER_FIELD_TITLE)) { + $info[$conf->global->LDAP_MEMBER_FIELD_TITLE] = $this->poste; + } + if ($this->company && !empty($conf->global->LDAP_MEMBER_FIELD_COMPANY)) { + $info[$conf->global->LDAP_MEMBER_FIELD_COMPANY] = $this->company; + } + if ($this->address && !empty($conf->global->LDAP_MEMBER_FIELD_ADDRESS)) { + $info[$conf->global->LDAP_MEMBER_FIELD_ADDRESS] = $this->address; + } + if ($this->zip && !empty($conf->global->LDAP_MEMBER_FIELD_ZIP)) { + $info[$conf->global->LDAP_MEMBER_FIELD_ZIP] = $this->zip; + } + if ($this->town && !empty($conf->global->LDAP_MEMBER_FIELD_TOWN)) { + $info[$conf->global->LDAP_MEMBER_FIELD_TOWN] = $this->town; + } + if ($this->country_code && !empty($conf->global->LDAP_MEMBER_FIELD_COUNTRY)) { + $info[$conf->global->LDAP_MEMBER_FIELD_COUNTRY] = $this->country_code; + } foreach ($socialnetworks as $key => $value) { if ($this->socialnetworks[$value['label']] && !empty($conf->global->{'LDAP_MEMBER_FIELD_'.strtoupper($value['label'])})) { $info[$conf->global->{'LDAP_MEMBER_FIELD_'.strtoupper($value['label'])}] = $this->socialnetworks[$value['label']]; } } - if ($this->phone && !empty($conf->global->LDAP_MEMBER_FIELD_PHONE)) $info[$conf->global->LDAP_MEMBER_FIELD_PHONE] = $this->phone; - if ($this->phone_perso && !empty($conf->global->LDAP_MEMBER_FIELD_PHONE_PERSO)) $info[$conf->global->LDAP_MEMBER_FIELD_PHONE_PERSO] = $this->phone_perso; - if ($this->phone_mobile && !empty($conf->global->LDAP_MEMBER_FIELD_MOBILE)) $info[$conf->global->LDAP_MEMBER_FIELD_MOBILE] = $this->phone_mobile; - if ($this->fax && !empty($conf->global->LDAP_MEMBER_FIELD_FAX)) $info[$conf->global->LDAP_MEMBER_FIELD_FAX] = $this->fax; - if ($this->note_private && !empty($conf->global->LDAP_MEMBER_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_MEMBER_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_private, 2); - if ($this->note_public && !empty($conf->global->LDAP_MEMBER_FIELD_NOTE_PUBLIC)) $info[$conf->global->LDAP_MEMBER_FIELD_NOTE_PUBLIC] = dol_string_nohtmltag($this->note_public, 2); - if ($this->birth && !empty($conf->global->LDAP_MEMBER_FIELD_BIRTHDATE)) $info[$conf->global->LDAP_MEMBER_FIELD_BIRTHDATE] = dol_print_date($this->birth, 'dayhourldap'); - if (isset($this->statut) && !empty($conf->global->LDAP_FIELD_MEMBER_STATUS)) $info[$conf->global->LDAP_FIELD_MEMBER_STATUS] = $this->statut; - if ($this->datefin && !empty($conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION)) $info[$conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION] = dol_print_date($this->datefin, 'dayhourldap'); + if ($this->phone && !empty($conf->global->LDAP_MEMBER_FIELD_PHONE)) { + $info[$conf->global->LDAP_MEMBER_FIELD_PHONE] = $this->phone; + } + if ($this->phone_perso && !empty($conf->global->LDAP_MEMBER_FIELD_PHONE_PERSO)) { + $info[$conf->global->LDAP_MEMBER_FIELD_PHONE_PERSO] = $this->phone_perso; + } + if ($this->phone_mobile && !empty($conf->global->LDAP_MEMBER_FIELD_MOBILE)) { + $info[$conf->global->LDAP_MEMBER_FIELD_MOBILE] = $this->phone_mobile; + } + if ($this->fax && !empty($conf->global->LDAP_MEMBER_FIELD_FAX)) { + $info[$conf->global->LDAP_MEMBER_FIELD_FAX] = $this->fax; + } + if ($this->note_private && !empty($conf->global->LDAP_MEMBER_FIELD_DESCRIPTION)) { + $info[$conf->global->LDAP_MEMBER_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_private, 2); + } + if ($this->note_public && !empty($conf->global->LDAP_MEMBER_FIELD_NOTE_PUBLIC)) { + $info[$conf->global->LDAP_MEMBER_FIELD_NOTE_PUBLIC] = dol_string_nohtmltag($this->note_public, 2); + } + if ($this->birth && !empty($conf->global->LDAP_MEMBER_FIELD_BIRTHDATE)) { + $info[$conf->global->LDAP_MEMBER_FIELD_BIRTHDATE] = dol_print_date($this->birth, 'dayhourldap'); + } + if (isset($this->statut) && !empty($conf->global->LDAP_FIELD_MEMBER_STATUS)) { + $info[$conf->global->LDAP_FIELD_MEMBER_STATUS] = $this->statut; + } + if ($this->datefin && !empty($conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION)) { + $info[$conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION] = dol_print_date($this->datefin, 'dayhourldap'); + } // When password is modified if (!empty($this->pass)) { @@ -2482,8 +2590,9 @@ class Adherent extends CommonObject if (!empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) { $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass, 4); // Create OpenLDAP MD5 password (TODO add type of encryption) } - } // Set LDAP password if possible - elseif ($conf->global->LDAP_SERVER_PROTOCOLVERSION !== '3') { // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password + } elseif ($conf->global->LDAP_SERVER_PROTOCOLVERSION !== '3') { + // Set LDAP password if possible + // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) { // Just for the default MD5 ! if (empty($conf->global->MAIN_SECURITY_HASH_ALGO)) { @@ -2493,18 +2602,30 @@ class Adherent extends CommonObject $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = '{md5}'.base64_encode(hex2bin($this->pass_indatabase_crypted)); } } - } // Use $this->pass_indatabase value if exists - elseif (!empty($this->pass_indatabase)) { - if (!empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte - if (!empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase, 4); // md5 for OpenLdap TODO add type of encryption + } elseif (!empty($this->pass_indatabase)) { + // Use $this->pass_indatabase value if exists + if (!empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD)) { + $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD] = $this->pass_indatabase; // $this->pass_indatabase = mot de passe non crypte + } + if (!empty($conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED)) { + $info[$conf->global->LDAP_MEMBER_FIELD_PASSWORD_CRYPTED] = dol_hash($this->pass_indatabase, 4); // md5 for OpenLdap TODO add type of encryption + } } } // Subscriptions - if ($this->first_subscription_date && !empty($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE)) $info[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE] = dol_print_date($this->first_subscription_date, 'dayhourldap'); - if (isset($this->first_subscription_amount) && !empty($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT)) $info[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT] = $this->first_subscription_amount; - if ($this->last_subscription_date && !empty($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE)) $info[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE] = dol_print_date($this->last_subscription_date, 'dayhourldap'); - if (isset($this->last_subscription_amount) && !empty($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT)) $info[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT] = $this->last_subscription_amount; + if ($this->first_subscription_date && !empty($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE)) { + $info[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE] = dol_print_date($this->first_subscription_date, 'dayhourldap'); + } + if (isset($this->first_subscription_amount) && !empty($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT)) { + $info[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT] = $this->first_subscription_amount; + } + if ($this->last_subscription_date && !empty($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE)) { + $info[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE] = dol_print_date($this->last_subscription_date, 'dayhourldap'); + } + if (isset($this->last_subscription_amount) && !empty($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT)) { + $info[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT] = $this->last_subscription_amount; + } return $info; } @@ -2523,7 +2644,7 @@ class Adherent extends CommonObject $sql .= ' a.tms as datem,'; $sql .= ' a.fk_user_author, a.fk_user_valid, a.fk_user_mod'; $sql .= ' FROM '.MAIN_DB_PREFIX.'adherent as a'; - $sql .= ' WHERE a.rowid = '.$id; + $sql .= ' WHERE a.rowid = '.((int) $id); dol_syslog(get_class($this)."::info", LOG_DEBUG); $result = $this->db->query($sql); @@ -2626,8 +2747,12 @@ class Adherent extends CommonObject global $conf; //Only valid members - if ($this->statut <= 0) return false; - if (!$this->datefin) return false; + if ($this->statut <= 0) { + return false; + } + if (!$this->datefin) { + return false; + } $now = dol_now(); @@ -2720,7 +2845,9 @@ class Adherent extends CommonObject $arraydefaultmessage = null; $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_REMIND_EXPIRATION; - if (!empty($labeltouse)) $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'member', $user, $outputlangs, 0, 1, $labeltouse); + if (!empty($labeltouse)) { + $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'member', $user, $outputlangs, 0, 1, $labeltouse); + } if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) { $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $adherent); @@ -2763,7 +2890,9 @@ class Adherent extends CommonObject if ($message) { $actionmsg = $langs->transnoentities('MailFrom').': '.dol_escape_htmltag($from); $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTo').': '.dol_escape_htmltag($sendto)); - if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".dol_escape_htmltag($sendtocc)); + if ($sendtocc) { + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".dol_escape_htmltag($sendtocc)); + } $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subject); $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":"); $actionmsg = dol_concatdesc($actionmsg, $message); @@ -2843,7 +2972,9 @@ class Adherent extends CommonObject $listofids .= $idmember; $i++; } - if ($listofids) $listofids .= ']'; + if ($listofids) { + $listofids .= ']'; + } $this->output .= $listofids; } if ($nbko) { @@ -2864,7 +2995,9 @@ class Adherent extends CommonObject $listofids .= $idmember; $i++; } - if ($listofids) $listofids .= ']'; + if ($listofids) { + $listofids .= ']'; + } $this->output .= $listofids; } } diff --git a/htdocs/adherents/class/adherent_type.class.php b/htdocs/adherents/class/adherent_type.class.php index 9c677148b92..9acecaab1ce 100644 --- a/htdocs/adherents/class/adherent_type.class.php +++ b/htdocs/adherents/class/adherent_type.class.php @@ -74,8 +74,8 @@ class AdherentType extends CommonObject public $duration; /* - * type expiration - */ + * type expiration + */ public $duration_value; /** @@ -241,12 +241,12 @@ class AdherentType extends CommonObject } /** - * Delete a language for this member type - * - * @param string $langtodelete Language code to delete - * @param User $user Object user making delete - * @return int <0 if KO, >0 if OK - */ + * Delete a language for this member type + * + * @param string $langtodelete Language code to delete + * @param User $user Object user making delete + * @return int <0 if KO, >0 if OK + */ public function delMultiLangs($langtodelete, $user) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."adherent_type_lang"; @@ -313,7 +313,9 @@ class AdherentType extends CommonObject if (!$notrigger) { // Call trigger $result = $this->call_trigger('MEMBER_TYPE_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -386,7 +388,9 @@ class AdherentType extends CommonObject if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('MEMBER_TYPE_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -423,7 +427,9 @@ class AdherentType extends CommonObject if ($resql) { // Call trigger $result = $this->call_trigger('MEMBER_TYPE_DELETE', $user); - if ($result < 0) { $error++; $this->db->rollback(); return -2; } + if ($result < 0) { + $error++; $this->db->rollback(); return -2; + } // End call triggers $this->db->commit(); @@ -499,7 +505,9 @@ class AdherentType extends CommonObject $sql = "SELECT rowid, libelle as label"; $sql .= " FROM ".MAIN_DB_PREFIX."adherent_type"; $sql .= " WHERE entity IN (".getEntity('member_type').")"; - if ($status >= 0) $sql .= " AND statut = ".((int) $status); + if ($status >= 0) { + $sql .= " AND statut = ".((int) $status); + } $resql = $this->db->query($sql); if ($resql) { @@ -539,7 +547,9 @@ class AdherentType extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."adherent as a"; $sql .= " WHERE a.entity IN (".getEntity('member').")"; $sql .= " AND a.fk_adherent_type = ".$this->id; - if (!empty($excludefilter)) $sql .= ' AND ('.$excludefilter.')'; + if (!empty($excludefilter)) { + $sql .= ' AND ('.$excludefilter.')'; + } dol_syslog(get_class($this)."::listUsersForGroup", LOG_DEBUG); $resql = $this->db->query($sql); @@ -554,7 +564,9 @@ class AdherentType extends CommonObject $memberstatic->fetch($obj->rowid); } $ret[$obj->rowid] = $memberstatic; - } else $ret[$obj->rowid] = $obj->rowid; + } else { + $ret[$obj->rowid] = $obj->rowid; + } } } @@ -578,7 +590,13 @@ class AdherentType extends CommonObject public function getmorphylib($morphy = '') { global $langs; - if ($morphy == 'phy') { return $langs->trans("Physical"); } elseif ($morphy == 'mor') { return $langs->trans("Moral"); } else return $langs->trans("MorAndPhy"); + if ($morphy == 'phy') { + return $langs->trans("Physical"); + } elseif ($morphy == 'mor') { + return $langs->trans("Moral"); + } else { + return $langs->trans("MorAndPhy"); + } //return $morphy; } @@ -605,12 +623,16 @@ class AdherentType extends CommonObject $label .= '
'.$langs->trans("SubscriptionRequired").': '.yn($this->subscription); } - $linkstart = '
'; + $linkstart = ''; $linkend = ''; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= ($maxlen ?dol_trunc($this->label, $maxlen) : $this->label); + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= ($maxlen ?dol_trunc($this->label, $maxlen) : $this->label); + } $result .= $linkend; return $result; @@ -642,7 +664,9 @@ class AdherentType extends CommonObject $langs->load('companies'); $statusType = 'status4'; - if ($status == 0) $statusType = 'status5'; + if ($status == 0) { + $statusType = 'status5'; + } if (empty($this->labelStatus) || empty($this->labelStatusShort)) { $this->labelStatus[0] = $langs->trans("ActivityCeased"); @@ -670,9 +694,15 @@ class AdherentType extends CommonObject // phpcs:enable global $conf; $dn = ''; - if ($mode == 0) $dn = $conf->global->LDAP_KEY_MEMBERS_TYPES."=".$info[$conf->global->LDAP_KEY_MEMBERS_TYPES].",".$conf->global->LDAP_MEMBER_TYPE_DN; - if ($mode == 1) $dn = $conf->global->LDAP_MEMBER_TYPE_DN; - if ($mode == 2) $dn = $conf->global->LDAP_KEY_MEMBERS_TYPES."=".$info[$conf->global->LDAP_KEY_MEMBERS_TYPES]; + if ($mode == 0) { + $dn = $conf->global->LDAP_KEY_MEMBERS_TYPES."=".$info[$conf->global->LDAP_KEY_MEMBERS_TYPES].",".$conf->global->LDAP_MEMBER_TYPE_DN; + } + if ($mode == 1) { + $dn = $conf->global->LDAP_MEMBER_TYPE_DN; + } + if ($mode == 2) { + $dn = $conf->global->LDAP_KEY_MEMBERS_TYPES."=".$info[$conf->global->LDAP_KEY_MEMBERS_TYPES]; + } return $dn; } @@ -695,11 +725,15 @@ class AdherentType extends CommonObject $info["objectclass"] = explode(',', $conf->global->LDAP_MEMBER_TYPE_OBJECT_CLASS); // Champs - if ($this->label && !empty($conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME)) $info[$conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME] = $this->label; - if ($this->note && !empty($conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note, 0, 'UTF-8', 1); + if ($this->label && !empty($conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME)) { + $info[$conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME] = $this->label; + } + if ($this->note && !empty($conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION)) { + $info[$conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note, 0, 'UTF-8', 1); + } if (!empty($conf->global->LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS)) { $valueofldapfield = array(); - foreach ($this->members as $key=>$val) { // This is array of users for group into dolibarr database. + foreach ($this->members as $key => $val) { // This is array of users for group into dolibarr database. $member = new Adherent($this->db); $member->fetch($val->id, '', '', '', false, false); $info2 = $member->_load_ldap_info(); diff --git a/htdocs/adherents/class/api_members.class.php b/htdocs/adherents/class/api_members.class.php index 6fa3058dca1..277d2798bb7 100644 --- a/htdocs/adherents/class/api_members.class.php +++ b/htdocs/adherents/class/api_members.class.php @@ -36,7 +36,7 @@ class Members extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'morphy', 'typeid' ); @@ -325,7 +325,9 @@ class Members extends DolibarrApi } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } // Process the status separately because it must be updated using // the validate() and resiliate() methods of the class Adherent. if ($field == 'statut') { @@ -399,8 +401,9 @@ class Members extends DolibarrApi { $member = array(); foreach (Members::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $member[$field] = $data[$field]; } return $member; diff --git a/htdocs/adherents/class/api_memberstypes.class.php b/htdocs/adherents/class/api_memberstypes.class.php index f9f410f34aa..fbf9150be68 100644 --- a/htdocs/adherents/class/api_memberstypes.class.php +++ b/htdocs/adherents/class/api_memberstypes.class.php @@ -30,7 +30,7 @@ class MembersTypes extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'label', ); @@ -190,7 +190,9 @@ class MembersTypes extends DolibarrApi } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } // Process the status separately because it must be updated using // the validate() and resiliate() methods of the class AdherentType. $membertype->$field = $value; @@ -250,8 +252,9 @@ class MembersTypes extends DolibarrApi { $membertype = array(); foreach (MembersTypes::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $membertype[$field] = $data[$field]; } return $membertype; diff --git a/htdocs/adherents/class/api_subscriptions.class.php b/htdocs/adherents/class/api_subscriptions.class.php index 04b9f750a88..3758885c4a3 100644 --- a/htdocs/adherents/class/api_subscriptions.class.php +++ b/htdocs/adherents/class/api_subscriptions.class.php @@ -30,7 +30,7 @@ class Subscriptions extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'fk_adherent', 'dateh', 'datef', diff --git a/htdocs/adherents/class/subscription.class.php b/htdocs/adherents/class/subscription.class.php index dff127d6d2b..65b01991100 100644 --- a/htdocs/adherents/class/subscription.class.php +++ b/htdocs/adherents/class/subscription.class.php @@ -417,7 +417,7 @@ class Subscription extends CommonObject $label .= '
'.$langs->trans('DateEnd').': '.dol_print_date($this->datef, 'day'); } - $url = DOL_URL_ROOT.'/adherents/subscription/card.php?rowid='.$this->id; + $url = DOL_URL_ROOT.'/adherents/subscription/card.php?rowid='.((int) $this->id); if ($option != 'nolink') { // Add param to save lastsearch_values or not @@ -483,7 +483,7 @@ class Subscription extends CommonObject $sql = 'SELECT c.rowid, c.datec,'; $sql .= ' c.tms as datem'; $sql .= ' FROM '.MAIN_DB_PREFIX.'subscription as c'; - $sql .= ' WHERE c.rowid = '.$id; + $sql .= ' WHERE c.rowid = '.((int) $id); $result = $this->db->query($sql); if ($result) { diff --git a/htdocs/adherents/document.php b/htdocs/adherents/document.php index 35ce841ba6e..349cf5e7b75 100644 --- a/htdocs/adherents/document.php +++ b/htdocs/adherents/document.php @@ -50,12 +50,18 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} $form = new Form($db); @@ -96,8 +102,9 @@ if ($id > 0) { $totalsize += $file['size']; } - if (!empty($conf->notification->enabled)) + if (!empty($conf->notification->enabled)) { $langs->load("mails"); + } $head = member_prepare_head($object); @@ -125,8 +132,8 @@ if ($id > 0) { // Morphy print ''.$langs->trans("MemberNature").''.$object->getmorphylib().''; /*print ''; - print $form->showphoto('memberphoto',$object); - print '';*/ + print $form->showphoto('memberphoto',$object); + print '';*/ print ''; // Company diff --git a/htdocs/adherents/htpasswd.php b/htdocs/adherents/htpasswd.php index fc9b2eaf7f9..a1c105bd192 100644 --- a/htdocs/adherents/htpasswd.php +++ b/htdocs/adherents/htpasswd.php @@ -27,7 +27,9 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; // Security check -if (!$user->rights->adherent->export) accessforbidden(); +if (!$user->rights->adherent->export) { + accessforbidden(); +} /* @@ -38,8 +40,12 @@ llxHeader(); $now = dol_now(); -if (empty($sortorder)) { $sortorder = "ASC"; } -if (empty($sortfield)) { $sortfield = "d.login"; } +if (empty($sortorder)) { + $sortorder = "ASC"; +} +if (empty($sortfield)) { + $sortfield = "d.login"; +} if (!isset($statut)) { $statut = 1; } diff --git a/htdocs/adherents/index.php b/htdocs/adherents/index.php index 192c6f97a45..4a4724593e4 100644 --- a/htdocs/adherents/index.php +++ b/htdocs/adherents/index.php @@ -4,6 +4,7 @@ * Copyright (C) 2004-2020 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2019 Nicolas ZABOURI + * Copyright (C) 2021 Frédéric France * * 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 @@ -29,6 +30,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; $hookmanager = new HookManager($db); @@ -42,22 +44,45 @@ $langs->loadLangs(array("companies", "members")); $result = restrictedArea($user, 'adherent'); +/* + * Actions + */ + +if (GETPOST('addbox')) { + // Add box (when submit is done from a form when ajax disabled) + require_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php'; + $zone = GETPOST('areacode', 'aZ09'); + $userid = GETPOST('userid', 'int'); + $boxorder = GETPOST('boxorder', 'aZ09'); + $boxorder .= GETPOST('boxcombo', 'aZ09'); + $result = InfoBox::saveboxorder($db, $zone, $boxorder, $userid); + if ($result > 0) { + setEventMessages($langs->trans("BoxAdded"), null); + } +} + + /* * View */ +$form = new Form($db); + +// Load $resultboxes (selectboxlist + boxactivated + boxlista + boxlistb) +$resultboxes = FormOther::getBoxesArea($user, "2"); + llxHeader('', $langs->trans("Members"), 'EN:Module_Foundations|FR:Module_Adhérents|ES:Módulo_Miembros'); $staticmember = new Adherent($db); $statictype = new AdherentType($db); $subscriptionstatic = new Subscription($db); -print load_fiche_titre($langs->trans("MembersArea"), '', 'member'); +print load_fiche_titre($langs->trans("MembersArea"), $resultboxes['selectboxlist'], 'members'); -$Adherents = array(); -$AdherentsAValider = array(); -$MemberUpToDate = array(); -$AdherentsResilies = array(); +$MembersValidated = array(); +$MembersToValidate = array(); +$MembersUpToDate = array(); +$MembersResiliated = array(); $AdherentType = array(); @@ -86,7 +111,7 @@ if ($result) { $AdherentType[$objp->rowid] = $adhtype; if ($objp->statut == -1) { - $MemberToValidate[$objp->rowid] = $objp->somme; + $MembersToValidate[$objp->rowid] = $objp->somme; } if ($objp->statut == 1) { $MembersValidated[$objp->rowid] = $objp->somme; @@ -119,16 +144,13 @@ if ($result) { $i = 0; while ($i < $num) { $objp = $db->fetch_object($result); - $MemberUpToDate[$objp->fk_adherent_type] = $objp->somme; + $MembersUpToDate[$objp->fk_adherent_type] = $objp->somme; $i++; } $db->free(); } - -print '
'; - - +$searchbox = ''; if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo // Search contact/address if (!empty($conf->adherent->enabled) && $user->rights->adherent->lire) { @@ -136,27 +158,27 @@ if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is usel } if (count($listofsearchfields)) { - print '
'; - print ''; - print '
'; - print ''; + $searchbox .=''; + $searchbox .=''; + $searchbox .='
'; + $searchbox .='
'; $i = 0; foreach ($listofsearchfields as $key => $value) { if ($i == 0) { - print ''; + $searchbox .=''; } - print ''; - print ''; + $searchbox .=''; + $searchbox .=''; if ($i == 0) { - print ''; + $searchbox .=''; } - print ''; + $searchbox .=''; $i++; } - print '
'.$langs->trans("Search").'
'.$langs->trans("Search").'
:
:
'; - print '
'; - print '
'; - print '
'; + $searchbox .=''; + $searchbox .='
'; + $searchbox .=''; + $searchbox .='
'; } } @@ -164,28 +186,29 @@ if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is usel /* * Statistics */ - +$boxgraph = ''; if ($conf->use_javascript_ajax) { - print '
'; - print ''; - print ''; - print ''; + $boxgraph .= ''; + $boxgraph .= '
'.$langs->trans("Statistics").'
'; + $boxgraph .='
'; + $boxgraph .=''; + $boxgraph .=''; + $boxgraph .=''; - print ''; - print '
'.$langs->trans("Statistics").'
'; $SommeA = 0; $SommeB = 0; + $SommeC = 0; $SommeD = 0; $total = 0; $dataval = array(); $i = 0; foreach ($AdherentType as $key => $adhtype) { - $dataval['draft'][] = array($i, isset($MemberToValidate[$key]) ? $MemberToValidate[$key] : 0); - $dataval['notuptodate'][] = array($i, isset($MembersValidated[$key]) ? $MembersValidated[$key] - (isset($MemberUpToDate[$key]) ? $MemberUpToDate[$key] : 0) : 0); - $dataval['uptodate'][] = array($i, isset($MemberUpToDate[$key]) ? $MemberUpToDate[$key] : 0); + $dataval['draft'][] = array($i, isset($MembersToValidate[$key]) ? $MembersToValidate[$key] : 0); + $dataval['notuptodate'][] = array($i, isset($MembersValidated[$key]) ? $MembersValidated[$key] - (isset($MembersUpToDate[$key]) ? $MembersUpToDate[$key] : 0) : 0); + $dataval['uptodate'][] = array($i, isset($MembersUpToDate[$key]) ? $MembersUpToDate[$key] : 0); $dataval['resiliated'][] = array($i, isset($MembersResiliated[$key]) ? $MembersResiliated[$key] : 0); - $SommeA += isset($MemberToValidate[$key]) ? $MemberToValidate[$key] : 0; - $SommeB += isset($MembersValidated[$key]) ? $MembersValidated[$key] - (isset($MemberUpToDate[$key]) ? $MemberUpToDate[$key] : 0) : 0; - $SommeC += isset($MemberUpToDate[$key]) ? $MemberUpToDate[$key] : 0; + $SommeA += isset($MembersToValidate[$key]) ? $MembersToValidate[$key] : 0; + $SommeB += isset($MembersValidated[$key]) ? $MembersValidated[$key] - (isset($MembersUpToDate[$key]) ? $MembersUpToDate[$key] : 0) : 0; + $SommeC += isset($MembersUpToDate[$key]) ? $MembersUpToDate[$key] : 0; $SommeD += isset($MembersResiliated[$key]) ? $MembersResiliated[$key] : 0; $i++; } @@ -196,7 +219,7 @@ if ($conf->use_javascript_ajax) { $dataseries[] = array($langs->transnoentitiesnoconv("MembersStatusResiliated"), round($SommeD)); $dataseries[] = array($langs->transnoentitiesnoconv("MembersStatusToValid"), round($SommeA)); - include_once DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php'; + include DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php'; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; $dolgraph = new DolGraph(); @@ -207,17 +230,26 @@ if ($conf->use_javascript_ajax) { $dolgraph->SetType(array('pie')); $dolgraph->setHeight('200'); $dolgraph->draw('idgraphstatus'); - print $dolgraph->show($total ? 0 : 1); + $boxgraph .=$dolgraph->show($total ? 0 : 1); - print '
'.$langs->trans("Total").''; - print $SommeA + $SommeB + $SommeC + $SommeD; - print '
'; - print '
'; + $boxgraph .= '
'.$langs->trans("Total").''; + $boxgraph .= $SommeA + $SommeB + $SommeC + $SommeD; + $boxgraph .= '
'; + $boxgraph .= '
'; + $boxgraph .= '
'; } -print '
'; +// boxes +print '
'; +print '
'; + +print '
'; + +print '
'; +print $searchbox; +print $boxgraph; // List of subscription by year $Total = array(); @@ -284,17 +316,21 @@ print ''.price($tot).""; print "".price(price2num($numb > 0 ? ($tot / $numb) : 0, 'MT')).""; print "\n"; print "
"; + print "
\n"; +print $resultboxes['boxlista']; -print '
'; +print '
'."\n"; + +print '
'; /* * Latest modified members */ $max = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; -$sql = "SELECT a.rowid, a.ref, a.statut as status, a.lastname, a.firstname, a.societe as company, a.fk_soc,"; +$sql = "SELECT a.rowid, a.statut as status, a.lastname, a.firstname, a.societe as company, a.fk_soc,"; $sql .= " a.gender, a.email, a.photo, a.morphy,"; $sql .= " a.tms as datem, a.datefin as date_end_subscription,"; $sql .= " ta.rowid as typeid, ta.libelle as label, ta.subscription as need_subscription"; @@ -318,7 +354,7 @@ if ($resql) { $obj = $db->fetch_object($resql); $staticmember->id = $obj->rowid; - $staticmember->ref = $obj->ref; + $staticmember->ref = $obj->rowid; $staticmember->lastname = $obj->lastname; $staticmember->firstname = $obj->firstname; $staticmember->gender = $obj->gender; @@ -440,9 +476,9 @@ print "\n"; foreach ($AdherentType as $key => $adhtype) { print ''; print ''.$adhtype->getNomUrl(1, dol_size(32)).''; - print ''.(isset($MemberToValidate[$key]) && $MemberToValidate[$key] > 0 ? $MemberToValidate[$key] : '').' '.$staticmember->LibStatut(-1, $adhtype->subscription, 0, 3).''; - print ''.(isset($MembersValidated[$key]) && ($MembersValidated[$key] - (isset($MemberUpToDate[$key]) ? $MemberUpToDate[$key] : 0) > 0) ? $MembersValidated[$key] - (isset($MemberUpToDate[$key]) ? $MemberUpToDate[$key] : 0) : '').' '.$staticmember->LibStatut(1, $adhtype->subscription, 0, 3).''; - print ''.(isset($MemberUpToDate[$key]) && $MemberUpToDate[$key] > 0 ? $MemberUpToDate[$key] : '').' '.$staticmember->LibStatut(1, $adhtype->subscription, $now, 3).''; + print ''.(isset($MembersToValidate[$key]) && $MembersToValidate[$key] > 0 ? $MembersToValidate[$key] : '').' '.$staticmember->LibStatut(-1, $adhtype->subscription, 0, 3).''; + print ''.(isset($MembersValidated[$key]) && ($MembersValidated[$key] - (isset($MembersUpToDate[$key]) ? $MembersUpToDate[$key] : 0) > 0) ? $MembersValidated[$key] - (isset($MembersUpToDate[$key]) ? $MembersUpToDate[$key] : 0) : '').' '.$staticmember->LibStatut(1, $adhtype->subscription, 0, 3).''; + print ''.(isset($MembersUpToDate[$key]) && $MembersUpToDate[$key] > 0 ? $MembersUpToDate[$key] : '').' '.$staticmember->LibStatut(1, $adhtype->subscription, $now, 3).''; print ''.(isset($MembersResiliated[$key]) && $MembersResiliated[$key] > 0 ? $MembersResiliated[$key] : '').' '.$staticmember->LibStatut(0, $adhtype->subscription, 0, 3).''; print "\n"; } @@ -457,7 +493,14 @@ print ''; print "\n"; print "
"; -print '
'; +print '
'; + +print $resultboxes['boxlistb']; + +print ''."\n"; + +print ''; +print ''; $parameters = array('user' => $user); $reshook = $hookmanager->executeHooks('dashboardMembers', $parameters, $object); // Note that $action and $object may have been modified by hook diff --git a/htdocs/adherents/ldap.php b/htdocs/adherents/ldap.php index 6be535b6e3b..843ca08a5df 100644 --- a/htdocs/adherents/ldap.php +++ b/htdocs/adherents/ldap.php @@ -142,7 +142,9 @@ if (!empty($conf->global->LDAP_MEMBER_ACTIVE) && $conf->global->LDAP_MEMBER_ACTI print "\n"; -if (!empty($conf->global->LDAP_MEMBER_ACTIVE) && $conf->global->LDAP_MEMBER_ACTIVE != 'ldap2dolibarr') print "
\n"; +if (!empty($conf->global->LDAP_MEMBER_ACTIVE) && $conf->global->LDAP_MEMBER_ACTIVE != 'ldap2dolibarr') { + print "
\n"; +} diff --git a/htdocs/adherents/list.php b/htdocs/adherents/list.php index 704f484f38a..c37e9e325cf 100644 --- a/htdocs/adherents/list.php +++ b/htdocs/adherents/list.php @@ -69,24 +69,36 @@ $catid = GETPOST("catid", 'int'); $optioncss = GETPOST('optioncss', 'alpha'); $filter = GETPOST("filter", 'alpha'); -if ($filter) $search_filter = $filter; // For backward compatibility +if ($filter) { + $search_filter = $filter; // For backward compatibility +} $statut = GETPOST("statut", 'alpha'); -if ($statut != '') $search_status = $statut; // For backward compatibility +if ($statut != '') { + $search_status = $statut; // For backward compatibility +} $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); -if ($search_status < -1) $search_status = ''; +if ($search_status < -1) { + $search_status = ''; +} $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortorder) { $sortorder = ($filter == 'outofdate' ? "DESC" : "ASC"); } -if (!$sortfield) { $sortfield = ($filter == 'outofdate' ? "d.datefin" : "d.lastname"); } +if (!$sortorder) { + $sortorder = ($filter == 'outofdate' ? "DESC" : "ASC"); +} +if (!$sortfield) { + $sortfield = ($filter == 'outofdate' ? "d.datefin" : "d.lastname"); +} $object = new Adherent($db); @@ -117,7 +129,9 @@ $fieldstosearchall = array( 'd.note_public'=>'NotePublic', 'd.note_private'=>'NotePrivate', ); -if ($db->type == 'pgsql') unset($fieldstosearchall['d.rowid']); +if ($db->type == 'pgsql') { + unset($fieldstosearchall['d.rowid']); +} $arrayfields = array( 'd.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), 'd.civility'=>array('label'=>$langs->trans("Civility"), 'checked'=>0), @@ -153,12 +167,18 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { + $massaction = ''; +} $parameters = array('socid'=>$socid); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} if (empty($reshook)) { // Selection of new fields @@ -212,7 +232,9 @@ if (empty($reshook)) { if ($result < 0 && !count($tmpmember->errors)) { setEventMessages($tmpmember->error, $tmpmember->errors, 'errors'); } else { - if ($result > 0) $nbclose++; + if ($result > 0) { + $nbclose++; + } } } @@ -256,8 +278,11 @@ $sql .= " s.nom,"; $sql .= " t.libelle as type, t.subscription,"; $sql .= " state.code_departement as state_code, state.nom as state_name,"; // Add fields from extrafields -if (!empty($extrafields->attributes[$object->table_element]['label'])) - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); +if (!empty($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); + } +} // Add fields from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook @@ -276,16 +301,34 @@ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on (s.rowid = d.fk_soc)"; $sql .= ", ".MAIN_DB_PREFIX."adherent_type as t"; $sql .= " WHERE d.fk_adherent_type = t.rowid "; -if ($catid > 0) $sql .= " AND cm.fk_categorie = ".$db->escape($catid); -if ($catid == -2) $sql .= " AND cm.fk_categorie IS NULL"; -if ($search_categ > 0) $sql .= " AND cm.fk_categorie = ".$db->escape($search_categ); -if ($search_categ == -2) $sql .= " AND cm.fk_categorie IS NULL"; +if ($catid > 0) { + $sql .= " AND cm.fk_categorie = ".$db->escape($catid); +} +if ($catid == -2) { + $sql .= " AND cm.fk_categorie IS NULL"; +} +if ($search_categ > 0) { + $sql .= " AND cm.fk_categorie = ".$db->escape($search_categ); +} +if ($search_categ == -2) { + $sql .= " AND cm.fk_categorie IS NULL"; +} $sql .= " AND d.entity IN (".getEntity('adherent').")"; -if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); -if ($search_type > 0) $sql .= " AND t.rowid=".$db->escape($search_type); -if ($search_filter == 'withoutsubscription') $sql .= " AND (datefin IS NULL OR t.subscription = 0)"; -if ($search_filter == 'uptodate') $sql .= " AND (datefin >= '".$db->idate($now)."' OR t.subscription = 0)"; -if ($search_filter == 'outofdate') $sql .= " AND (datefin < '".$db->idate($now)."' AND t.subscription = 1)"; +if ($sall) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} +if ($search_type > 0) { + $sql .= " AND t.rowid=".$db->escape($search_type); +} +if ($search_filter == 'withoutsubscription') { + $sql .= " AND (datefin IS NULL OR t.subscription = 0)"; +} +if ($search_filter == 'uptodate') { + $sql .= " AND (datefin >= '".$db->idate($now)."' OR t.subscription = 0)"; +} +if ($search_filter == 'outofdate') { + $sql .= " AND (datefin < '".$db->idate($now)."' AND t.subscription = 1)"; +} if ($search_status != '') { // Peut valoir un nombre ou liste de nombre separes par virgules $sql .= " AND d.statut in (".$db->sanitize($db->escape($search_status)).")"; @@ -293,21 +336,51 @@ if ($search_status != '') { if ($search_ref) { $sql .= natural_search("d.ref", $search_ref); } -if ($search_civility) $sql .= natural_search("d.civility", $search_civility); -if ($search_firstname) $sql .= natural_search("d.firstname", $search_firstname); -if ($search_lastname) $sql .= natural_search(array("d.firstname", "d.lastname", "d.societe"), $search_lastname); -if ($search_gender != '' && $search_gender != '-1') $sql .= natural_search("d.gender", $search_gender); -if ($search_login) $sql .= natural_search("d.login", $search_login); -if ($search_company) $sql .= natural_search("s.nom", $search_company); -if ($search_email) $sql .= natural_search("d.email", $search_email); -if ($search_address) $sql .= natural_search("d.address", $search_address); -if ($search_town) $sql .= natural_search("d.town", $search_town); -if ($search_zip) $sql .= natural_search("d.zip", $search_zip); -if ($search_state) $sql .= natural_search("state.nom", $search_state); -if ($search_phone) $sql .= natural_search("d.phone", $search_phone); -if ($search_phone_perso) $sql .= natural_search("d.phone_perso", $search_phone_perso); -if ($search_phone_mobile) $sql .= natural_search("d.phone_mobile", $search_phone_mobile); -if ($search_country) $sql .= " AND d.country IN (".$search_country.')'; +if ($search_civility) { + $sql .= natural_search("d.civility", $search_civility); +} +if ($search_firstname) { + $sql .= natural_search("d.firstname", $search_firstname); +} +if ($search_lastname) { + $sql .= natural_search(array("d.firstname", "d.lastname", "d.societe"), $search_lastname); +} +if ($search_gender != '' && $search_gender != '-1') { + $sql .= natural_search("d.gender", $search_gender); +} +if ($search_login) { + $sql .= natural_search("d.login", $search_login); +} +if ($search_company) { + $sql .= natural_search("s.nom", $search_company); +} +if ($search_email) { + $sql .= natural_search("d.email", $search_email); +} +if ($search_address) { + $sql .= natural_search("d.address", $search_address); +} +if ($search_town) { + $sql .= natural_search("d.town", $search_town); +} +if ($search_zip) { + $sql .= natural_search("d.zip", $search_zip); +} +if ($search_state) { + $sql .= natural_search("state.nom", $search_state); +} +if ($search_phone) { + $sql .= natural_search("d.phone", $search_phone); +} +if ($search_phone_perso) { + $sql .= natural_search("d.phone_perso", $search_phone_perso); +} +if ($search_phone_mobile) { + $sql .= natural_search("d.phone_mobile", $search_phone_mobile); +} +if ($search_country) { + $sql .= " AND d.country IN (".$search_country.')'; +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; @@ -323,8 +396,11 @@ $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $resql = $db->query($sql); - if ($resql) $nbtotalofrecords = $db->num_rows($resql); - else dol_print_error($db); + if ($resql) { + $nbtotalofrecords = $db->num_rows($resql); + } else { + dol_print_error($db); + } if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; @@ -355,13 +431,27 @@ llxHeader('', $langs->trans("Member"), 'EN:Module_Foundations|FR:Module_Adh&eacu $titre = $langs->trans("MembersList"); if (GETPOSTISSET("search_status")) { - if ($search_status == '-1,1') { $titre = $langs->trans("MembersListQualified"); } - if ($search_status == '-1') { $titre = $langs->trans("MembersListToValid"); } - if ($search_status == '1' && $filter == '') { $titre = $langs->trans("MembersValidated"); } - if ($search_status == '1' && $filter == 'withoutsubscription') { $titre = $langs->trans("MembersWithSubscriptionToReceive"); } - if ($search_status == '1' && $filter == 'uptodate') { $titre = $langs->trans("MembersListUpToDate"); } - if ($search_status == '1' && $filter == 'outofdate') { $titre = $langs->trans("MembersListNotUpToDate"); } - if ($search_status == '0') { $titre = $langs->trans("MembersListResiliated"); } + if ($search_status == '-1,1') { + $titre = $langs->trans("MembersListQualified"); + } + if ($search_status == '-1') { + $titre = $langs->trans("MembersListToValid"); + } + if ($search_status == '1' && $filter == '') { + $titre = $langs->trans("MembersValidated"); + } + if ($search_status == '1' && $filter == 'withoutsubscription') { + $titre = $langs->trans("MembersWithSubscriptionToReceive"); + } + if ($search_status == '1' && $filter == 'uptodate') { + $titre = $langs->trans("MembersListUpToDate"); + } + if ($search_status == '1' && $filter == 'outofdate') { + $titre = $langs->trans("MembersListNotUpToDate"); + } + if ($search_status == '0') { + $titre = $langs->trans("MembersListResiliated"); + } } elseif ($action == 'search') { $titre = $langs->trans("MembersListQualified"); } @@ -373,30 +463,78 @@ if ($search_type > 0) { } $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -if ($sall != "") $param .= "&sall=".urlencode($sall); -if ($search_ref) $param .= "&search_ref=".urlencode($search_ref); -if ($search_civility) $param .= "&search_civility=".urlencode($search_civility); -if ($search_firstname) $param .= "&search_firstname=".urlencode($search_firstname); -if ($search_lastname) $param .= "&search_lastname=".urlencode($search_lastname); -if ($search_gender) $param .= "&search_gender=".urlencode($search_gender); -if ($search_login) $param .= "&search_login=".urlencode($search_login); -if ($search_email) $param .= "&search_email=".urlencode($search_email); -if ($search_categ) $param .= "&search_categ=".urlencode($search_categ); -if ($search_company) $param .= "&search_company=".urlencode($search_company); -if ($search_address != '') $param .= "&search_address=".urlencode($search_address); -if ($search_town != '') $param .= "&search_town=".urlencode($search_town); -if ($search_zip != '') $param .= "&search_zip=".urlencode($search_zip); -if ($search_state != '') $param .= "&search_state=".urlencode($search_state); -if ($search_country != '') $param .= "&search_country=".urlencode($search_country); -if ($search_phone != '') $param .= "&search_phone=".urlencode($search_phone); -if ($search_phone_perso != '') $param .= "&search_phone_perso=".urlencode($search_phone_perso); -if ($search_phone_mobile != '') $param .= "&search_phone_mobile=".urlencode($search_phone_mobile); -if ($search_filter && $search_filter != '-1') $param .= "&search_filter=".urlencode($search_filter); -if ($search_status != "" && $search_status != '-1') $param .= "&search_status=".urlencode($search_status); -if ($search_type > 0) $param .= "&search_type=".urlencode($search_type); -if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +if ($sall != "") { + $param .= "&sall=".urlencode($sall); +} +if ($search_ref) { + $param .= "&search_ref=".urlencode($search_ref); +} +if ($search_civility) { + $param .= "&search_civility=".urlencode($search_civility); +} +if ($search_firstname) { + $param .= "&search_firstname=".urlencode($search_firstname); +} +if ($search_lastname) { + $param .= "&search_lastname=".urlencode($search_lastname); +} +if ($search_gender) { + $param .= "&search_gender=".urlencode($search_gender); +} +if ($search_login) { + $param .= "&search_login=".urlencode($search_login); +} +if ($search_email) { + $param .= "&search_email=".urlencode($search_email); +} +if ($search_categ) { + $param .= "&search_categ=".urlencode($search_categ); +} +if ($search_company) { + $param .= "&search_company=".urlencode($search_company); +} +if ($search_address != '') { + $param .= "&search_address=".urlencode($search_address); +} +if ($search_town != '') { + $param .= "&search_town=".urlencode($search_town); +} +if ($search_zip != '') { + $param .= "&search_zip=".urlencode($search_zip); +} +if ($search_state != '') { + $param .= "&search_state=".urlencode($search_state); +} +if ($search_country != '') { + $param .= "&search_country=".urlencode($search_country); +} +if ($search_phone != '') { + $param .= "&search_phone=".urlencode($search_phone); +} +if ($search_phone_perso != '') { + $param .= "&search_phone_perso=".urlencode($search_phone_perso); +} +if ($search_phone_mobile != '') { + $param .= "&search_phone_mobile=".urlencode($search_phone_mobile); +} +if ($search_filter && $search_filter != '-1') { + $param .= "&search_filter=".urlencode($search_filter); +} +if ($search_status != "" && $search_status != '-1') { + $param .= "&search_status=".urlencode($search_status); +} +if ($search_type > 0) { + $param .= "&search_type=".urlencode($search_type); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -405,10 +543,18 @@ $arrayofmassactions = array( //'presend'=>$langs->trans("SendByMail"), //'builddoc'=>$langs->trans("PDFMerge"), ); -if ($user->rights->adherent->creer) $arrayofmassactions['close'] = $langs->trans("Resiliate"); -if ($user->rights->adherent->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); -if ($user->rights->societe->creer) $arrayofmassactions['preaffecttag'] = ''.$langs->trans("AffectTag"); -if (in_array($massaction, array('presend', 'predelete','preaffecttag'))) $arrayofmassactions = array(); +if ($user->rights->adherent->creer) { + $arrayofmassactions['close'] = $langs->trans("Resiliate"); +} +if ($user->rights->adherent->supprimer) { + $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); +} +if ($user->rights->societe->creer) { + $arrayofmassactions['preaffecttag'] = ''.$langs->trans("AffectTag"); +} +if (in_array($massaction, array('presend', 'predelete','preaffecttag'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $newcardbutton = ''; @@ -417,7 +563,9 @@ if ($user->rights->adherent->creer) { } print '
'; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -434,7 +582,9 @@ $trackid = 'mem'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($sall) { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
'; } @@ -448,8 +598,11 @@ if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { } $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook -if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; -else $moreforfilter = $hookmanager->resPrint; +if (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; +} else { + $moreforfilter = $hookmanager->resPrint; +} if (!empty($moreforfilter)) { print '
'; print $moreforfilter; @@ -458,7 +611,9 @@ if (!empty($moreforfilter)) { $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); +if ($massactionbutton) { + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); +} print '
'; print ''."\n"; @@ -609,26 +764,66 @@ print ''; print "\n"; print ''; -if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) print_liste_field_titre("ID", $_SERVER["PHP_SELF"], '', '', $param, 'align="center"', $sortfield, $sortorder); -if (!empty($arrayfields['d.ref']['checked'])) print_liste_field_titre($arrayfields['d.ref']['label'], $_SERVER["PHP_SELF"], 'd.ref', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['d.civility']['checked'])) print_liste_field_titre($arrayfields['d.civility']['label'], $_SERVER["PHP_SELF"], 'd.civility', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['d.firstname']['checked'])) print_liste_field_titre($arrayfields['d.firstname']['label'], $_SERVER["PHP_SELF"], 'd.firstname', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['d.lastname']['checked'])) print_liste_field_titre($arrayfields['d.lastname']['label'], $_SERVER["PHP_SELF"], 'd.lastname', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['d.gender']['checked'])) print_liste_field_titre($arrayfields['d.gender']['label'], $_SERVER['PHP_SELF'], 'd.gender', $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['d.company']['checked'])) print_liste_field_titre($arrayfields['d.company']['label'], $_SERVER["PHP_SELF"], 'd.societe', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['d.login']['checked'])) print_liste_field_titre($arrayfields['d.login']['label'], $_SERVER["PHP_SELF"], 'd.login', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['d.morphy']['checked'])) print_liste_field_titre($arrayfields['d.morphy']['label'], $_SERVER["PHP_SELF"], 'd.morphy', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['t.libelle']['checked'])) print_liste_field_titre($arrayfields['t.libelle']['label'], $_SERVER["PHP_SELF"], 't.libelle', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['d.address']['checked'])) print_liste_field_titre($arrayfields['d.address']['label'], $_SERVER["PHP_SELF"], 'd.address', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['d.zip']['checked'])) print_liste_field_titre($arrayfields['d.zip']['label'], $_SERVER["PHP_SELF"], 'd.zip', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['d.town']['checked'])) print_liste_field_titre($arrayfields['d.town']['label'], $_SERVER["PHP_SELF"], 'd.town', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, 'align="center"', $sortfield, $sortorder); -if (!empty($arrayfields['d.phone']['checked'])) print_liste_field_titre($arrayfields['d.phone']['label'], $_SERVER["PHP_SELF"], 'd.phone', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['d.phone_perso']['checked'])) print_liste_field_titre($arrayfields['d.phone_perso']['label'], $_SERVER["PHP_SELF"], 'd.phone_perso', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['d.phone_mobile']['checked'])) print_liste_field_titre($arrayfields['d.phone_mobile']['label'], $_SERVER["PHP_SELF"], 'd.phone_mobile', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['d.email']['checked'])) print_liste_field_titre($arrayfields['d.email']['label'], $_SERVER["PHP_SELF"], 'd.email', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['d.datefin']['checked'])) print_liste_field_titre($arrayfields['d.datefin']['label'], $_SERVER["PHP_SELF"], 'd.datefin', '', $param, 'align="center"', $sortfield, $sortorder); +if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) { + print_liste_field_titre("ID", $_SERVER["PHP_SELF"], '', '', $param, 'align="center"', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.ref']['checked'])) { + print_liste_field_titre($arrayfields['d.ref']['label'], $_SERVER["PHP_SELF"], 'd.ref', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.civility']['checked'])) { + print_liste_field_titre($arrayfields['d.civility']['label'], $_SERVER["PHP_SELF"], 'd.civility', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.firstname']['checked'])) { + print_liste_field_titre($arrayfields['d.firstname']['label'], $_SERVER["PHP_SELF"], 'd.firstname', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.lastname']['checked'])) { + print_liste_field_titre($arrayfields['d.lastname']['label'], $_SERVER["PHP_SELF"], 'd.lastname', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.gender']['checked'])) { + print_liste_field_titre($arrayfields['d.gender']['label'], $_SERVER['PHP_SELF'], 'd.gender', $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['d.company']['checked'])) { + print_liste_field_titre($arrayfields['d.company']['label'], $_SERVER["PHP_SELF"], 'd.societe', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.login']['checked'])) { + print_liste_field_titre($arrayfields['d.login']['label'], $_SERVER["PHP_SELF"], 'd.login', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.morphy']['checked'])) { + print_liste_field_titre($arrayfields['d.morphy']['label'], $_SERVER["PHP_SELF"], 'd.morphy', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['t.libelle']['checked'])) { + print_liste_field_titre($arrayfields['t.libelle']['label'], $_SERVER["PHP_SELF"], 't.libelle', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.address']['checked'])) { + print_liste_field_titre($arrayfields['d.address']['label'], $_SERVER["PHP_SELF"], 'd.address', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.zip']['checked'])) { + print_liste_field_titre($arrayfields['d.zip']['label'], $_SERVER["PHP_SELF"], 'd.zip', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.town']['checked'])) { + print_liste_field_titre($arrayfields['d.town']['label'], $_SERVER["PHP_SELF"], 'd.town', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['state.nom']['checked'])) { + print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['country.code_iso']['checked'])) { + print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, 'align="center"', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.phone']['checked'])) { + print_liste_field_titre($arrayfields['d.phone']['label'], $_SERVER["PHP_SELF"], 'd.phone', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.phone_perso']['checked'])) { + print_liste_field_titre($arrayfields['d.phone_perso']['label'], $_SERVER["PHP_SELF"], 'd.phone_perso', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.phone_mobile']['checked'])) { + print_liste_field_titre($arrayfields['d.phone_mobile']['label'], $_SERVER["PHP_SELF"], 'd.phone_mobile', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.email']['checked'])) { + print_liste_field_titre($arrayfields['d.email']['label'], $_SERVER["PHP_SELF"], 'd.email', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.datefin']['checked'])) { + print_liste_field_titre($arrayfields['d.datefin']['label'], $_SERVER["PHP_SELF"], 'd.datefin', '', $param, 'align="center"', $sortfield, $sortorder); +} // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; @@ -636,10 +831,18 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -if (!empty($arrayfields['d.datec']['checked'])) print_liste_field_titre($arrayfields['d.datec']['label'], $_SERVER["PHP_SELF"], "d.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); -if (!empty($arrayfields['d.birth']['checked'])) print_liste_field_titre($arrayfields['d.birth']['label'], $_SERVER["PHP_SELF"], "d.birth", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); -if (!empty($arrayfields['d.tms']['checked'])) print_liste_field_titre($arrayfields['d.tms']['label'], $_SERVER["PHP_SELF"], "d.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); -if (!empty($arrayfields['d.statut']['checked'])) print_liste_field_titre($arrayfields['d.statut']['label'], $_SERVER["PHP_SELF"], "d.statut", "", $param, 'class="right"', $sortfield, $sortorder); +if (!empty($arrayfields['d.datec']['checked'])) { + print_liste_field_titre($arrayfields['d.datec']['label'], $_SERVER["PHP_SELF"], "d.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.birth']['checked'])) { + print_liste_field_titre($arrayfields['d.birth']['label'], $_SERVER["PHP_SELF"], "d.birth", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.tms']['checked'])) { + print_liste_field_titre($arrayfields['d.tms']['label'], $_SERVER["PHP_SELF"], "d.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.statut']['checked'])) { + print_liste_field_titre($arrayfields['d.statut']['label'], $_SERVER["PHP_SELF"], "d.statut", "", $param, 'class="right"', $sortfield, $sortorder); +} print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); print "\n"; @@ -676,7 +879,9 @@ while ($i < min($num, $limit)) { if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID)) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Ref @@ -684,35 +889,47 @@ while ($i < min($num, $limit)) { print "\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Civility if (!empty($arrayfields['d.civility']['checked'])) { print "\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Firstname if (!empty($arrayfields['d.firstname']['checked'])) { print "\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Lastname if (!empty($arrayfields['d.lastname']['checked'])) { print "\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Gender if (!empty($arrayfields['d.gender']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Company if (!empty($arrayfields['d.company']['checked'])) { @@ -723,7 +940,9 @@ while ($i < min($num, $limit)) { // Login if (!empty($arrayfields['d.login']['checked'])) { print "\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Nature (Moral/Physical) if (!empty($arrayfields['d.morphy']['checked'])) { @@ -737,7 +956,9 @@ while ($i < min($num, $limit)) { } print $s; print "\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type label if (!empty($arrayfields['t.libelle']['checked'])) { @@ -746,33 +967,43 @@ while ($i < min($num, $limit)) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Address if (!empty($arrayfields['d.address']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Zip if (!empty($arrayfields['d.zip']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Town if (!empty($arrayfields['d.town']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // State if (!empty($arrayfields['state.nom']['checked'])) { print "\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Country if (!empty($arrayfields['country.code_iso']['checked'])) { @@ -780,28 +1011,36 @@ while ($i < min($num, $limit)) { $tmparray = getCountry($obj->country, 'all'); print $tmparray['label']; print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Phone pro if (!empty($arrayfields['d.phone']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Phone perso if (!empty($arrayfields['d.phone_perso']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Phone mobile if (!empty($arrayfields['d.phone_mobile']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // EMail if (!empty($arrayfields['d.email']['checked'])) { @@ -822,7 +1061,9 @@ while ($i < min($num, $limit)) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Birth if (!empty($arrayfields['d.birth']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification if (!empty($arrayfields['d.tms']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status if (!empty($arrayfields['d.statut']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "\n"; $i++; @@ -884,7 +1137,11 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found if ($num == 0) { $colspan = 1; - foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { + $colspan++; + } + } print ''; } diff --git a/htdocs/adherents/note.php b/htdocs/adherents/note.php index e611eb3bbcf..437a8c0c577 100644 --- a/htdocs/adherents/note.php +++ b/htdocs/adherents/note.php @@ -91,8 +91,8 @@ if ($id) { // Morphy print ''; /*print '';*/ + print $form->showphoto('memberphoto',$member); + print '';*/ print ''; // Company diff --git a/htdocs/adherents/stats/byproperties.php b/htdocs/adherents/stats/byproperties.php index b1c4844974e..9f8691a69a6 100644 --- a/htdocs/adherents/stats/byproperties.php +++ b/htdocs/adherents/stats/byproperties.php @@ -82,8 +82,12 @@ if ($resql) { while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj->code == 'phy') $foundphy++; - if ($obj->code == 'mor') $foundmor++; + if ($obj->code == 'phy') { + $foundphy++; + } + if ($obj->code == 'mor') { + $foundmor++; + } $data[$obj->code] = array('label'=>$obj->code, 'nb'=>$obj->nb, 'nbsubscriptions'=>$obj->nbsubscriptions, 'lastdate'=>$db->jdate($obj->lastdate), 'lastsubscriptiondate'=>$db->jdate($obj->lastsubscriptiondate)); @@ -113,8 +117,12 @@ if ($resql) { while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj->code == 'phy') $foundphy++; - if ($obj->code == 'mor') $foundmor++; + if ($obj->code == 'phy') { + $foundphy++; + } + if ($obj->code == 'mor') { + $foundmor++; + } $data[$obj->code]['nbactive'] = $obj->nb; @@ -152,8 +160,12 @@ print ''; print ''; print ''; -if (!$foundphy) $data[] = array('label'=>'phy', 'nb'=>'0', 'nbactive'=>'0', 'lastdate'=>'', 'lastsubscriptiondate'=>''); -if (!$foundmor) $data[] = array('label'=>'mor', 'nb'=>'0', 'nbactive'=>'0', 'lastdate'=>'', 'lastsubscriptiondate'=>''); +if (!$foundphy) { + $data[] = array('label'=>'phy', 'nb'=>'0', 'nbactive'=>'0', 'lastdate'=>'', 'lastsubscriptiondate'=>''); +} +if (!$foundmor) { + $data[] = array('label'=>'mor', 'nb'=>'0', 'nbactive'=>'0', 'lastdate'=>'', 'lastsubscriptiondate'=>''); +} foreach ($data as $val) { $nb = $val['nb']; diff --git a/htdocs/adherents/stats/geo.php b/htdocs/adherents/stats/geo.php index b2a2aa2ced5..6107669c967 100644 --- a/htdocs/adherents/stats/geo.php +++ b/htdocs/adherents/stats/geo.php @@ -56,13 +56,23 @@ $langs->loadLangs(array("companies", "members", "banks")); $memberstatic = new Adherent($db); $arrayjs = array('https://www.google.com/jsapi'); -if (!empty($conf->dol_use_jmobile)) $arrayjs = array(); +if (!empty($conf->dol_use_jmobile)) { + $arrayjs = array(); +} $title = $langs->trans("Statistics"); -if ($mode == 'memberbycountry') $title = $langs->trans("MembersStatisticsByCountries"); -if ($mode == 'memberbystate') $title = $langs->trans("MembersStatisticsByState"); -if ($mode == 'memberbytown') $title = $langs->trans("MembersStatisticsByTown"); -if ($mode == 'memberbyregion') $title = $langs->trans("MembersStatisticsByRegion"); +if ($mode == 'memberbycountry') { + $title = $langs->trans("MembersStatisticsByCountries"); +} +if ($mode == 'memberbystate') { + $title = $langs->trans("MembersStatisticsByState"); +} +if ($mode == 'memberbytown') { + $title = $langs->trans("MembersStatisticsByTown"); +} +if ($mode == 'memberbyregion') { + $title = $langs->trans("MembersStatisticsByRegion"); +} llxHeader('', $title, '', '', 0, 0, $arrayjs); @@ -207,11 +217,15 @@ if ($mode && !count($data)) { print $langs->trans("NoValidatedMemberYet").'
'; print '
'; } else { - if ($mode == 'memberbycountry') print ''.$langs->trans("MembersByCountryDesc").'
'; - elseif ($mode == 'memberbystate') print ''.$langs->trans("MembersByStateDesc").'
'; - elseif ($mode == 'memberbytown') print ''.$langs->trans("MembersByTownDesc").'
'; - elseif ($mode == 'memberbyregion') print ''.$langs->trans("MembersByRegion").'
'; //+ - else { + if ($mode == 'memberbycountry') { + print ''.$langs->trans("MembersByCountryDesc").'
'; + } elseif ($mode == 'memberbystate') { + print ''.$langs->trans("MembersByStateDesc").'
'; + } elseif ($mode == 'memberbytown') { + print ''.$langs->trans("MembersByTownDesc").'
'; + } elseif ($mode == 'memberbyregion') { + print ''.$langs->trans("MembersByRegion").'
'; //+ + } else { print ''.$langs->trans("MembersStatisticsDesc").'
'; print '
'; print ''.$langs->trans("MembersStatisticsByCountries").'
'; @@ -229,7 +243,9 @@ if ($mode && !count($data)) { // Show graphics if (count($arrayjs) && $mode == 'memberbycountry') { $color_file = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php'; - if (is_readable($color_file)) include_once $color_file; + if (is_readable($color_file)) { + include_once $color_file; + } // Assume we've already included the proper headers so just call our script inline // More doc: https://developers.google.com/chart/interactive/docs/gallery/geomap?hl=fr-FR @@ -248,11 +264,15 @@ if (count($arrayjs) && $mode == 'memberbycountry') { foreach ($data as $val) { $valcountry = strtoupper($val['code']); // Should be ISO-3166 code (faster) //$valcountry=ucfirst($val['label_en']); - if ($valcountry == 'Great Britain') { $valcountry = 'United Kingdom'; } // fix case of uk (when we use labels) + if ($valcountry == 'Great Britain') { + $valcountry = 'United Kingdom'; + } // fix case of uk (when we use labels) print "\tdata.setValue(".$i.", 0, \"".$valcountry."\");\n"; print "\tdata.setValue(".$i.", 1, ".$val['nb'].");\n"; // Google's Geomap only supports up to 400 entries - if ($i >= 400) { break; } + if ($i >= 400) { + break; + } $i++; } @@ -279,7 +299,9 @@ if ($mode) { print '
'.$obj->rowid.'"; print $memberstatic->getNomUrl(-1, 0, 'card', 'ref', '', -1, 0, 1); print ""; print $obj->civility; print ""; print $obj->firstname; print ""; print $obj->lastname; print "'; - if ($obj->gender) print $langs->trans("Gender".$obj->gender); + if ($obj->gender) { + print $langs->trans("Gender".$obj->gender); + } print '".$obj->login."'; print $membertypestatic->getNomUrl(1, 32); print ''; print $obj->address; print ''; print $obj->zip; print ''; print $obj->town; print '".$obj->state_name."'; print $obj->phone; print ''; print $obj->phone_perso; print ''; print $obj->phone_mobile; print ''; if ($obj->subscription == 'yes') { print $langs->trans("SubscriptionNotReceived"); - if ($obj->statut > 0) print " ".img_warning(); + if ($obj->statut > 0) { + print " ".img_warning(); + } } else { print ' '; } @@ -840,38 +1081,50 @@ while ($i < min($num, $limit)) { print ''; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print ''; print dol_print_date($db->jdate($obj->birth), 'day', 'tzuser'); print ''; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print ''; print $memberstatic->LibStatut($obj->statut, $obj->subscription, $datefin, 5); print ''; if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined $selected = 0; - if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + if (in_array($obj->rowid, $arrayofselected)) { + $selected = 1; + } print ''; } print '
'.$langs->trans("NoRecordFound").'
'.$langs->trans("MemberNature").''.$object->getmorphylib().''; - print $form->showphoto('memberphoto',$member); - print '
'.$langs->trans("NbOfSubscriptions").''.$langs->trans("LatestSubscriptionDate").'
'; print ''; print ''; - if ($label2) print ''; + if ($label2) { + print ''; + } print ''; print ''; print ''; @@ -289,7 +311,9 @@ if ($mode) { $year = $val['year']; print ''; print ''; - if ($label2) print ''; + if ($label2) { + print ''; + } print ''; print ''; print ''; diff --git a/htdocs/adherents/stats/index.php b/htdocs/adherents/stats/index.php index 123fb5333d5..b092c7bcf20 100644 --- a/htdocs/adherents/stats/index.php +++ b/htdocs/adherents/stats/index.php @@ -32,8 +32,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php'; $WIDTH = DolGraph::getDefaultGraphSizeForStats('width'); $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); -$userid = GETPOST('userid', 'int'); if ($userid < 0) $userid = 0; -$socid = GETPOST('socid', 'int'); if ($socid < 0) $socid = 0; +$userid = GETPOST('userid', 'int'); if ($userid < 0) { + $userid = 0; +} +$socid = GETPOST('socid', 'int'); if ($socid < 0) { + $socid = 0; +} // Security check if ($user->socid > 0) { @@ -209,7 +213,9 @@ print '
'; // Show graphs print '
'.$label.''.$label2.''.$label2.''.$langs->trans("NbOfMembers").' ('.$langs->trans("AllTime").')'.$langs->trans("LastMemberDate").''.$langs->trans("LatestSubscriptionDate").'
'.$val['label'].''.$val['label2'].''.$val['label2'].''.$val['nb'].''.dol_print_date($val['lastdate'], 'dayhour').''.dol_print_date($val['lastsubscriptiondate'], 'dayhour').'
'; } + // Date end subscription + print ''; + print '
'; -if ($mesg) { print $mesg; } else { +if ($mesg) { + print $mesg; +} else { print $px1->show(); print "
\n"; print $px2->show(); diff --git a/htdocs/adherents/subscription.php b/htdocs/adherents/subscription.php index e19f01779aa..b48328a17e8 100644 --- a/htdocs/adherents/subscription.php +++ b/htdocs/adherents/subscription.php @@ -50,14 +50,20 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; // Default sort order (if not yet defined by previous GETPOST) -if (!$sortfield) $sortfield = "c.rowid"; -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "c.rowid"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} // Security check @@ -150,7 +156,9 @@ if (empty($reshook) && $action == 'setuserid' && ($user->rights->user->self->cre if (!$error) { if ($_POST["userid"] != $object->user_id) { // If link differs from currently in database $result = $object->setUserId($_POST["userid"]); - if ($result < 0) dol_print_error('', $object->error); + if ($result < 0) { + dol_print_error('', $object->error); + } $_POST['action'] = ''; $action = ''; } @@ -178,7 +186,9 @@ if (empty($reshook) && $action == 'setsocid') { if (!$error) { $result = $object->setThirdPartyId(GETPOST('socid', 'int')); - if ($result < 0) dol_print_error('', $object->error); + if ($result < 0) { + dol_print_error('', $object->error); + } $_POST['action'] = ''; $action = ''; } @@ -423,25 +433,37 @@ llxHeader("", $title, $helpurl); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} $param .= '&id='.$rowid; -if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} // Add $param from extra fields //include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; if ($rowid > 0) { $res = $object->fetch($rowid); - if ($res < 0) { dol_print_error($db, $object->error); exit; } + if ($res < 0) { + dol_print_error($db, $object->error); exit; + } $adht->fetch($object->typeid); $head = member_prepare_head($object); $rowspan = 10; - if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) $rowspan++; - if (!empty($conf->societe->enabled)) $rowspan++; + if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { + $rowspan++; + } + if (!empty($conf->societe->enabled)) { + $rowspan++; + } print ''; print ''; @@ -481,6 +503,15 @@ if ($rowid > 0) { // Password if (empty($conf->global->ADHERENT_LOGIN_NOT_REQUIRED)) { print '
'.$langs->trans("Password").''.preg_replace('/./i', '*', $object->pass); + if ($object->pass) { + print preg_replace('/./i', '*', $object->pass); + } else { + if ($user->admin) { + print $langs->trans("Crypted").': '.$object->pass_indatabase_crypted; + } else { + print $langs->trans("Hidden"); + } + } if ((!empty($object->pass) || !empty($object->pass_crypted)) && empty($object->user_id)) { $langs->load("errors"); $htmltext = $langs->trans("WarningPasswordSetWithNoAccount"); @@ -489,6 +520,28 @@ if ($rowid > 0) { print '
'.$langs->trans("SubscriptionEndDate").''; + if ($object->datefin) { + print dol_print_date($object->datefin, 'day'); + if ($object->hasDelay()) { + print " ".img_warning($langs->trans("Late")); + } + } else { + if (!$adht->subscription) { + print $langs->trans("SubscriptionNotRecorded"); + if ($object->statut > 0) { + print " ".img_warning($langs->trans("Late")); // Display a delay picto only if it is not a draft and is not canceled + } + } else { + print $langs->trans("SubscriptionNotReceived"); + if ($object->statut > 0) { + print " ".img_warning($langs->trans("Late")); // Display a delay picto only if it is not a draft and is not canceled + } + } + } + print '
'; print '
'; @@ -498,7 +551,7 @@ if ($rowid > 0) { print ''; // Birthday - print ''; + print ''; // Public print ''; @@ -515,31 +568,15 @@ if ($rowid > 0) { $cols = 2; include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; - // Date end subscription - print ''; - // Third party Dolibarr if (!empty($conf->societe->enabled)) { print ''; @@ -608,8 +647,11 @@ if ($rowid > 0) { if ($action != 'addsubscription' && $action != 'create_thirdparty') { print '
'; - if ($object->statut > 0) print '"; - else print ''; + if ($object->statut > 0) { + print '"; + } else { + print ''; + } print '
'; } @@ -712,7 +754,9 @@ if ($rowid > 0) { if (empty($num)) { $colspan = 6; - if (!empty($conf->banque->enabled)) $colspan++; + if (!empty($conf->banque->enabled)) { + $colspan++; + } print ''; } @@ -749,13 +793,23 @@ if ($rowid > 0) { $invoiceonly = 0; // 1 means option by default is invoice only $bankviainvoice = 0; // 1 means option by default is write to bank via invoice if (GETPOST('paymentsave')) { - if (GETPOST('paymentsave') == 'bankdirect') $bankdirect = 1; - if (GETPOST('paymentsave') == 'invoiceonly') $invoiceonly = 1; - if (GETPOST('paymentsave') == 'bankviainvoice') $bankviainvoice = 1; + if (GETPOST('paymentsave') == 'bankdirect') { + $bankdirect = 1; + } + if (GETPOST('paymentsave') == 'invoiceonly') { + $invoiceonly = 1; + } + if (GETPOST('paymentsave') == 'bankviainvoice') { + $bankviainvoice = 1; + } } else { - if (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankviainvoice' && !empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) $bankviainvoice = 1; - elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankdirect' && !empty($conf->banque->enabled)) $bankdirect = 1; - elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'invoiceonly' && !empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) $invoiceonly = 1; + if (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankviainvoice' && !empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) { + $bankviainvoice = 1; + } elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankdirect' && !empty($conf->banque->enabled)) { + $bankdirect = 1; + } elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'invoiceonly' && !empty($conf->banque->enabled) && !empty($conf->societe->enabled) && !empty($conf->facture->enabled)) { + $invoiceonly = 1; + } } print "\n\n\n"; @@ -789,7 +843,9 @@ if ($rowid > 0) { } }); '; - if (GETPOST('paymentsave')) print '$("#'.GETPOST('paymentsave').'").prop("checked",true);'; + if (GETPOST('paymentsave')) { + print '$("#'.GETPOST('paymentsave').'").prop("checked",true);'; + } print '});'; print ''."\n"; } @@ -802,10 +858,14 @@ if ($rowid > 0) { if ($object->morphy == 'mor') { $companyname = $object->company; - if (!empty($fullname)) $companyalias = $fullname; + if (!empty($fullname)) { + $companyalias = $fullname; + } } else { $companyname = $fullname; - if (!empty($object->company)) $companyalias = $object->company; + if (!empty($object->company)) { + $companyalias = $object->company; + } } // Create a form array @@ -886,7 +946,9 @@ if ($rowid > 0) { // Label print ''; print ''; // Complementary action @@ -914,16 +976,21 @@ if ($rowid > 0) { print 'fk_soc)) print ' disabled'; print '> '.$langs->trans("MoreActionInvoiceOnly"); - if ($object->fk_soc) print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')'; - else { + if ($object->fk_soc) { + print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')'; + } else { print ' ('; - if (empty($object->fk_soc)) print img_warning($langs->trans("NoThirdPartyAssociatedToMember")); + if (empty($object->fk_soc)) { + print img_warning($langs->trans("NoThirdPartyAssociatedToMember")); + } print $langs->trans("NoThirdPartyAssociatedToMember"); print ' - '; print $langs->trans("CreateDolibarrThirdParty"); print ')'; } - if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') print '. '.$langs->trans("NoVatOnSubscription", 0).''; + if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') { + print '. '.$langs->trans("NoVatOnSubscription", 0).''; + } if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) { $prodtmp = new Product($db); $result = $prodtmp->fetch($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS); @@ -943,13 +1010,17 @@ if ($rowid > 0) { print ' ('.$langs->trans("ThirdParty").': '.$company->getNomUrl(1).')'; } else { print ' ('; - if (empty($object->fk_soc)) print img_warning($langs->trans("NoThirdPartyAssociatedToMember")); + if (empty($object->fk_soc)) { + print img_warning($langs->trans("NoThirdPartyAssociatedToMember")); + } print $langs->trans("NoThirdPartyAssociatedToMember"); print ' - '; print $langs->trans("CreateDolibarrThirdParty"); print ')'; } - if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') print '. '.$langs->trans("NoVatOnSubscription", 0).''; + if (empty($conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS) || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') { + print '. '.$langs->trans("NoVatOnSubscription", 0).''; + } if (!empty($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS) && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) { $prodtmp = new Product($db); $result = $prodtmp->fetch($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS); diff --git a/htdocs/adherents/subscription/card.php b/htdocs/adherents/subscription/card.php index f0f982b8764..4b2b4861c1c 100644 --- a/htdocs/adherents/subscription/card.php +++ b/htdocs/adherents/subscription/card.php @@ -48,8 +48,9 @@ $note = GETPOST('note', 'alpha'); $typeid = (int) GETPOST('typeid', 'int'); $amount = price2num(GETPOST('amount', 'alpha'), 'MT'); -if (!$user->rights->adherent->cotisation->lire) +if (!$user->rights->adherent->cotisation->lire) { accessforbidden(); +} $permissionnote = $user->rights->adherent->cotisation->creer; // Used by the include of actions_setnotes.inc.php $permissiondellink = $user->rights->adherent->cotisation->creer; // Used by the include of actions_dellink.inc.php @@ -65,7 +66,9 @@ $result = restrictedArea($user, 'subscription', 0); // TODO Check on object id * Actions */ -if ($cancel) $action = ''; +if ($cancel) { + $action = ''; +} //include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once @@ -122,7 +125,9 @@ if ($user->rights->adherent->cotisation->creer && $action == 'update' && !$cance $errmsg = $object->error; } else { foreach ($object->errors as $error) { - if ($errmsg) $errmsg .= '
'; + if ($errmsg) { + $errmsg .= '
'; + } $errmsg .= $error; } } @@ -269,7 +274,9 @@ if ($rowid && $action != 'edit') { //$formquestion=array(); //$formquestion['text']=''.$langs->trans("ThisWillAlsoDeleteBankRecord").''; $text = $langs->trans("ConfirmDeleteSubscription"); - if (!empty($conf->banque->enabled) && !empty($conf->global->ADHERENT_BANK_USE)) $text .= '
'.img_warning().' '.$langs->trans("ThisWillAlsoDeleteBankRecord"); + if (!empty($conf->banque->enabled) && !empty($conf->global->ADHERENT_BANK_USE)) { + $text .= '
'.img_warning().' '.$langs->trans("ThisWillAlsoDeleteBankRecord"); + } print $form->formconfirm($_SERVER["PHP_SELF"]."?rowid=".$object->id, $langs->trans("DeleteSubscription"), $text, "confirm_delete", $formquestion, 0, 1); } @@ -342,9 +349,9 @@ if ($rowid && $action != 'edit') { print dol_get_fiche_end(); /* - * Barre d'actions - * - */ + * Barre d'actions + * + */ print '
'; if ($user->rights->adherent->cotisation->creer) { @@ -368,15 +375,15 @@ if ($rowid && $action != 'edit') { // Documents generes /* - $filename = dol_sanitizeFileName($object->ref); - $filedir = $conf->facture->dir_output . '/' . dol_sanitizeFileName($object->ref); - $urlsource = $_SERVER['PHP_SELF'] . '?facid=' . $object->id; - $genallowed = $user->rights->facture->lire; - $delallowed = $user->rights->facture->creer; + $filename = dol_sanitizeFileName($object->ref); + $filedir = $conf->facture->dir_output . '/' . dol_sanitizeFileName($object->ref); + $urlsource = $_SERVER['PHP_SELF'] . '?facid=' . $object->id; + $genallowed = $user->rights->facture->lire; + $delallowed = $user->rights->facture->creer; - print $formfile->showdocuments('facture', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); - $somethingshown = $formfile->numoffiles; - */ + print $formfile->showdocuments('facture', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang); + $somethingshown = $formfile->numoffiles; + */ // Show links to link elements //$linktoelem = $form->showLinkToObjectBlock($object, null, array('subscription')); $somethingshown = $form->showLinkedObjectBlock($object, ''); @@ -384,16 +391,16 @@ if ($rowid && $action != 'edit') { // Show links to link elements /*$linktoelem = $form->showLinkToObjectBlock($object,array('order')); if ($linktoelem) print ($somethingshown?'':'
').$linktoelem; - */ + */ print '
'; // List of actions on element /* - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; - $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'invoice', $socid, 1); - */ + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, 'invoice', $socid, 1); + */ print '
'; } diff --git a/htdocs/adherents/subscription/info.php b/htdocs/adherents/subscription/info.php index a7a4a897505..080e2c0330c 100644 --- a/htdocs/adherents/subscription/info.php +++ b/htdocs/adherents/subscription/info.php @@ -31,8 +31,9 @@ require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; // Load translation files required by the page $langs->loadLangs(array("companies", "members", "bills", "users")); -if (!$user->rights->adherent->lire) +if (!$user->rights->adherent->lire) { accessforbidden(); +} $rowid = GETPOST("rowid", 'int'); diff --git a/htdocs/adherents/subscription/list.php b/htdocs/adherents/subscription/list.php index 4dbfdd5c851..a69962e84b6 100644 --- a/htdocs/adherents/subscription/list.php +++ b/htdocs/adherents/subscription/list.php @@ -55,12 +55,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortorder) { $sortorder = "DESC"; } -if (!$sortfield) { $sortfield = "c.dateadh"; } +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "c.dateadh"; +} $object = new Subscription($db); @@ -102,12 +108,18 @@ $result = restrictedArea($user, 'adherent', '', '', 'cotisation'); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { + $massaction = ''; +} $parameters = array('socid'=>$socid); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} if (empty($reshook)) { // Selection of new fields @@ -157,16 +169,33 @@ if (isset($date_select) && $date_select != '') { $sql .= " AND c.dateadh < '".((int) $date_select + 1)."-01-01 00:00:00'"; } if ($search_ref) { - if (is_numeric($search_ref)) $sql .= " AND (c.rowid = ".$db->escape($search_ref).")"; - else $sql .= " AND 1 = 2"; // Always wrong + if (is_numeric($search_ref)) { + $sql .= " AND (c.rowid = ".$db->escape($search_ref).")"; + } else { + $sql .= " AND 1 = 2"; // Always wrong + } +} +if ($search_type) { + $sql .= natural_search(array('c.fk_type'), $search_type); +} +if ($search_lastname) { + $sql .= natural_search(array('d.lastname', 'd.societe'), $search_lastname); +} +if ($search_firstname) { + $sql .= natural_search(array('d.firstname'), $search_firstname); +} +if ($search_login) { + $sql .= natural_search('d.login', $search_login); +} +if ($search_note) { + $sql .= natural_search('c.note', $search_note); +} +if ($search_account > 0) { + $sql .= " AND b.fk_account = ".urldecode($search_account); +} +if ($search_amount) { + $sql .= natural_search('c.subscription', $search_amount, 1); } -if ($search_type) $sql .= natural_search(array('c.fk_type'), $search_type); -if ($search_lastname) $sql .= natural_search(array('d.lastname', 'd.societe'), $search_lastname); -if ($search_firstname) $sql .= natural_search(array('d.firstname'), $search_firstname); -if ($search_login) $sql .= natural_search('d.login', $search_login); -if ($search_note) $sql .= natural_search('c.note', $search_note); -if ($search_account > 0) $sql .= " AND b.fk_account = ".urldecode($search_account); -if ($search_amount) $sql .= natural_search('c.subscription', $search_amount, 1); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; @@ -182,8 +211,11 @@ $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $resql = $db->query($sql); - if ($resql) $nbtotalofrecords = $db->num_rows($resql); - else dol_print_error($db); + if ($resql) { + $nbtotalofrecords = $db->num_rows($resql); + } else { + dol_print_error($db); + } if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; @@ -215,19 +247,41 @@ llxHeader('', $langs->trans("ListOfSubscriptions"), $help_url); $i = 0; $title = $langs->trans("ListOfSubscriptions"); -if (!empty($date_select)) $title .= ' ('.$langs->trans("Year").' '.$date_select.')'; +if (!empty($date_select)) { + $title .= ' ('.$langs->trans("Year").' '.$date_select.')'; +} $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -if ($statut != '') $param .= "&statut=".urlencode($statut); -if ($search_type) $param .= "&search_type=".urlencode($search_type); -if ($date_select) $param .= "&date_select=".urlencode($date_select); -if ($search_lastname) $param .= "&search_lastname=".urlencode($search_lastname); -if ($search_login) $param .= "&search_login=".urlencode($search_login); -if ($search_account) $param .= "&search_account=".urlencode($search_account); -if ($search_amount) $param .= "&search_amount=".urlencode($search_amount); -if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +if ($statut != '') { + $param .= "&statut=".urlencode($statut); +} +if ($search_type) { + $param .= "&search_type=".urlencode($search_type); +} +if ($date_select) { + $param .= "&date_select=".urlencode($date_select); +} +if ($search_lastname) { + $param .= "&search_lastname=".urlencode($search_lastname); +} +if ($search_login) { + $param .= "&search_login=".urlencode($search_login); +} +if ($search_account) { + $param .= "&search_account=".urlencode($search_account); +} +if ($search_amount) { + $param .= "&search_amount=".urlencode($search_amount); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -237,7 +291,9 @@ $arrayofmassactions = array( //'builddoc'=>$langs->trans("PDFMerge"), ); //if ($user->rights->adherent->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); -if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if (in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $newcardbutton = ''; @@ -246,7 +302,9 @@ if ($user->rights->adherent->cotisation->creer) { } print ''; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -263,7 +321,9 @@ $trackid = 'sub'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($sall) { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
'; } @@ -271,7 +331,9 @@ $moreforfilter = ''; $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); +if ($massactionbutton) { + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); +} print '
'; print '
'.$langs->trans("Birthday").''.dol_print_date($object->birth, 'day').'
'.$langs->trans("DateOfBirth").''.dol_print_date($object->birth, 'day').'
'.$langs->trans("Public").''.yn($object->public).'
'.$langs->trans("SubscriptionEndDate").''; - if ($object->datefin) { - print dol_print_date($object->datefin, 'day'); - if ($object->hasDelay()) { - print " ".img_warning($langs->trans("Late")); - } - } else { - if (!$adht->subscription) { - print $langs->trans("SubscriptionNotRecorded"); - if ($object->statut > 0) print " ".img_warning($langs->trans("Late")); // Display a delay picto only if it is not a draft and is not canceled - } else { - print $langs->trans("SubscriptionNotReceived"); - if ($object->statut > 0) print " ".img_warning($langs->trans("Late")); // Display a delay picto only if it is not a draft and is not canceled - } - } - print '
'; print ''; - if ($action != 'editthirdparty' && $user->rights->adherent->creer) print ''; + if ($action != 'editthirdparty' && $user->rights->adherent->creer) { + print ''; + } print '
'; print $langs->trans("LinkedToDolibarrThirdParty"); print 'id.'">'.img_edit($langs->trans('SetLinkToThirdParty'), 1).'id.'">'.img_edit($langs->trans('SetLinkToThirdParty'), 1).'
'; print '
'; if ($action == 'editthirdparty') { @@ -585,7 +622,9 @@ if ($rowid > 0) { } else { if ($object->user_id) { $form->form_users($_SERVER['PHP_SELF'].'?rowid='.$object->id, $object->user_id, 'none'); - } else print $langs->trans("NoDolibarrAccess"); + } else { + print $langs->trans("NoDolibarrAccess"); + } } print '
'.$langs->trans("None").'
'.$langs->trans("Label").'global->MEMBER_NO_DEFAULT_LABEL)) { + print $langs->trans("Subscription").' '.dol_print_date(($datefrom ? $datefrom : time()), "%Y"); + } print '">
'."\n"; @@ -366,16 +428,36 @@ print "\n"; print ''; -if (!empty($arrayfields['d.ref']['checked'])) print_liste_field_titre($arrayfields['d.ref']['label'], $_SERVER["PHP_SELF"], "c.rowid", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['d.fk_type']['checked'])) print_liste_field_titre($arrayfields['d.fk_type']['label'], $_SERVER["PHP_SELF"], "c.fk_type", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['d.lastname']['checked'])) print_liste_field_titre($arrayfields['d.lastname']['label'], $_SERVER["PHP_SELF"], "d.lastname", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['d.firstname']['checked'])) print_liste_field_titre($arrayfields['d.firstname']['label'], $_SERVER["PHP_SELF"], "d.firstname", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['d.login']['checked'])) print_liste_field_titre($arrayfields['d.login']['label'], $_SERVER["PHP_SELF"], "d.login", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['t.libelle']['checked'])) print_liste_field_titre($arrayfields['t.libelle']['label'], $_SERVER["PHP_SELF"], "c.note", $param, "", '', $sortfield, $sortorder); -if (!empty($arrayfields['d.bank']['checked'])) print_liste_field_titre($arrayfields['d.bank']['label'], $_SERVER["PHP_SELF"], "b.fk_account", $param, "", "", $sortfield, $sortorder); -if (!empty($arrayfields['c.dateadh']['checked'])) print_liste_field_titre($arrayfields['c.dateadh']['label'], $_SERVER["PHP_SELF"], "c.dateadh", $param, "", '', $sortfield, $sortorder, 'center nowraponall '); -if (!empty($arrayfields['c.datef']['checked'])) print_liste_field_titre($arrayfields['c.datef']['label'], $_SERVER["PHP_SELF"], "c.datef", $param, "", '', $sortfield, $sortorder, 'center nowraponall '); -if (!empty($arrayfields['d.amount']['checked'])) print_liste_field_titre($arrayfields['d.amount']['label'], $_SERVER["PHP_SELF"], "c.subscription", $param, "", '', $sortfield, $sortorder, 'right '); +if (!empty($arrayfields['d.ref']['checked'])) { + print_liste_field_titre($arrayfields['d.ref']['label'], $_SERVER["PHP_SELF"], "c.rowid", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['d.fk_type']['checked'])) { + print_liste_field_titre($arrayfields['d.fk_type']['label'], $_SERVER["PHP_SELF"], "c.fk_type", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['d.lastname']['checked'])) { + print_liste_field_titre($arrayfields['d.lastname']['label'], $_SERVER["PHP_SELF"], "d.lastname", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['d.firstname']['checked'])) { + print_liste_field_titre($arrayfields['d.firstname']['label'], $_SERVER["PHP_SELF"], "d.firstname", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['d.login']['checked'])) { + print_liste_field_titre($arrayfields['d.login']['label'], $_SERVER["PHP_SELF"], "d.login", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['t.libelle']['checked'])) { + print_liste_field_titre($arrayfields['t.libelle']['label'], $_SERVER["PHP_SELF"], "c.note", $param, "", '', $sortfield, $sortorder); +} +if (!empty($arrayfields['d.bank']['checked'])) { + print_liste_field_titre($arrayfields['d.bank']['label'], $_SERVER["PHP_SELF"], "b.fk_account", $param, "", "", $sortfield, $sortorder); +} +if (!empty($arrayfields['c.dateadh']['checked'])) { + print_liste_field_titre($arrayfields['c.dateadh']['label'], $_SERVER["PHP_SELF"], "c.dateadh", $param, "", '', $sortfield, $sortorder, 'center nowraponall '); +} +if (!empty($arrayfields['c.datef']['checked'])) { + print_liste_field_titre($arrayfields['c.datef']['label'], $_SERVER["PHP_SELF"], "c.datef", $param, "", '', $sortfield, $sortorder, 'center nowraponall '); +} +if (!empty($arrayfields['d.amount']['checked'])) { + print_liste_field_titre($arrayfields['d.amount']['label'], $_SERVER["PHP_SELF"], "c.subscription", $param, "", '', $sortfield, $sortorder, 'right '); +} // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; @@ -384,8 +466,12 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -if (!empty($arrayfields['c.datec']['checked'])) print_liste_field_titre($arrayfields['c.datec']['label'], $_SERVER["PHP_SELF"], "c.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); -if (!empty($arrayfields['c.tms']['checked'])) print_liste_field_titre($arrayfields['c.tms']['label'], $_SERVER["PHP_SELF"], "c.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); +if (!empty($arrayfields['c.datec']['checked'])) { + print_liste_field_titre($arrayfields['c.datec']['label'], $_SERVER["PHP_SELF"], "c.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); +} +if (!empty($arrayfields['c.tms']['checked'])) { + print_liste_field_titre($arrayfields['c.tms']['label'], $_SERVER["PHP_SELF"], "c.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); +} print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], '', '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); print "\n"; @@ -420,7 +506,9 @@ while ($i < min($num, $limit)) { // Ref if (!empty($arrayfields['d.ref']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type if (!empty($arrayfields['d.fk_type']['checked'])) { @@ -429,24 +517,32 @@ while ($i < min($num, $limit)) { print $adht->getNomUrl(1); } print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Lastname if (!empty($arrayfields['d.lastname']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Firstname if (!empty($arrayfields['d.firstname']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Login if (!empty($arrayfields['d.login']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Label @@ -454,7 +550,9 @@ while ($i < min($num, $limit)) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Banque @@ -467,24 +565,34 @@ while ($i < min($num, $limit)) { print $accountstatic->getNomUrl(1); } print "\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date start if (!empty($arrayfields['c.dateadh']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date end if (!empty($arrayfields['c.datef']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Price if (!empty($arrayfields['d.amount']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'd.amount'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'd.amount'; + } $totalarray['val']['d.amount'] += $obj->subscription; } // Extra fields @@ -498,24 +606,32 @@ while ($i < min($num, $limit)) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification if (!empty($arrayfields['c.tms']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "\n"; $i++; @@ -528,7 +644,11 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found if ($num == 0) { $colspan = 1; - foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { + $colspan++; + } + } print ''; } diff --git a/htdocs/adherents/type.php b/htdocs/adherents/type.php index 0659204761e..d2b46e96610 100644 --- a/htdocs/adherents/type.php +++ b/htdocs/adherents/type.php @@ -52,12 +52,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortorder) { $sortorder = "DESC"; } -if (!$sortfield) { $sortfield = "d.lastname"; } +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "d.lastname"; +} $label = GETPOST("label", "alpha"); $morphy = GETPOST("morphy", "alpha"); @@ -118,7 +124,9 @@ if ($action == 'add' && $user->rights->adherent->configurer) { // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } if (empty($object->label)) { $error++; @@ -167,7 +175,9 @@ if ($action == 'update' && $user->rights->adherent->configurer) { // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } $ret = $object->update($user); @@ -222,8 +232,12 @@ if (!$rowid && $action != 'create' && $action != 'edit') { $i = 0; $param = ''; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.$contextpage; + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.$limit; + } $newcardbutton = ''; if ($user->rights->adherent->configurer) { @@ -231,7 +245,9 @@ if (!$rowid && $action != 'create' && $action != 'edit') { } print ''; - if ($optioncss != '') print ''; + if ($optioncss != '') { + print ''; + } print ''; print ''; print ''; @@ -273,14 +289,20 @@ if (!$rowid && $action != 'create' && $action != 'edit') { print ''; print ''; print ''; print ''; print ''; print ''; - if ($user->rights->adherent->configurer) + if ($user->rights->adherent->configurer) { print ''; - else { + } else { print ''; } print ""; @@ -318,19 +340,19 @@ if ($action == 'create') { print ''; print ''; + print $form->selectarray('status', array('0'=>$langs->trans('ActivityCeased'), '1'=>$langs->trans('InActivity')), 1); + print ''; // Morphy - $morphys = array(); - $morphys[""] = $langs->trans("MorAndPhy"); - $morphys["phy"] = $langs->trans("Physical"); + $morphys = array(); + $morphys[""] = $langs->trans("MorAndPhy"); + $morphys["phy"] = $langs->trans("Physical"); $morphys["mor"] = $langs->trans("Moral"); print '"; - print ''; @@ -485,8 +507,8 @@ if ($rowid > 0) { } if ($action == 'search') { if (GETPOST('search', 'alpha')) { - $sql .= natural_search(array("d.firstname", "d.lastname"), GETPOST('search', 'alpha')); - } + $sql .= natural_search(array("d.firstname", "d.lastname"), GETPOST('search', 'alpha')); + } } if (!empty($search_lastname)) { $sql .= natural_search(array("d.firstname", "d.lastname"), $search_lastname); @@ -510,8 +532,11 @@ if ($rowid > 0) { $nbtotalofrecords = ''; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $resql = $db->query($sql); - if ($resql) $nbtotalofrecords = $db->num_rows($result); - else dol_print_error($db); + if ($resql) { + $nbtotalofrecords = $db->num_rows($result); + } else { + dol_print_error($db); + } if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; @@ -551,12 +576,24 @@ if ($rowid > 0) { } $param = "&rowid=".$object->id; - if (!empty($status)) $param .= "&status=".$status; - if (!empty($search_lastname)) $param .= "&search_lastname=".$search_lastname; - if (!empty($search_firstname)) $param .= "&search_firstname=".$search_firstname; - if (!empty($search_login)) $param .= "&search_login=".$search_login; - if (!empty($search_email)) $param .= "&search_email=".$search_email; - if (!empty($filter)) $param .= "&filter=".$filter; + if (!empty($status)) { + $param .= "&status=".$status; + } + if (!empty($search_lastname)) { + $param .= "&search_lastname=".$search_lastname; + } + if (!empty($search_firstname)) { + $param .= "&search_firstname=".$search_firstname; + } + if (!empty($search_login)) { + $param .= "&search_login=".$search_login; + } + if (!empty($search_email)) { + $param .= "&search_email=".$search_email; + } + if (!empty($filter)) { + $param .= "&filter=".$filter; + } if ($sall) { print $langs->trans("Filter")." (".$langs->trans("Lastname").", ".$langs->trans("Firstname").", ".$langs->trans("EMail").", ".$langs->trans("Address")." ".$langs->trans("or")." ".$langs->trans("Town")."): ".$sall; @@ -633,10 +670,10 @@ if ($rowid > 0) { // Type /*print ''; + $membertypestatic->id=$objp->type_id; + $membertypestatic->label=$objp->type; + print $membertypestatic->getNomUrl(1,12); + print ''; */ // Moral/Physique @@ -663,7 +700,9 @@ if ($rowid > 0) { print ''."\n"; } +// AGENDA_EVENT_DEFAULT_STATUS +print ''."\n"; +print ''."\n"; +print ''."\n"; +print ''."\n"; + // AGENDA_DEFAULT_FILTER_TYPE print ''."\n"; print ''."\n"; diff --git a/htdocs/admin/barcode.php b/htdocs/admin/barcode.php index ecc30c74ac9..e6211f0b56f 100644 --- a/htdocs/admin/barcode.php +++ b/htdocs/admin/barcode.php @@ -121,7 +121,7 @@ if ($action == 'setcoder') { $form = new Form($db); $formbarcode = new FormBarCode($db); -$help_url = 'EN:Module_Barcode|FR:Module_Codes_Barre|ES:Módulo Código de barra'; +$help_url = 'EN:Module_Barcode|FR:Module_Codes_Barre|ES:Módulo Código de barra|DE:Modul_Barcode'; llxHeader('', $langs->trans("BarcodeSetup"), $help_url); $linkback = ''.$langs->trans("BackToModuleList").''; diff --git a/htdocs/admin/boxes.php b/htdocs/admin/boxes.php index 4cb24cc62df..b28c81a25b1 100644 --- a/htdocs/admin/boxes.php +++ b/htdocs/admin/boxes.php @@ -40,7 +40,7 @@ $action = GETPOST('action', 'aZ09'); // Define possible position of boxes -$pos_name = InfoBox::getListOfPagesForBoxes(); +$arrayofhomepages = InfoBox::getListOfPagesForBoxes(); $boxes = array(); @@ -348,7 +348,7 @@ foreach ($boxtoadd as $box) { // For each possible position, an activation link is displayed if the box is not already active for that position print ''; @@ -406,7 +406,7 @@ foreach ($boxactivated as $key => $box) { print ($box->note ? $box->note : ' '); } print ''; - print ''; + print ''; $hasnext = ($key < (count($boxactivated) - 1)); $hasprevious = ($key != 0); print ''; diff --git a/htdocs/admin/const.php b/htdocs/admin/const.php index 1e98a1f8736..177a38e382b 100644 --- a/htdocs/admin/const.php +++ b/htdocs/admin/const.php @@ -266,16 +266,16 @@ if ($result) { print ''; print ''; print ''; - print ''; + print ''; print ''; // Note print ''; // Date last change - print ''; diff --git a/htdocs/admin/defaultvalues.php b/htdocs/admin/defaultvalues.php index 4a480349bb3..dc801059e41 100644 --- a/htdocs/admin/defaultvalues.php +++ b/htdocs/admin/defaultvalues.php @@ -30,6 +30,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/defaultvalues.class.php'; // Load translation files required by the page $langs->loadLangs(array('companies', 'products', 'admin', 'sms', 'other', 'errors')); @@ -42,7 +43,7 @@ $id = GETPOST('rowid', 'int'); $action = GETPOST('action', 'aZ09'); $optioncss = GETPOST('optionscss', 'alphanohtml'); -$mode = GETPOST('mode', 'aZ09') ?GETPOST('mode', 'aZ09') : 'createform'; // 'createform', 'filters', 'sortorder', 'focus' +$mode = GETPOST('mode', 'aZ09') ? GETPOST('mode', 'aZ09') : 'createform'; // 'createform', 'filters', 'sortorder', 'focus' $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); @@ -75,6 +76,7 @@ $value = GETPOST('value', 'restricthtml'); $hookmanager->initHooks(array('admindefaultvalues', 'globaladmin')); +$object = new DefaultValues($db); /* * Actions */ @@ -136,41 +138,54 @@ if (($action == 'add' || (GETPOST('add') && $action != 'update')) || GETPOST('ac } if (!$error) { - $db->begin(); - if ($action == 'add' || (GETPOST('add') && $action != 'update')) { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."default_values(type, user_id, page, param, value, entity) VALUES ('".$db->escape($mode)."', 0, '".$db->escape($defaulturl)."','".$db->escape($defaultkey)."','".$db->escape($defaultvalue)."', ".$db->escape($conf->entity).")"; + $object->type=$mode; + $object->user_id=0; + $object->page=$defaulturl; + $object->param=$defaultkey; + $object->value=$defaultvalue; + $object->entity=$conf->entity; + $result=$object->create($user); + if ($result<0) { + $action = ''; + setEventMessages($object->error, $object->errors, 'errors'); + } else { + setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); + $action = ""; + $defaulturl = ''; + $defaultkey = ''; + $defaultvalue = ''; + } } if (GETPOST('actionmodify')) { - $sql = "UPDATE ".MAIN_DB_PREFIX."default_values SET page = '".$db->escape($urlpage)."', param = '".$db->escape($key)."', value = '".$db->escape($value)."'"; - $sql .= " WHERE rowid = ".$id; - } - - $result = $db->query($sql); - if ($result > 0) { - $db->commit(); - setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); - $action = ""; - $defaulturl = ''; - $defaultkey = ''; - $defaultvalue = ''; - } else { - $db->rollback(); - setEventMessages($db->lasterror(), null, 'errors'); - $action = ''; + $object->id=$id; + $object->type=$mode; + $object->page=$urlpage; + $object->param=$key; + $object->value=$value; + $object->entity=$conf->entity; + $result=$object->update($user); + if ($result<0) { + $action = ''; + setEventMessages($object->error, $object->errors, 'errors'); + } else { + setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); + $action = ""; + $defaulturl = ''; + $defaultkey = ''; + $defaultvalue = ''; + } } } } // Delete line from delete picto if ($action == 'delete') { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."default_values WHERE rowid = ".$db->escape($id); - // Delete const - $result = $db->query($sql); - if ($result >= 0) { - setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); - } else { - dol_print_error($db); + $object->id=$id; + $result=$object->delete($user); + if ($result<0) { + $action = ''; + setEventMessages($object->error, $object->errors, 'errors'); } } @@ -338,43 +353,26 @@ print '\n"; print ''; +$result=$object->fetchAll($sortorder, $sortfield, 0, 0, array('t.type'=>$mode,'t.entity'=>array($user->entity,$conf->entity))); -// Show constants -$sql = "SELECT rowid, entity, type, page, param, value"; -$sql .= " FROM ".MAIN_DB_PREFIX."default_values"; -$sql .= " WHERE type = '".$db->escape($mode)."'"; -$sql .= " AND entity IN (".$user->entity.",".$conf->entity.")"; -$sql .= $db->order($sortfield, $sortorder); - -dol_syslog("translation::select from table", LOG_DEBUG); -$result = $db->query($sql); -if ($result) { - $num = $db->num_rows($result); - $i = 0; - - while ($i < $num) { - $obj = $db->fetch_object($result); - +if (!is_array($result) && $result<0) { + setEventMessages($object->error, $object->errors, 'errors'); +} elseif (count($result)>0) { + foreach ($result as $key=>$defaultvalue) { print "\n"; print ''; // Page print ''."\n"; // Field print ''."\n"; // Value @@ -385,11 +383,8 @@ if ($result) { print ''; print ''; */ - if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) { - print dol_escape_htmltag($obj->value); - } else { - print ''; - } + if ($action != 'edit' || GETPOST('rowid') != $defaultvalue->id) print dol_escape_htmltag($defaultvalue->value); + else print ''; print ''; } @@ -397,13 +392,13 @@ if ($result) { // Actions print '
'.$subscription->getNomUrl(1).''.$adherent->getNomUrl(-1, 0, 'card', 'lastname').''.$adherent->firstname.''.$adherent->login.''; print dol_trunc($obj->note, 128); print ''.dol_print_date($db->jdate($obj->dateadh), 'day')."'.dol_print_date($db->jdate($obj->datef), 'day')."'.price($obj->subscription).''; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print ''; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print ''; if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined $selected = 0; - if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + if (in_array($obj->rowid, $arrayofselected)) { + $selected = 1; + } print ''; } print '
'.$langs->trans("NoRecordFound").'
'.dol_escape_htmltag($objp->label).''; - if ($objp->morphy == 'phy') { print $langs->trans("Physical"); } elseif ($objp->morphy == 'mor') { print $langs->trans("Moral"); } else print $langs->trans("MorAndPhy"); + if ($objp->morphy == 'phy') { + print $langs->trans("Physical"); + } elseif ($objp->morphy == 'mor') { + print $langs->trans("Moral"); + } else { + print $langs->trans("MorAndPhy"); + } print ''.yn($objp->subscription).''.yn($objp->vote).''.$membertype->getLibStatut(5).'rowid.'">'.img_edit().' 
'.$langs->trans("Label").'
'.$langs->trans("Status").''; - print $form->selectarray('status', array('0'=>$langs->trans('ActivityCeased'), '1'=>$langs->trans('InActivity')), 1); - print '
'.$langs->trans("MembersNature").''; print $form->selectarray("morphy", $morphys, GETPOSTISSET("morphy") ? GETPOST("morphy", 'aZ09') : 'morphy'); print "
'.$langs->trans("SubscriptionRequired").''; + print '
'.$langs->trans("SubscriptionRequired").''; print $form->selectyesno("subscription", 1, 1); print '
'; - $membertypestatic->id=$objp->type_id; - $membertypestatic->label=$objp->type; - print $membertypestatic->getNomUrl(1,12); - print ''; if ($objp->subscription == 'yes') { print $langs->trans("SubscriptionNotReceived"); - if ($objp->status > 0) print " ".img_warning(); + if ($objp->status > 0) { + print " ".img_warning(); + } } else { print ' '; } diff --git a/htdocs/adherents/type_ldap.php b/htdocs/adherents/type_ldap.php index 1d37f337a78..87a952a68b4 100644 --- a/htdocs/adherents/type_ldap.php +++ b/htdocs/adherents/type_ldap.php @@ -51,7 +51,9 @@ $hookmanager->initHooks(array('membertypeldapcard', 'globalcard')); $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} if (empty($reshook)) { if ($action == 'dolibarr2ldap') { @@ -128,7 +130,9 @@ if ($conf->global->LDAP_MEMBER_TYPE_ACTIVE == 1) { print "\n"; -if ($conf->global->LDAP_MEMBER_TYPE_ACTIVE == 1) print "
\n"; +if ($conf->global->LDAP_MEMBER_TYPE_ACTIVE == 1) { + print "
\n"; +} diff --git a/htdocs/adherents/type_translation.php b/htdocs/adherents/type_translation.php index f2c3b785160..56dfc05e895 100644 --- a/htdocs/adherents/type_translation.php +++ b/htdocs/adherents/type_translation.php @@ -42,7 +42,9 @@ $ref = GETPOST('ref', 'alphanohtml'); // Security check $fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); $fieldtype = (!empty($ref) ? 'ref' : 'rowid'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} // Security check $result = restrictedArea($user, 'adherent', $id, 'adherent_type'); @@ -184,7 +186,9 @@ print "\n
\n"; if ($action == '') { if ($user->rights->produit->creer || $user->rights->service->creer) { print ''.$langs->trans("Add").''; - if ($cnt_trans > 0) print ''.$langs->trans("Update").''; + if ($cnt_trans > 0) { + print ''.$langs->trans("Update").''; + } } } @@ -242,7 +246,9 @@ if ($action == 'edit') { print '
'; } } - if (!$cnt_trans && $action != 'add') print '
'.$langs->trans('NoTranslation').'
'; + if (!$cnt_trans && $action != 'add') { + print '
'.$langs->trans('NoTranslation').'
'; + } } diff --git a/htdocs/admin/agenda_other.php b/htdocs/admin/agenda_other.php index 2b3eaf9be94..d23bd42848a 100644 --- a/htdocs/admin/agenda_other.php +++ b/htdocs/admin/agenda_other.php @@ -30,6 +30,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/defaultvalues.class.php'; if (!$user->admin) { accessforbidden(); @@ -80,6 +81,30 @@ if ($action == 'set') { dolibarr_set_const($db, 'AGENDA_DEFAULT_FILTER_TYPE', $defaultfilter, 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, 'AGENDA_DEFAULT_FILTER_STATUS', GETPOST('AGENDA_DEFAULT_FILTER_STATUS'), 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, 'AGENDA_DEFAULT_VIEW', GETPOST('AGENDA_DEFAULT_VIEW'), 'chaine', 0, '', $conf->entity); + + $defaultValues = new DefaultValues($db); + $result = $defaultValues->fetchAll('', '', 0, 0, array('t.page'=>'comm/action/card.php', 't.param'=>'complete','t.user_id'=>'0', 't.type'=>'createform', 't.entity'=>$conf->entity)); + if (!is_array($result) && $result<0) { + setEventMessages($defaultValues->error, $defaultValues->errors, 'errors'); + } elseif (count($result)>0) { + foreach ($result as $defval) { + $defaultValues->id=$defval->id; + $resultDel = $defaultValues->delete($user); + if ($resultDel<0) { + setEventMessages($defaultValues->error, $defaultValues->errors, 'errors'); + } + } + } + $defaultValues->type='createform'; + $defaultValues->entity=$conf->entity; + $defaultValues->user_id=0; + $defaultValues->page='comm/action/card.php'; + $defaultValues->param='complete'; + $defaultValues->value=GETPOST('AGENDA_EVENT_DEFAULT_STATUS'); + $resultCreat=$defaultValues->create($user); + if ($resultCreat<0) { + setEventMessages($defaultValues->error, $defaultValues->errors, 'errors'); + } } elseif ($action == 'specimen') { // For orders $modele = GETPOST('module', 'alpha'); @@ -325,6 +350,22 @@ if (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) { print '
'.$langs->trans("AGENDA_EVENT_DEFAULT_STATUS").' '."\n"; +$defval='na'; +$defaultValues = new DefaultValues($db); +$result = $defaultValues->fetchAll('', '', 0, 0, array('t.page'=>'comm/action/card.php', 't.param'=>'complete','t.user_id'=>'0', 't.type'=>'createform', 't.entity'=>$conf->entity)); +if (!is_array($result) && $result<0) { + setEventMessages($defaultValues->error, $defaultValues->errors, 'errors'); +} elseif (count($result)>0) { + $defval=reset($result)->value; +} +$formactions->form_select_status_action('agenda', $defval, 1, "AGENDA_EVENT_DEFAULT_STATUS", 0, 1, 'maxwidth200'); +print '
'.$langs->trans("AGENDA_DEFAULT_FILTER_TYPE").''; - print $form->selectarray("boxid[".$box->box_id."][pos]", $pos_name, -1, 1, 0, 0, '', 1)."\n"; + print $form->selectarray("boxid[".$box->box_id."][pos]", $arrayofhomepages, -1, 1, 0, 0, '', 1)."\n"; print ''."\n"; print ''.(empty($pos_name[$box->position]) ? '' : $langs->trans($pos_name[$box->position])).''.(empty($arrayofhomepages[$box->position]) ? '' : $langs->trans($arrayofhomepages[$box->position])).''.($key + 1).''; - print ''; + print ''; print ''; + print ''; print dol_print_date($db->jdate($obj->tms), 'dayhour'); print '
'; - if ($action != 'edit' || GETPOST('rowid', 'int') != $obj->rowid) { - print $obj->page; - } else { - print ''; - } + if ($action != 'edit' || GETPOST('rowid', 'int') != $defaultvalue->id) print $defaultvalue->page; + else print ''; print ''; - if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) { - print $obj->param; - } else { - print ''; - } + if ($action != 'edit' || GETPOST('rowid') != $defaultvalue->id) print $defaultvalue->param; + else print ''; print ''; - if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) { - print ''.img_edit().''; - print ''.img_delete().''; + if ($action != 'edit' || GETPOST('rowid') != $defaultvalue->id) { + print ''.img_edit().''; + print ''.img_delete().''; } else { print ''; print ''; - print '
'; + print '
'; print ''; print ''; } @@ -413,8 +408,6 @@ if ($result) { print "\n"; $i++; } -} else { - dol_print_error($db); } print '
'; diff --git a/htdocs/admin/eventorganization.php b/htdocs/admin/eventorganization.php index feb200744d2..8625f182f47 100644 --- a/htdocs/admin/eventorganization.php +++ b/htdocs/admin/eventorganization.php @@ -248,7 +248,7 @@ if ($action == 'edit') { $tmp = explode(':', $val['type']); print img_picto('', 'category', 'class="pictofixedwidth"'); - print $formother->select_categories($tmp[1], $conf->global->{$constname}, $constname, 0, $langs->trans('CustomersProspectsCategoriesShort')); + print $formother->select_categories($tmp[1], $conf->global->{$constname}, $constname, 0, $langs->trans('CustomersProspectsCategoriesShort')); } else { print ''; } diff --git a/htdocs/admin/eventorganization_confbooth_extrafields.php b/htdocs/admin/eventorganization_confbooth_extrafields.php index 4e45b0fddc3..4b6f9bdc46a 100644 --- a/htdocs/admin/eventorganization_confbooth_extrafields.php +++ b/htdocs/admin/eventorganization_confbooth_extrafields.php @@ -60,7 +60,7 @@ require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; */ -llxHeader('', $langs->trans("EventOrganizationSetup"), $help_url); +llxHeader('', $langs->trans("EventOrganizationSetup")); $linkback = ''.$langs->trans("BackToModuleList").''; diff --git a/htdocs/admin/index.php b/htdocs/admin/index.php index c16a01e5816..d94c8a3fffd 100644 --- a/htdocs/admin/index.php +++ b/htdocs/admin/index.php @@ -81,7 +81,7 @@ print '
'; if (empty($conf->global->MAIN_INFO_SOCIETE_NOM) || empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) { $setupcompanynotcomplete = 1; } -print img_picto('', 'puce').' '.$langs->trans("SetupDescription3", DOL_URL_ROOT.'/admin/company.php?mainmenu=home'.(empty($setupcompanynotcomplete) ? '' : '&action=edit'), $langs->transnoentities("Setup"), $langs->transnoentities("MenuCompanySetup")); +print img_picto('', 'company', 'class="paddingright"').' '.$langs->trans("SetupDescription3", DOL_URL_ROOT.'/admin/company.php?mainmenu=home'.(empty($setupcompanynotcomplete) ? '' : '&action=edit'), $langs->transnoentities("Setup"), $langs->transnoentities("MenuCompanySetup")); if (!empty($setupcompanynotcomplete)) { $langs->load("errors"); $warnpicto = img_warning($langs->trans("WarningMandatorySetupNotComplete"), 'style="padding-right: 6px;"'); @@ -92,7 +92,7 @@ print '
'; print '
'; // Show info setup module -print img_picto('', 'puce').' '.$langs->trans("SetupDescription4", DOL_URL_ROOT.'/admin/modules.php?mainmenu=home', $langs->transnoentities("Setup"), $langs->transnoentities("Modules")); +print img_picto('', 'cog', 'class="paddingright"').' '.$langs->trans("SetupDescription4", DOL_URL_ROOT.'/admin/modules.php?mainmenu=home', $langs->transnoentities("Setup"), $langs->transnoentities("Modules")); if (count($conf->modules) <= (empty($conf->global->MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING) ? 1 : $conf->global->MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING)) { // If only user module enabled $langs->load("errors"); $warnpicto = img_warning($langs->trans("WarningEnableYourModulesApplications"), 'style="padding-right: 6px;"'); diff --git a/htdocs/admin/ldap_groups.php b/htdocs/admin/ldap_groups.php index 0cd05a53a74..13532474681 100644 --- a/htdocs/admin/ldap_groups.php +++ b/htdocs/admin/ldap_groups.php @@ -57,7 +57,9 @@ if ($action == 'setvalue' && $user->admin) { if (!dolibarr_set_const($db, 'LDAP_GROUP_OBJECT_CLASS', GETPOST("objectclass", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) { $error++; } - + if (!dolibarr_set_const($db, 'LDAP_GROUP_FILTER', GETPOST("filter"), 'chaine', 0, '', $conf->entity)) { + $error++; + } if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_FULLNAME', GETPOST("fieldfullname", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) { $error++; } @@ -141,6 +143,13 @@ print ''.$langs->trans("LDAPGroupObjectClassListExample").''; print ' '; print ''; +// Filter, used to filter search +print ''.$langs->trans("LDAPFilterConnection").''; +print ''; +print ''.$langs->trans("LDAPGroupFilterExample").''; +print ''; +print ''; + print ''; print '
'; print ''; @@ -211,11 +220,18 @@ if ($conf->global->LDAP_SYNCHRO_ACTIVE == 'dolibarr2ldap') { $dn = $conf->global->LDAP_GROUP_DN; $objectclass = $conf->global->LDAP_GROUP_OBJECT_CLASS; + show_ldap_test_button($butlabel, $testlabel, $key, $dn, $objectclass); +} elseif ($conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr') { + $butlabel = $langs->trans("LDAPTestSearch"); + $testlabel = 'testsearchgroup'; + $key = $conf->global->LDAP_KEY_GROUPS; + $dn = $conf->global->LDAP_GROUP_DN; + $objectclass = $conf->global->LDAP_GROUP_OBJECT_CLASS; show_ldap_test_button($butlabel, $testlabel, $key, $dn, $objectclass); } if (function_exists("ldap_connect")) { - if ($_GET["action"] == 'testgroup') { + if ($action == 'testgroup') { // Creation objet $object = new UserGroup($db); $object->initAsSpecimen(); @@ -260,6 +276,62 @@ if (function_exists("ldap_connect")) { print $langs->trans("ErrorLDAPMakeManualTest", $conf->ldap->dir_temp).'
'; } } + + if ($action == 'testsearchgroup') { + // TODO Mutualize code following with other ldap_xxxx.php pages + + // Test synchro + $ldap = new Ldap(); + $result = $ldap->connect_bind(); + + if ($result > 0) { + $required_fields = array( + $conf->global->LDAP_KEY_GROUPS, + // $conf->global->LDAP_GROUP_FIELD_NAME, + $conf->global->LDAP_GROUP_FIELD_DESCRIPTION, + $conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS, + $conf->global->LDAP_GROUP_FIELD_GROUPID + ); + + // Remove from required_fields all entries not configured in LDAP (empty) and duplicated + $required_fields = array_unique(array_values(array_filter($required_fields, "dol_validElement"))); + + // Get from LDAP database an array of results + $ldapgroups = $ldap->getRecords('*', $conf->global->LDAP_GROUP_DN, $conf->global->LDAP_KEY_GROUPS, $required_fields, 'group'); + //$ldapgroups = $ldap->getRecords('*', $conf->global->LDAP_GROUP_DN, $conf->global->LDAP_KEY_GROUPS, '', 'group'); + + if (is_array($ldapgroups)) { + $liste = array(); + foreach ($ldapgroups as $key => $ldapgroup) { + // Define the label string for this group + $label = ''; + foreach ($required_fields as $value) { + if ($value) { + $label .= $value."=".$ldapgroup[$value]." "; + } + } + $liste[$key] = $label; + } + } else { + setEventMessages($ldap->error, $ldap->errors, 'errors'); + } + + print "
\n"; + print "LDAP search for group:
\n"; + print "search: *
\n"; + print "userDN: ".$conf->global->LDAP_GROUP_DN."
\n"; + print "useridentifier: ".$conf->global->LDAP_KEY_GROUPS."
\n"; + print "required_fields: ".implode(',', $required_fields)."
\n"; + print "=> ".count($liste)." records
\n"; + print "\n
"; + } else { + print img_picto('', 'error').' '; + print ''.$langs->trans("LDAPSynchroKO"); + print ': '.$ldap->error; + print '
'; + print $langs->trans("ErrorLDAPMakeManualTest", $conf->ldap->dir_temp).'
'; + } + } } // End of page diff --git a/htdocs/admin/modules.php b/htdocs/admin/modules.php index a5867d63553..5cf852fdacb 100644 --- a/htdocs/admin/modules.php +++ b/htdocs/admin/modules.php @@ -464,7 +464,7 @@ asort($orders); $nbofactivatedmodules = count($conf->modules); $moreinfo = $langs->trans("TitleNumberOfActivatedModules"); -$moreinfo2 = ($nbofactivatedmodules - 1)." / ".count($modules); +$moreinfo2 = ''.($nbofactivatedmodules - 1).' / '.count($modules).''; if ($nbofactivatedmodules <= 1) { $moreinfo2 .= ' '.img_warning($langs->trans("YouMustEnableOneModule")); } @@ -476,16 +476,16 @@ $deschelp = ''; if ($mode == 'common' || $mode == 'commonkanban') { $desc = $langs->trans("ModulesDesc", '{picto}'); $desc = str_replace('{picto}', img_picto('', 'switch_off'), $desc); - $deschelp = ''.$desc."

\n"; + $deschelp = '
'.$desc."

\n"; } if ($mode == 'marketplace') { - $deschelp = ''.$langs->trans("ModulesMarketPlaceDesc")."

\n"; + //$deschelp = '
'.$langs->trans("ModulesMarketPlaceDesc")."

\n"; } if ($mode == 'deploy') { - $deschelp = ''.$langs->trans("ModulesDeployDesc", $langs->transnoentitiesnoconv("AvailableModules"))."

\n"; + $deschelp = '
'.$langs->trans("ModulesDeployDesc", $langs->transnoentitiesnoconv("AvailableModules"))."

\n"; } if ($mode == 'develop') { - $deschelp = ''.$langs->trans("ModulesDevelopDesc")."

\n"; + $deschelp = '
'.$langs->trans("ModulesDevelopDesc")."

\n"; } $head = modules_prepare_head(); @@ -521,11 +521,11 @@ if ($mode == 'common' || $mode == 'commonkanban') { $moreforfilter .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-list-alt imgforviewmode', $_SERVER["PHP_SELF"].'?mode=common'.$param, '', 1, array('morecss'=>'reposition'.($mode == 'commonkanban' ? '' : ' btnTitleSelected'))); $moreforfilter .= ''; - $moreforfilter .= '
'.$moreinfo.'
'.$moreinfo2.'
'; + $moreforfilter .= '
'.$moreinfo.' '.$moreinfo2.'
'; $moreforfilter .= '
'; $moreforfilter .= '
'; - $moreforfilter .= img_picto($langs->trans("Filter"), 'filter', 'class="paddingright opacitymedium"').''; + $moreforfilter .= img_picto($langs->trans("Filter"), 'filter', 'class="paddingright opacityhigh"').''; $moreforfilter .= '
'; $moreforfilter .= '
'; $moreforfilter .= $form->selectarray('search_nature', $arrayofnatures, dol_escape_htmltag($search_nature), $langs->trans('Origin'), 0, 0, '', 0, 0, 0, '', 'maxwidth200', 1); @@ -745,7 +745,7 @@ if ($mode == 'common' || $mode == 'commonkanban') { } } else { if (!empty($objMod->warnings_unactivation[$mysoc->country_code]) && method_exists($objMod, 'alreadyUsed') && $objMod->alreadyUsed()) { - $codeenabledisable .= 'warnings_unactivation[$mysoc->country_code].'&value='.$modName.'&mode='.$mode.$param.'">'; + $codeenabledisable .= 'warnings_unactivation[$mysoc->country_code]).'&value='.$modName.'&mode='.$mode.$param.'">'; $codeenabledisable .= img_picto($langs->trans("Activated"), 'switch_on'); $codeenabledisable .= ''; } else { @@ -762,13 +762,13 @@ if ($mode == 'common' || $mode == 'commonkanban') { $backtourlparam .= ($backtourlparam ? '&' : '?').'search_keyword='.$search_keyword; // No urlencode here, done later } if ($search_nature > -1) { - $backtourlparam .= ($backtourlparam ? '&' : '?').'search_nature='.$search_nature; + $backtourlparam .= ($backtourlparam ? '&' : '?').'search_nature='.$search_nature; // No urlencode here, done later } if ($search_version > -1) { - $backtourlparam .= ($backtourlparam ? '&' : '?').'search_version='.$search_version; + $backtourlparam .= ($backtourlparam ? '&' : '?').'search_version='.$search_version; // No urlencode here, done later } if ($search_status > -1) { - $backtourlparam .= ($backtourlparam ? '&' : '?').'search_status='.$search_status; + $backtourlparam .= ($backtourlparam ? '&' : '?').'search_status='.$search_status; // No urlencode here, done later } $backtourl = $_SERVER["PHP_SELF"].$backtourlparam; @@ -955,7 +955,7 @@ if ($mode == 'marketplace') { print '
'."\n"; $url = 'https://www.dolistore.com'; print ''; - print ''; + print ''; print ''; print ''; diff --git a/htdocs/admin/propal.php b/htdocs/admin/propal.php index c515fe27a58..a0d590579ca 100644 --- a/htdocs/admin/propal.php +++ b/htdocs/admin/propal.php @@ -402,13 +402,13 @@ foreach ($dirmodels as $reldir) { // Active if (in_array($name, $def)) { print ''; } else { print ""; } @@ -417,7 +417,7 @@ foreach ($dirmodels as $reldir) { if ($conf->global->PROPALE_ADDON_PDF == "$name") { print img_picto($langs->trans("Default"), 'on'); } else { - print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; + print 'scandir.'&label='.urlencode($module->name).'" alt="'.$langs->trans("Default").'">'.img_picto($langs->trans("Disabled"), 'off').''; } print ''; diff --git a/htdocs/admin/system/phpinfo.php b/htdocs/admin/system/phpinfo.php index 1f8b7680563..ac51ce33dc3 100644 --- a/htdocs/admin/system/phpinfo.php +++ b/htdocs/admin/system/phpinfo.php @@ -309,8 +309,9 @@ function getResultColumn($name, array $activated, array $loaded, array $function } if (strtolower($name) == 'xdebug') { $html .= ' '.$langs->trans("ModuleActivated", "xdebug"); + $html .= ' - '.$langs->trans("ModuleActivatedMayExposeInformation"); } else { - $html .= ' '.$langs->trans("PHPSupport", $name); + $html .= ' '.$langs->trans("PHPSupport", $name).''; } } else { if (strtolower($name) == 'xdebug') { diff --git a/htdocs/admin/system/security.php b/htdocs/admin/system/security.php index f69e520bb9b..745b732b6e1 100644 --- a/htdocs/admin/system/security.php +++ b/htdocs/admin/system/security.php @@ -76,7 +76,7 @@ if ($test) { print '
'; print '
'; -print load_fiche_titre($langs->trans("ConfigurationFile"), '', 'folder'); +print load_fiche_titre($langs->trans("ConfigurationFile").' ('.$conffile.')', '', 'folder'); print ''.$langs->trans("dolibarr_main_prod").': '.$dolibarr_main_prod; if (empty($dolibarr_main_prod)) { @@ -98,7 +98,7 @@ print '
'; print '
'; print '
'; -print load_fiche_titre($langs->trans("Permissions"), '', 'folder'); +print load_fiche_titre($langs->trans("PermissionsOnFiles"), '', 'folder'); print ''.$langs->trans("PermissionsOnFilesInWebRoot").': '; // TODO Check permission are read only except for custom dir @@ -151,9 +151,18 @@ print load_fiche_titre($langs->trans("Menu").' '.$langs->trans("SecuritySetup"), //print ''.$langs->trans("PasswordEncryption").': '; print 'MAIN_SECURITY_HASH_ALGO = '.(empty($conf->global->MAIN_SECURITY_HASH_ALGO) ? $langs->trans("Undefined") : '')."   "; -print '   If unset: \'md5\' '; -print ' - Recommanded value: \'password_hash\'
'; -print 'MAIN_SECURITY_SALT = '.(empty($conf->global->MAIN_SECURITY_SALT) ? $langs->trans("Undefined") : '').'
'; +print '     If unset: \'md5\'
'; +if ($conf->global->MAIN_SECURITY_HASH_ALGO != 'password_hash') { + print 'MAIN_SECURITY_SALT = '.(empty($conf->global->MAIN_SECURITY_SALT) ? $langs->trans("Undefined") : $conf->global->MAIN_SECURITY_SALT).'
'; +} +if ($conf->global->MAIN_SECURITY_HASH_ALGO != 'password_hash') { + print 'The recommanded value for MAIN_SECURITY_HASH_ALGO is now \'password_hash\' but setting it now will make ALL existing passwords of all users not valid, so update is not possible.
'; + print 'If you really want to switch, you must:
'; + print '- Go on home - setup - other and add constant MAIN_SECURITY_HASH_ALGO to value \'password_hash\'
'; + print '- In same session, WITHOUT LOGGING OUT, go into your admin user record and set a new password
'; + print '- You can now logout and login with this new password. You must now reset password of all other users.
'; + print '

'; +} print '
'; // TODO diff --git a/htdocs/admin/system/xdebug.php b/htdocs/admin/system/xdebug.php index 186edc02dbd..fd10aad05e8 100644 --- a/htdocs/admin/system/xdebug.php +++ b/htdocs/admin/system/xdebug.php @@ -37,15 +37,18 @@ llxHeader(); print load_fiche_titre("XDebug", '', 'title_setup'); -print "
\n"; - - if (!function_exists('xdebug_is_enabled')) { + print "
\n"; print 'XDebug seems to be not installed. Function xdebug_is_enabled not found.'; llxFooter(); exit; } +print ''; +print $langs->trans("ModuleActivatedMayExposeInformation", $langs->transnoentities("XDebug")); +print ''; + +print '

'; if (function_exists('socket_create')) { $address = ini_get('xdebug.remote_host') ?ini_get('xdebug.remote_host') : '127.0.0.1'; diff --git a/htdocs/admin/tools/listevents.php b/htdocs/admin/tools/listevents.php index f49886594a7..935804ada10 100644 --- a/htdocs/admin/tools/listevents.php +++ b/htdocs/admin/tools/listevents.php @@ -69,13 +69,20 @@ $search_desc = GETPOST("search_desc", "alpha"); $search_ua = GETPOST("search_ua", "restricthtml"); $search_prefix_session = GETPOST("search_prefix_session", "restricthtml"); -if (GETPOST("date_startmonth") == '' || GETPOST("date_startmonth") > 0) { - $date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear")); +$now = dol_now(); +$nowarray = dol_getdate($now); + +if (!GETPOSTISSET("date_startmonth")) { + $date_start = dol_get_first_day($nowarray['year'], $nowarray['mon'], 'tzuserrel'); +} elseif (GETPOST("date_startmonth") > 0) { + $date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth", 'int'), GETPOST("date_startday", 'int'), GETPOST("date_startyear", 'int'), 'tzuserrel'); } else { $date_start = -1; } -if (GETPOST("date_endmonth") == '' || GETPOST("date_endmonth") > 0) { - $date_end = dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear")); +if (!GETPOSTISSET("date_endmonth")) { + $date_end = dol_get_last_hour(dol_now('gmt'), 'tzuserrel'); +} elseif (GETPOST("date_endmonth") > 0) { + $date_end = dol_get_last_hour(dol_mktime(23, 59, 59, GETPOST("date_endmonth", 'int'), GETPOST("date_endday", 'int'), GETPOST("date_endyear", 'int'), 'tzuserrel'), 'tzuserrel'); } else { $date_end = -1; } @@ -85,8 +92,6 @@ if ($date_start > 0 && $date_end > 0 && $date_start > $date_end) { $date_end = $date_start + 86400; } -$now = dol_now(); -$nowarray = dol_getdate($now); if (empty($date_start)) { // We define date_start and date_end $date_start = dol_get_first_day($nowarray['year'], $nowarray['mon'], false); @@ -114,7 +119,6 @@ $arrayfields = array( ) ); - /* * Actions */ @@ -316,19 +320,22 @@ if ($result) { // Fields title search print ''; - print ''; + print ''; print ''; // IP print ''; print ''; print ''; } if (!empty($arrayfields['e.prefix_session']['checked'])) { print ''; } @@ -376,7 +383,7 @@ if ($result) { print ''; // Date - print ''; + print ''; // Code print ''; diff --git a/htdocs/api/admin/index.php b/htdocs/api/admin/index.php index 1d15d5b9e75..3743d61b639 100644 --- a/htdocs/api/admin/index.php +++ b/htdocs/api/admin/index.php @@ -32,50 +32,44 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; // Load translation files required by the page $langs->load("admin"); -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} $action = GETPOST('action', 'aZ09'); //Activate ProfId -if ($action == 'setproductionmode') -{ +if ($action == 'setproductionmode') { $status = GETPOST('status', 'alpha'); - if (dolibarr_set_const($db, 'API_PRODUCTION_MODE', $status, 'chaine', 0, '', 0) > 0) - { + if (dolibarr_set_const($db, 'API_PRODUCTION_MODE', $status, 'chaine', 0, '', 0) > 0) { $error = 0; - if ($status == 1) - { + if ($status == 1) { $result = dol_mkdir($conf->api->dir_temp); - if ($result < 0) - { + if ($result < 0) { setEventMessages($langs->trans("ErrorFailedToCreateDir", $conf->api->dir_temp), null, 'errors'); $error++; } } else { // Delete the cache file otherwise it does not update $result = dol_delete_file($conf->api->dir_temp.'/routes.php'); - if ($result < 0) - { + if ($result < 0) { setEventMessages($langs->trans("ErrorFailedToDeleteFile", $conf->api->dir_temp.'/routes.php'), null, 'errors'); $error++; } } - if (!$error) - { + if (!$error) { header("Location: ".$_SERVER["PHP_SELF"]); - exit; + exit; } } else { dol_print_error($db); } } -if ($action == 'save') -{ +if ($action == 'save') { dolibarr_set_const($db, 'API_RESTRICT_ON_IP', GETPOST('API_RESTRICT_ON_IP', 'alpha')); } @@ -110,8 +104,7 @@ print ""; print ''; print ''; $production_mode = (empty($conf->global->API_PRODUCTION_MODE) ?false:true); -if ($production_mode) -{ +if ($production_mode) { print ''; @@ -155,8 +148,7 @@ print '
'; // Explorer print ''.$langs->trans("ApiExporerIs").':
'; -if (dol_is_dir(DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/explorer')) -{ +if (dol_is_dir(DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/explorer')) { $url = DOL_MAIN_URL_ROOT.'/api/index.php/explorer'; print img_picto('', 'globe').' '.$url."
\n"; } else { diff --git a/htdocs/asset/admin/index.html b/htdocs/asset/admin/index.html new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/htdocs/asset/admin/index.html @@ -0,0 +1 @@ + diff --git a/htdocs/asset/class/asset.class.php b/htdocs/asset/class/asset.class.php index 48f66ae5ccf..66cd9bcb4cf 100644 --- a/htdocs/asset/class/asset.class.php +++ b/htdocs/asset/class/asset.class.php @@ -414,7 +414,7 @@ class Asset extends CommonObject $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; $sql .= ' fk_user_creat, fk_user_modif'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - $sql .= ' WHERE t.rowid = '.$id; + $sql .= ' WHERE t.rowid = '.((int) $id); $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) { diff --git a/htdocs/asset/class/asset_type.class.php b/htdocs/asset/class/asset_type.class.php index 7354b8dfd15..6b345aaef68 100644 --- a/htdocs/asset/class/asset_type.class.php +++ b/htdocs/asset/class/asset_type.class.php @@ -397,7 +397,7 @@ class AssetType extends CommonObject $result = ''; $label = $langs->trans("ShowTypeCard", $this->label); - $linkstart = ''; + $linkstart = ''; $linkend = ''; $result .= $linkstart; diff --git a/htdocs/asset/class/index.html b/htdocs/asset/class/index.html new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/htdocs/asset/class/index.html @@ -0,0 +1 @@ + diff --git a/htdocs/asset/index.html b/htdocs/asset/index.html new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/htdocs/asset/index.html @@ -0,0 +1 @@ + diff --git a/htdocs/blockedlog/admin/blockedlog.php b/htdocs/blockedlog/admin/blockedlog.php index 86a563881e4..f90385b4209 100644 --- a/htdocs/blockedlog/admin/blockedlog.php +++ b/htdocs/blockedlog/admin/blockedlog.php @@ -30,7 +30,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "other", "blockedlog")); -if (!$user->admin || empty($conf->blockedlog->enabled)) accessforbidden(); +if (!$user->admin || empty($conf->blockedlog->enabled)) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); @@ -43,14 +45,14 @@ $withtab = GETPOST('withtab', 'int'); */ $reg = array(); -if (preg_match('/set_(.*)/', $action, $reg)) -{ +if (preg_match('/set_(.*)/', $action, $reg)) { $code = $reg[1]; $values = GETPOST($code); - if (is_array($values)) $values = implode(',', $values); + if (is_array($values)) { + $values = implode(',', $values); + } - if (dolibarr_set_const($db, $code, $values, 'chaine', 0, '', $conf->entity) > 0) - { + if (dolibarr_set_const($db, $code, $values, 'chaine', 0, '', $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"].($withtab ? '?withtab='.$withtab : '')); exit; } else { @@ -58,11 +60,9 @@ if (preg_match('/set_(.*)/', $action, $reg)) } } -if (preg_match('/del_(.*)/', $action, $reg)) -{ +if (preg_match('/del_(.*)/', $action, $reg)) { $code = $reg[1]; - if (dolibarr_del_const($db, $code, 0) > 0) - { + if (dolibarr_del_const($db, $code, 0) > 0) { Header("Location: ".$_SERVER["PHP_SELF"].($withtab ? '?withtab='.$withtab : '')); exit; } else { @@ -142,10 +142,8 @@ $sql .= " WHERE active > 0"; $countryArray = array(); $resql = $db->query($sql); -if ($resql) -{ - while ($obj = $db->fetch_object($resql)) - { +if ($resql) { + while ($obj = $db->fetch_object($resql)) { $countryArray[$obj->code_iso] = ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso) != "Country".$obj->code_iso ? $langs->transnoentitiesnoconv("Country".$obj->code_iso) : ($obj->label != '-' ? $obj->label : '')); } } @@ -163,8 +161,7 @@ print ''; print ''; print '
'.$langs->trans("DoliStoreDesc").''.$langs->trans("DoliStoreDesc").''.$url.'
'."\n"; - print ''; + print ''; print img_picto($langs->trans("Enabled"), 'switch_on'); print ''; print '\n"; - print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"), 'switch_off').''; + print 'scandir.'&label='.urlencode($module->name).'">'.img_picto($langs->trans("Disabled"), 'switch_off').''; print "
'.$form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0).''; + print $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzuserrel'); + print $form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzuserrel'); + print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; @@ -337,13 +344,13 @@ if ($result) { if (!empty($arrayfields['e.user_agent']['checked'])) { print ''; - print ''; + print ''; print ''; - print ''; + print ''; print '
'.dol_print_date($db->jdate($obj->dateevent), '%Y-%m-%d %H:%M:%S').''.dol_print_date($db->jdate($obj->dateevent), '%Y-%m-%d %H:%M:%S', 'tzuserrel').''.$obj->type.'
'.$langs->trans("ApiProductionMode").''; print img_picto($langs->trans("Activated"), 'switch_on'); print '
'; print $langs->trans("ListOfTrackedEvents").''; $arrayoftrackedevents = $block_static->trackedevents; -foreach ($arrayoftrackedevents as $key => $val) -{ +foreach ($arrayoftrackedevents as $key => $val) { print $key.' - '.$langs->trans($val).'
'; } @@ -174,8 +171,7 @@ print '
'; -if ($withtab) -{ +if ($withtab) { print dol_get_fiche_end(); } diff --git a/htdocs/blockedlog/admin/blockedlog_list.php b/htdocs/blockedlog/admin/blockedlog_list.php index 8f7b209cc6e..6b59c009ae7 100644 --- a/htdocs/blockedlog/admin/blockedlog_list.php +++ b/htdocs/blockedlog/admin/blockedlog_list.php @@ -33,7 +33,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "other", "blockedlog", "bills")); -if ((!$user->admin && !$user->rights->blockedlog->read) || empty($conf->blockedlog->enabled)) accessforbidden(); +if ((!$user->admin && !$user->rights->blockedlog->read) || empty($conf->blockedlog->enabled)) { + accessforbidden(); +} $action = GETPOST('action', 'aZ09'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'blockedloglist'; // To manage different context of search @@ -41,32 +43,46 @@ $backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') $search_showonlyerrors = GETPOST('search_showonlyerrors', 'int'); -if ($search_showonlyerrors < 0) $search_showonlyerrors = 0; +if ($search_showonlyerrors < 0) { + $search_showonlyerrors = 0; +} $search_id = GETPOST('search_id', 'alpha'); $search_fk_user = GETPOST('search_fk_user', 'intcomma'); $search_start = -1; -if (GETPOST('search_startyear') != '') $search_start = dol_mktime(0, 0, 0, GETPOST('search_startmonth'), GETPOST('search_startday'), GETPOST('search_startyear')); +if (GETPOST('search_startyear') != '') { + $search_start = dol_mktime(0, 0, 0, GETPOST('search_startmonth'), GETPOST('search_startday'), GETPOST('search_startyear')); +} $search_end = -1; -if (GETPOST('search_endyear') != '') $search_end = dol_mktime(23, 59, 59, GETPOST('search_endmonth'), GETPOST('search_endday'), GETPOST('search_endyear')); +if (GETPOST('search_endyear') != '') { + $search_end = dol_mktime(23, 59, 59, GETPOST('search_endmonth'), GETPOST('search_endday'), GETPOST('search_endyear')); +} $search_code = GETPOST('search_code', 'alpha'); $search_ref = GETPOST('search_ref', 'alpha'); $search_amount = GETPOST('search_amount', 'alpha'); -if (($search_start == -1 || empty($search_start)) && !GETPOSTISSET('search_startmonth')) $search_start = dol_time_plus_duree(dol_now(), '-1', 'w'); +if (($search_start == -1 || empty($search_start)) && !GETPOSTISSET('search_startmonth')) { + $search_start = dol_time_plus_duree(dol_now(), '-1', 'w'); +} // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (empty($sortfield)) $sortfield = 'rowid'; -if (empty($sortorder)) $sortorder = 'DESC'; +if (empty($sortfield)) { + $sortfield = 'rowid'; +} +if (empty($sortorder)) { + $sortorder = 'DESC'; +} $block_static = new BlockedLog($db); $block_static->loadTrackedEvents(); @@ -76,8 +92,7 @@ $result = restrictedArea($user, 'blockedlog', 0, ''); $max_execution_time_for_importexport = (empty($conf->global->EXPORT_MAX_EXECUTION_TIME) ? 300 : $conf->global->EXPORT_MAX_EXECUTION_TIME); // 5mn if not defined $max_time = @ini_get("max_execution_time"); -if ($max_time && $max_time < $max_execution_time_for_importexport) -{ +if ($max_time && $max_time < $max_execution_time_for_importexport) { dol_syslog("max_execution_time=".$max_time." is lower than max_execution_time_for_importexport=".$max_execution_time_for_importexport.". We try to increase it dynamically."); @ini_set("max_execution_time", $max_execution_time_for_importexport); // This work only if safe mode is off. also web servers has timeout of 300 } @@ -88,8 +103,7 @@ if ($max_time && $max_time < $max_execution_time_for_importexport) */ // Purge search criteria -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers $search_id = ''; $search_fk_user = ''; $search_start = -1; @@ -120,14 +134,12 @@ if ($action === 'downloadblockchain') { $previoushash = ''; $firstid = ''; - if (!$error) - { + if (!$error) { // Get ID of first line $sql = "SELECT rowid,date_creation,tms,user_fullname,action,amounts,element,fk_object,date_object,ref_object,signature,fk_user,object_data"; $sql .= " FROM ".MAIN_DB_PREFIX."blockedlog"; $sql .= " WHERE entity = ".$conf->entity; - if (GETPOST('monthtoexport', 'int') > 0 || GETPOST('yeartoexport', 'int') > 0) - { + if (GETPOST('monthtoexport', 'int') > 0 || GETPOST('yeartoexport', 'int') > 0) { $dates = dol_get_first_day(GETPOST('yeartoexport', 'int'), GETPOST('monthtoexport', 'int') ?GETPOST('monthtoexport', 'int') : 1); $datee = dol_get_last_day(GETPOST('yeartoexport', 'int'), GETPOST('monthtoexport', 'int') ?GETPOST('monthtoexport', 'int') : 12); $sql .= " AND date_creation BETWEEN '".$db->idate($dates)."' AND '".$db->idate($datee)."'"; @@ -136,12 +148,10 @@ if ($action === 'downloadblockchain') { $sql .= $db->plimit(1); $res = $db->query($sql); - if ($res) - { + if ($res) { // Make the first fetch to get first line $obj = $db->fetch_object($res); - if ($obj) - { + if ($obj) { $previoushash = $block_static->getPreviousHash(0, $obj->rowid); $firstid = $obj->rowid; } else { // If not data found for filter, we do not need previoushash neither firstid @@ -154,14 +164,12 @@ if ($action === 'downloadblockchain') { } } - if (!$error) - { + if (!$error) { // Now restart request with all data = no limit(1) in sql request $sql = "SELECT rowid,date_creation,tms,user_fullname,action,amounts,element,fk_object,date_object,ref_object,signature,fk_user,object_data"; $sql .= " FROM ".MAIN_DB_PREFIX."blockedlog"; $sql .= " WHERE entity = ".$conf->entity; - if (GETPOST('monthtoexport', 'int') > 0 || GETPOST('yeartoexport', 'int') > 0) - { + if (GETPOST('monthtoexport', 'int') > 0 || GETPOST('yeartoexport', 'int') > 0) { $dates = dol_get_first_day(GETPOST('yeartoexport', 'int'), GETPOST('monthtoexport', 'int') ?GETPOST('monthtoexport', 'int') : 1); $datee = dol_get_last_day(GETPOST('yeartoexport', 'int'), GETPOST('monthtoexport', 'int') ?GETPOST('monthtoexport', 'int') : 12); $sql .= " AND date_creation BETWEEN '".$db->idate($dates)."' AND '".$db->idate($datee)."'"; @@ -169,8 +177,7 @@ if ($action === 'downloadblockchain') { $sql .= " ORDER BY rowid ASC"; // Required so later we can use the parameter $previoushash of checkSignature() $res = $db->query($sql); - if ($res) - { + if ($res) { header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"unalterable-log-archive-".$dolibarr_main_db_name."-".(GETPOST('yeartoexport', 'int') > 0 ? GETPOST('yeartoexport', 'int').(GETPOST('monthtoexport', 'int') > 0 ?sprintf("%02d", GETPOST('monthtoexport', 'int')) : '').'-' : '').$previoushash.".csv\""); @@ -193,8 +200,7 @@ if ($action === 'downloadblockchain') { $loweridinerror = 0; $i = 0; - while ($obj = $db->fetch_object($res)) - { + while ($obj = $db->fetch_object($res)) { // We set here all data used into signature calculation (see checkSignature method) and more // IMPORTANT: We must have here, the same rule for transformation of data than into the fetch method (db->jdate for date, ...) $block_static->id = $obj->rowid; @@ -213,19 +219,20 @@ if ($action === 'downloadblockchain') { $checksignature = $block_static->checkSignature($previoushash); // If $previoushash is not defined, checkSignature will search it - if ($checksignature) - { + if ($checksignature) { $statusofrecord = 'Valid'; - if ($loweridinerror > 0) $statusofrecordnote = 'ValidButFoundAPreviousKO'; - else $statusofrecordnote = ''; + if ($loweridinerror > 0) { + $statusofrecordnote = 'ValidButFoundAPreviousKO'; + } else { + $statusofrecordnote = ''; + } } else { $statusofrecord = 'KO'; $statusofrecordnote = 'LineCorruptedOrNotMatchingPreviousOne'; $loweridinerror = $obj->rowid; } - if ($i == 0) - { + if ($i == 0) { $statusofrecordnote = $langs->trans("PreviousFingerprint").': '.$previoushash.($statusofrecordnote ? ' - '.$statusofrecordnote : ''); } print $obj->rowid; @@ -263,8 +270,7 @@ if ($action === 'downloadblockchain') { $form = new Form($db); -if (GETPOST('withtab', 'alpha')) -{ +if (GETPOST('withtab', 'alpha')) { $title = $langs->trans("ModuleSetup").' '.$langs->trans('BlockedLog'); } else { $title = $langs->trans("BrowseBlockedLog"); @@ -275,10 +281,8 @@ llxHeader('', $langs->trans("BrowseBlockedLog")); $MAXLINES = 10000; $blocks = $block_static->getLog('all', $search_id, $MAXLINES, $sortfield, $sortorder, $search_fk_user, $search_start, $search_end, $search_ref, $search_amount, $search_code); -if (!is_array($blocks)) -{ - if ($blocks == -2) - { +if (!is_array($blocks)) { + if ($blocks == -2) { setEventMessages($langs->trans("TooManyRecordToScanRestrictFilters", $MAXLINES), null, 'errors'); } else { dol_print_error($block_static->db, $block_static->error, $block_static->errors); @@ -287,15 +291,13 @@ if (!is_array($blocks)) } $linkback = ''; -if (GETPOST('withtab', 'alpha')) -{ +if (GETPOST('withtab', 'alpha')) { $linkback = ''.$langs->trans("BackToModuleList").''; } print load_fiche_titre($title, $linkback); -if (GETPOST('withtab', 'alpha')) -{ +if (GETPOST('withtab', 'alpha')) { $head = blockedlogadmin_prepare_head(); print dol_get_fiche_head($head, 'fingerprints', '', -1); } @@ -305,19 +307,45 @@ print ''.$langs->trans("Fingerprint print '
'; $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -if ($search_id != '') $param .= '&search_id='.urlencode($search_id); -if ($search_fk_user > 0) $param .= '&search_fk_user='.urlencode($search_fk_user); -if ($search_startyear > 0) $param .= '&search_startyear='.urlencode(GETPOST('search_startyear', 'int')); -if ($search_startmonth > 0) $param .= '&search_startmonth='.urlencode(GETPOST('search_startmonth', 'int')); -if ($search_startday > 0) $param .= '&search_startday='.urlencode(GETPOST('search_startday', 'int')); -if ($search_endyear > 0) $param .= '&search_endyear='.urlencode(GETPOST('search_endyear', 'int')); -if ($search_endmonth > 0) $param .= '&search_endmonth='.urlencode(GETPOST('search_endmonth', 'int')); -if ($search_endday > 0) $param .= '&search_endday='.urlencode(GETPOST('search_endday', 'int')); -if ($search_showonlyerrors > 0) $param .= '&search_showonlyerrors='.urlencode($search_showonlyerrors); -if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); -if (GETPOST('withtab', 'alpha')) $param .= '&withtab='.urlencode(GETPOST('withtab', 'alpha')); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +if ($search_id != '') { + $param .= '&search_id='.urlencode($search_id); +} +if ($search_fk_user > 0) { + $param .= '&search_fk_user='.urlencode($search_fk_user); +} +if ($search_startyear > 0) { + $param .= '&search_startyear='.urlencode(GETPOST('search_startyear', 'int')); +} +if ($search_startmonth > 0) { + $param .= '&search_startmonth='.urlencode(GETPOST('search_startmonth', 'int')); +} +if ($search_startday > 0) { + $param .= '&search_startday='.urlencode(GETPOST('search_startday', 'int')); +} +if ($search_endyear > 0) { + $param .= '&search_endyear='.urlencode(GETPOST('search_endyear', 'int')); +} +if ($search_endmonth > 0) { + $param .= '&search_endmonth='.urlencode(GETPOST('search_endmonth', 'int')); +} +if ($search_endday > 0) { + $param .= '&search_endday='.urlencode(GETPOST('search_endday', 'int')); +} +if ($search_showonlyerrors > 0) { + $param .= '&search_showonlyerrors='.urlencode($search_showonlyerrors); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} +if (GETPOST('withtab', 'alpha')) { + $param .= '&withtab='.urlencode(GETPOST('withtab', 'alpha')); +} // Add $param from extra fields //include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -332,8 +360,7 @@ $smonth = GETPOST('monthtoexport', 'int'); $retstring = ''; $retstring .= ''; print ''; print ''; -if (!empty($conf->global->BLOCKEDLOG_USE_REMOTE_AUTHORITY)) print ' | '.$langs->trans('DownloadBlockChain').''; +if (!empty($conf->global->BLOCKEDLOG_USE_REMOTE_AUTHORITY)) { + print ' | '.$langs->trans('DownloadBlockChain').''; +} print '

'; print '
'; @@ -352,7 +381,9 @@ print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -446,10 +477,8 @@ if (!empty($conf->global->BLOCKEDLOG_SCAN_ALL_FOR_LOWERIDINERROR)) { $loweridinerror = 0; $checkresult = array(); $checkdetail = array(); - if (is_array($blocks)) - { - foreach ($blocks as &$block) - { + if (is_array($blocks)) { + foreach ($blocks as &$block) { $tmpcheckresult = $block->checkSignature('', 1); // Note: this make a sql request at each call, we can't avoid this as the sorting order is various $checksignature = $tmpcheckresult['checkresult']; @@ -457,26 +486,25 @@ if (!empty($conf->global->BLOCKEDLOG_SCAN_ALL_FOR_LOWERIDINERROR)) { $checkresult[$block->id] = $checksignature; // false if error $checkdetail[$block->id] = $tmpcheckresult; - if (!$checksignature) - { - if (empty($loweridinerror)) $loweridinerror = $block->id; - else $loweridinerror = min($loweridinerror, $block->id); + if (!$checksignature) { + if (empty($loweridinerror)) { + $loweridinerror = $block->id; + } else { + $loweridinerror = min($loweridinerror, $block->id); + } } } } } -if (is_array($blocks)) -{ +if (is_array($blocks)) { $nbshown = 0; $MAXFORSHOWLINK = 100; $object_link = ''; - foreach ($blocks as &$block) - { + foreach ($blocks as &$block) { //if (empty($search_showonlyerrors) || ! $checkresult[$block->id] || ($loweridinerror && $block->id >= $loweridinerror)) - if (empty($search_showonlyerrors) || !$checkresult[$block->id]) - { + if (empty($search_showonlyerrors) || !$checkresult[$block->id]) { $nbshown++; if ($nbshown < $MAXFORSHOWLINK) { // For performance and memory purpose, we get/show the link of objects only for the 100 first output @@ -485,72 +513,71 @@ if (is_array($blocks)) $object_link = $block->element.'/'.$block->fk_object; } - print ''; + print ''; - // ID - print ''.$block->id.''; + // ID + print ''.$block->id.''; - // Date - print ''.dol_print_date($block->date_creation, 'dayhour').''; + // Date + print ''.dol_print_date($block->date_creation, 'dayhour').''; // User - print ''; - //print $block->getUser() - print $block->user_fullname; - print ''; + print ''; + //print $block->getUser() + print $block->user_fullname; + print ''; - // Action - print ''.$langs->trans('log'.$block->action).''; + // Action + print ''.$langs->trans('log'.$block->action).''; - // Ref - print ''; - print $block->ref_object; - print ''; + // Ref + print ''; + print $block->ref_object; + print ''; - // Link to source object - print ''.$object_link.''; + // Link to source object + print ''.$object_link.''; - // Amount - print ''.price($block->amounts).''; + // Amount + print ''.price($block->amounts).''; - // Details link - print ''.img_info($langs->trans('ShowDetails')).''; + // Details link + print ''.img_info($langs->trans('ShowDetails')).''; - // Fingerprint - print ''; - $texttoshow = $langs->trans("Fingerprint").' - '.$langs->trans("Saved").':
'.$block->signature; - $texttoshow .= '

'.$langs->trans("Fingerprint").' - Recalculated sha256(previoushash * data):
'.$checkdetail[$block->id]['calculatedsignature']; - $texttoshow .= '
'.$langs->trans("PreviousHash").'='.$checkdetail[$block->id]['previoushash'].''; - //$texttoshow .= '
keyforsignature='.$checkdetail[$block->id]['keyforsignature']; - print $form->textwithpicto(dol_trunc($block->signature, '8'), $texttoshow, 1, 'help', '', 0, 2, 'fingerprint'.$block->id); - print ''; + // Fingerprint + print ''; + $texttoshow = $langs->trans("Fingerprint").' - '.$langs->trans("Saved").':
'.$block->signature; + $texttoshow .= '

'.$langs->trans("Fingerprint").' - Recalculated sha256(previoushash * data):
'.$checkdetail[$block->id]['calculatedsignature']; + $texttoshow .= '
'.$langs->trans("PreviousHash").'='.$checkdetail[$block->id]['previoushash'].''; + //$texttoshow .= '
keyforsignature='.$checkdetail[$block->id]['keyforsignature']; + print $form->textwithpicto(dol_trunc($block->signature, '8'), $texttoshow, 1, 'help', '', 0, 2, 'fingerprint'.$block->id); + print ''; - // Status - print ''; - if (!$checkresult[$block->id] || ($loweridinerror && $block->id >= $loweridinerror)) // If error - { - if ($checkresult[$block->id]) { - print 'OK'; - } - else { - print 'KO'; - } - } else { - print 'OK'; - } - print ''; + // Status + print ''; + if (!$checkresult[$block->id] || ($loweridinerror && $block->id >= $loweridinerror)) { // If error + if ($checkresult[$block->id]) { + print 'OK'; + } else { + print 'KO'; + } + } else { + print 'OK'; + } + print ''; - // Note - print ''; - if (!$checkresult[$block->id] || ($loweridinerror && $block->id >= $loweridinerror)) // If error - { - if ($checkresult[$block->id]) print $form->textwithpicto('', $langs->trans('OkCheckFingerprintValidityButChainIsKo')); - } + // Note + print ''; + if (!$checkresult[$block->id] || ($loweridinerror && $block->id >= $loweridinerror)) { // If error + if ($checkresult[$block->id]) { + print $form->textwithpicto('', $langs->trans('OkCheckFingerprintValidityButChainIsKo')); + } + } - if (!empty($conf->global->BLOCKEDLOG_USE_REMOTE_AUTHORITY) && !empty($conf->global->BLOCKEDLOG_AUTHORITY_URL)) { - print ' '.($block->certified ? img_picto($langs->trans('AddedByAuthority'), 'info') : img_picto($langs->trans('NotAddedByAuthorityYet'), 'info_black')); - } - print ''; + if (!empty($conf->global->BLOCKEDLOG_USE_REMOTE_AUTHORITY) && !empty($conf->global->BLOCKEDLOG_AUTHORITY_URL)) { + print ' '.($block->certified ? img_picto($langs->trans('AddedByAuthority'), 'info') : img_picto($langs->trans('NotAddedByAuthorityYet'), 'info_black')); + } + print ''; print ''; @@ -598,8 +625,7 @@ jQuery(document).ready(function () { '."\n"; -if (!empty($conf->global->BLOCKEDLOG_USE_REMOTE_AUTHORITY) && !empty($conf->global->BLOCKEDLOG_AUTHORITY_URL)) -{ +if (!empty($conf->global->BLOCKEDLOG_USE_REMOTE_AUTHORITY) && !empty($conf->global->BLOCKEDLOG_AUTHORITY_URL)) { ?> - admin && !$user->rights->blockedlog->read) || empty($conf->blockedlog->enabled)) accessforbidden(); +if ((!$user->admin && !$user->rights->blockedlog->read) || empty($conf->blockedlog->enabled)) { + accessforbidden(); +} $langs->loadLangs(array("admin")); @@ -49,8 +57,7 @@ $langs->loadLangs(array("admin")); print '
'; print ''; -if ($block->fetch($id) > 0) -{ +if ($block->fetch($id) > 0) { $objtoshow = $block->object_data; print formatObject($objtoshow, ''); } else { @@ -77,18 +84,14 @@ function formatObject($objtoshow, $prefix) $newobjtoshow = $objtoshow; - if (is_object($newobjtoshow) || is_array($newobjtoshow)) - { + if (is_object($newobjtoshow) || is_array($newobjtoshow)) { //var_dump($newobjtoshow); - foreach ($newobjtoshow as $key => $val) - { - if (!is_object($val) && !is_array($val)) - { + foreach ($newobjtoshow as $key => $val) { + if (!is_object($val) && !is_array($val)) { // TODO $val can be '__PHP_Incomplete_Class', the is_object return false $s .= ''; $s .= ''; - } elseif (is_array($val)) - { + } elseif (is_array($val)) { $s .= formatObject($val, ($prefix ? $prefix.' > ' : '').$key); - } elseif (is_object($val)) - { + } elseif (is_object($val)) { $s .= formatObject($val, ($prefix ? $prefix.' > ' : '').$key); } } diff --git a/htdocs/blockedlog/ajax/check_signature.php b/htdocs/blockedlog/ajax/check_signature.php index cca98176930..cc91182293e 100644 --- a/htdocs/blockedlog/ajax/check_signature.php +++ b/htdocs/blockedlog/ajax/check_signature.php @@ -26,14 +26,22 @@ // This script is called with a POST method. // Directory to scan (full path) is inside POST['dir']. -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); // Disables token renewal +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} require '../../main.inc.php'; -if (empty($conf->global->BLOCKEDLOG_AUTHORITY_URL)) exit('BLOCKEDLOG_AUTHORITY_URL not set'); +if (empty($conf->global->BLOCKEDLOG_AUTHORITY_URL)) { + exit('BLOCKEDLOG_AUTHORITY_URL not set'); +} require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php'; require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/authority.class.php'; diff --git a/htdocs/blockedlog/class/authority.class.php b/htdocs/blockedlog/class/authority.class.php index faed3ac7530..9fc10fdc59e 100644 --- a/htdocs/blockedlog/class/authority.class.php +++ b/htdocs/blockedlog/class/authority.class.php @@ -122,7 +122,9 @@ class BlockedLogAuthority public function checkBlock($block) { - if (strlen($block) != 64) return false; + if (strlen($block) != 64) { + return false; + } $blocks = str_split($this->blockchain, 64); @@ -148,8 +150,7 @@ class BlockedLogAuthority dol_syslog(get_class($this)."::fetch id=".$id, LOG_DEBUG); - if (empty($id) && empty($signature)) - { + if (empty($id) && empty($signature)) { $this->error = 'BadParameter'; return -1; } @@ -159,14 +160,15 @@ class BlockedLogAuthority $sql = "SELECT b.rowid, b.signature, b.blockchain, b.tms"; $sql .= " FROM ".MAIN_DB_PREFIX."blockedlog_authority as b"; - if ($id) $sql .= " WHERE b.rowid = ".$id; - elseif ($signature)$sql .= " WHERE b.signature = '".$this->db->escape($signature)."'"; + if ($id) { + $sql .= " WHERE b.rowid = ".((int) $id); + } elseif ($signature) { + $sql .= " WHERE b.signature = '".$this->db->escape($signature)."'"; + } $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -216,12 +218,10 @@ class BlockedLogAuthority $sql .= ")"; $res = $this->db->query($sql); - if ($res) - { + if ($res) { $id = $this->db->last_insert_id(MAIN_DB_PREFIX."blockedlog_authority"); - if ($id > 0) - { + if ($id > 0) { $this->id = $id; $this->db->commit(); @@ -259,11 +259,10 @@ class BlockedLogAuthority $sql = "UPDATE ".MAIN_DB_PREFIX."blockedlog_authority SET "; $sql .= " blockchain='".$this->db->escape($this->blockchain)."'"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $res = $this->db->query($sql); - if ($res) - { + if ($res) { $this->db->commit(); return 1; diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php index a3b8913a79c..366d7042d77 100644 --- a/htdocs/blockedlog/class/blockedlog.class.php +++ b/htdocs/blockedlog/class/blockedlog.class.php @@ -319,11 +319,9 @@ class BlockedLog } else { $this->error++; } - } elseif ($this->action == 'MODULE_SET') - { + } elseif ($this->action == 'MODULE_SET') { return 'System to track events into unalterable logs were enabled'; - } elseif ($this->action == 'MODULE_RESET') - { + } elseif ($this->action == 'MODULE_RESET') { if ($this->signature == '0000000000') { return 'System to track events into unalterable logs were disabled after some recording were done. We saved a special Fingerprint to track the chain as broken.'; } else { @@ -342,7 +340,9 @@ class BlockedLog { global $langs, $cachedUser; - if (empty($cachedUser))$cachedUser = array(); + if (empty($cachedUser)) { + $cachedUser = array(); + } if (empty($cachedUser[$this->fk_user])) { $u = new User($this->db); @@ -371,7 +371,9 @@ class BlockedLog { global $langs, $user, $mysoc; - if (is_object($fuser)) $user = $fuser; + if (is_object($fuser)) { + $user = $fuser; + } // Generic fields @@ -380,20 +382,15 @@ class BlockedLog // amount $this->amounts = $amounts; // date - if ($object->element == 'payment' || $object->element == 'payment_supplier') - { + if ($object->element == 'payment' || $object->element == 'payment_supplier') { $this->date_object = $object->datepaye; - } elseif ($object->element == 'payment_salary') - { + } elseif ($object->element == 'payment_salary') { $this->date_object = $object->datev; - } elseif ($object->element == 'payment_donation' || $object->element == 'payment_various') - { + } elseif ($object->element == 'payment_donation' || $object->element == 'payment_various') { $this->date_object = $object->datepaid ? $object->datepaid : $object->datep; - } elseif ($object->element == 'subscription') - { + } elseif ($object->element == 'subscription') { $this->date_object = $object->dateh; - } elseif ($object->element == 'cashcontrol') - { + } elseif ($object->element == 'cashcontrol') { $this->date_object = $object->date_creation; } else { $this->date_object = $object->date; @@ -424,70 +421,79 @@ class BlockedLog 'name', 'lastname', 'firstname', 'region', 'region_id', 'region_code', 'state', 'state_id', 'state_code', 'country', 'country_id', 'country_code', 'total_ht', 'total_tva', 'total_ttc', 'total_localtax1', 'total_localtax2', 'barcode_type', 'barcode_type_code', 'barcode_type_label', 'barcode_type_coder', 'mode_reglement_id', 'cond_reglement_id', 'mode_reglement', 'cond_reglement', 'shipping_method_id', - 'fk_incoterms', 'label_incoterms', 'location_incoterms', 'lines') - ); + 'fk_incoterms', 'label_incoterms', 'location_incoterms', 'lines')); } // Add thirdparty info - if (empty($object->thirdparty) && method_exists($object, 'fetch_thirdparty')) $object->fetch_thirdparty(); - if (!empty($object->thirdparty)) - { + if (empty($object->thirdparty) && method_exists($object, 'fetch_thirdparty')) { + $object->fetch_thirdparty(); + } + if (!empty($object->thirdparty)) { $this->object_data->thirdparty = new stdClass(); - foreach ($object->thirdparty as $key=>$value) - { - if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties + foreach ($object->thirdparty as $key => $value) { + if (in_array($key, $arrayoffieldstoexclude)) { + continue; // Discard some properties + } if (!in_array($key, array( 'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode', 'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur' - ))) continue; // Discard if not into a dedicated list - if (!is_object($value) && !is_null($value) && $value !== '') $this->object_data->thirdparty->{$key} = $value; + ))) { + continue; // Discard if not into a dedicated list + } + if (!is_object($value) && !is_null($value) && $value !== '') { + $this->object_data->thirdparty->{$key} = $value; + } } } // Add company info - if (!empty($mysoc)) - { + if (!empty($mysoc)) { $this->object_data->mycompany = new stdClass(); - foreach ($mysoc as $key=>$value) - { - if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties + foreach ($mysoc as $key => $value) { + if (in_array($key, $arrayoffieldstoexclude)) { + continue; // Discard some properties + } if (!in_array($key, array( 'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode', 'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur' - ))) continue; // Discard if not into a dedicated list - if (!is_object($value) && !is_null($value) && $value !== '') $this->object_data->mycompany->{$key} = $value; + ))) { + continue; // Discard if not into a dedicated list + } + if (!is_object($value) && !is_null($value) && $value !== '') { + $this->object_data->mycompany->{$key} = $value; + } } } // Add user info - if (!empty($user)) - { + if (!empty($user)) { $this->fk_user = $user->id; $this->user_fullname = $user->getFullName($langs); } // Field specific to object - if ($this->element == 'facture') - { - foreach ($object as $key=>$value) - { - if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties + if ($this->element == 'facture') { + foreach ($object as $key => $value) { + if (in_array($key, $arrayoffieldstoexclude)) { + continue; // Discard some properties + } if (!in_array($key, array( 'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'datev', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public', 'lines' - ))) continue; // Discard if not into a dedicated list - if ($key == 'lines') - { + ))) { + continue; // Discard if not into a dedicated list + } + if ($key == 'lines') { $lineid = 0; - foreach ($value as $tmpline) // $tmpline is object FactureLine - { + foreach ($value as $tmpline) { // $tmpline is object FactureLine $lineid++; - foreach ($tmpline as $keyline => $valueline) - { + foreach ($tmpline as $keyline => $valueline) { if (!in_array($keyline, array( 'ref', 'multicurrency_code', 'multicurrency_total_ht', 'multicurrency_total_tva', 'multicurrency_total_ttc', 'qty', 'product_type', 'vat_src_code', 'tva_tx', 'info_bits', 'localtax1_tx', 'localtax2_tx', 'total_ht', 'total_tva', 'total_ttc', 'total_localtax1', 'total_localtax2' - ))) continue; // Discard if not into a dedicated list + ))) { + continue; // Discard if not into a dedicated list + } if (empty($this->object_data->invoiceline[$lineid]) || !is_object($this->object_data->invoiceline[$lineid])) { // To avoid warning $this->object_data->invoiceline[$lineid] = new stdClass(); @@ -498,24 +504,33 @@ class BlockedLog } } } - } elseif (!is_object($value) && !is_null($value) && $value !== '') $this->object_data->{$key} = $value; + } elseif (!is_object($value) && !is_null($value) && $value !== '') { + $this->object_data->{$key} = $value; + } } - if (!empty($object->newref)) $this->object_data->ref = $object->newref; - } elseif ($this->element == 'invoice_supplier') - { - foreach ($object as $key => $value) - { - if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties + if (!empty($object->newref)) { + $this->object_data->ref = $object->newref; + } + } elseif ($this->element == 'invoice_supplier') { + foreach ($object as $key => $value) { + if (in_array($key, $arrayoffieldstoexclude)) { + continue; // Discard some properties + } if (!in_array($key, array( 'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public' - ))) continue; // Discard if not into a dedicated list - if (!is_object($value) && !is_null($value) && $value !== '') $this->object_data->{$key} = $value; + ))) { + continue; // Discard if not into a dedicated list + } + if (!is_object($value) && !is_null($value) && $value !== '') { + $this->object_data->{$key} = $value; + } } - if (!empty($object->newref)) $this->object_data->ref = $object->newref; - } elseif ($this->element == 'payment' || $this->element == 'payment_supplier' || $this->element == 'payment_donation' || $this->element == 'payment_various') - { + if (!empty($object->newref)) { + $this->object_data->ref = $object->newref; + } + } elseif ($this->element == 'payment' || $this->element == 'payment_supplier' || $this->element == 'payment_donation' || $this->element == 'payment_various') { $datepayment = $object->datepaye ? $object->datepaye : ($object->datepaid ? $object->datepaid : $object->datep); $paymenttypeid = $object->paiementid ? $object->paiementid : ($object->paymenttype ? $object->paymenttype : $object->type_payment); @@ -523,53 +538,51 @@ class BlockedLog $this->object_data->date = $datepayment; $this->object_data->type_code = dol_getIdFromCode($this->db, $paymenttypeid, 'c_paiement', 'id', 'code'); - if (!empty($object->num_payment)) $this->object_data->payment_num = $object->num_payment; - if (!empty($object->note_private)) $this->object_data->note_private = $object->note_private; + if (!empty($object->num_payment)) { + $this->object_data->payment_num = $object->num_payment; + } + if (!empty($object->note_private)) { + $this->object_data->note_private = $object->note_private; + } //$this->object_data->fk_account = $object->fk_account; //var_dump($this->object_data);exit; $totalamount = 0; - if (!is_array($object->amounts) && $object->amount) - { + if (!is_array($object->amounts) && $object->amount) { $object->amounts = array($object->id => $object->amount); } $paymentpartnumber = 0; - foreach ($object->amounts as $objid => $amount) - { - if (empty($amount)) continue; + foreach ($object->amounts as $objid => $amount) { + if (empty($amount)) { + continue; + } $totalamount += $amount; $tmpobject = null; - if ($this->element == 'payment_supplier') - { + if ($this->element == 'payment_supplier') { include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; $tmpobject = new FactureFournisseur($this->db); - } elseif ($this->element == 'payment') - { + } elseif ($this->element == 'payment') { include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $tmpobject = new Facture($this->db); - } elseif ($this->element == 'payment_donation') - { + } elseif ($this->element == 'payment_donation') { include_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; $tmpobject = new Don($this->db); - } elseif ($this->element == 'payment_various') - { + } elseif ($this->element == 'payment_various') { include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php'; $tmpobject = new PaymentVarious($this->db); } - if (!is_object($tmpobject)) - { + if (!is_object($tmpobject)) { continue; } $result = $tmpobject->fetch($objid); - if ($result <= 0) - { + if ($result <= 0) { $this->error = $tmpobject->error; $this->errors = $tmpobject->errors; dol_syslog("Failed to fetch object with id ".$objid, LOG_ERR); @@ -579,50 +592,61 @@ class BlockedLog $paymentpart = new stdClass(); $paymentpart->amount = $amount; - if (!in_array($this->element, array('payment_donation', 'payment_various'))) - { + if (!in_array($this->element, array('payment_donation', 'payment_various'))) { $result = $tmpobject->fetch_thirdparty(); - if ($result == 0) - { + if ($result == 0) { $this->error = 'Failed to fetch thirdparty for object with id '.$tmpobject->id; $this->errors[] = $this->error; dol_syslog("Failed to fetch thirdparty for object with id ".$tmpobject->id, LOG_ERR); return -1; - } elseif ($result < 0) - { + } elseif ($result < 0) { $this->error = $tmpobject->error; $this->errors = $tmpobject->errors; return -1; } $paymentpart->thirdparty = new stdClass(); - foreach ($tmpobject->thirdparty as $key=>$value) - { - if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties + foreach ($tmpobject->thirdparty as $key => $value) { + if (in_array($key, $arrayoffieldstoexclude)) { + continue; // Discard some properties + } if (!in_array($key, array( 'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code', 'idprof1', 'idprof2', 'idprof3', 'idprof4', 'idprof5', 'idprof6', 'phone', 'fax', 'email', 'barcode', 'tva_intra', 'localtax1_assuj', 'localtax1_value', 'localtax2_assuj', 'localtax2_value', 'managers', 'capital', 'typent_code', 'forme_juridique_code', 'code_client', 'code_fournisseur' - ))) continue; // Discard if not into a dedicated list - if (!is_object($value) && !is_null($value) && $value !== '') $paymentpart->thirdparty->{$key} = $value; + ))) { + continue; // Discard if not into a dedicated list + } + if (!is_object($value) && !is_null($value) && $value !== '') { + $paymentpart->thirdparty->{$key} = $value; + } } } // Init object to avoid warnings - if ($this->element == 'payment_donation') $paymentpart->donation = new stdClass(); - else $paymentpart->invoice = new stdClass(); + if ($this->element == 'payment_donation') { + $paymentpart->donation = new stdClass(); + } else { + $paymentpart->invoice = new stdClass(); + } - if ($this->element != 'payment_various') - { - foreach ($tmpobject as $key=>$value) - { - if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties + if ($this->element != 'payment_various') { + foreach ($tmpobject as $key => $value) { + if (in_array($key, $arrayoffieldstoexclude)) { + continue; // Discard some properties + } if (!in_array($key, array( 'ref', 'ref_client', 'ref_supplier', 'date', 'datef', 'type', 'total_ht', 'total_tva', 'total_ttc', 'localtax1', 'localtax2', 'revenuestamp', 'datepointoftax', 'note_public' - ))) continue; // Discard if not into a dedicated list + ))) { + continue; // Discard if not into a dedicated list + } if (!is_object($value) && !is_null($value) && $value !== '') { - if ($this->element == 'payment_donation') $paymentpart->donation->{$key} = $value; - elseif ($this->element == 'payment_various') $paymentpart->various->{$key} = $value; - else $paymentpart->invoice->{$key} = $value; + if ($this->element == 'payment_donation') { + $paymentpart->donation->{$key} = $value; + } elseif ($this->element == 'payment_various') { + $paymentpart->various->{$key} = $value; + } else { + $paymentpart->invoice->{$key} = $value; + } } } @@ -633,33 +657,47 @@ class BlockedLog $this->object_data->amount = $totalamount; - if (!empty($object->newref)) $this->object_data->ref = $object->newref; - } elseif ($this->element == 'payment_salary') - { + if (!empty($object->newref)) { + $this->object_data->ref = $object->newref; + } + } elseif ($this->element == 'payment_salary') { $this->object_data->amounts = array($object->amount); - if (!empty($object->newref)) $this->object_data->ref = $object->newref; - } elseif ($this->element == 'subscription') - { - foreach ($object as $key=>$value) - { - if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties + if (!empty($object->newref)) { + $this->object_data->ref = $object->newref; + } + } elseif ($this->element == 'subscription') { + foreach ($object as $key => $value) { + if (in_array($key, $arrayoffieldstoexclude)) { + continue; // Discard some properties + } if (!in_array($key, array( 'id', 'datec', 'dateh', 'datef', 'fk_adherent', 'amount', 'import_key', 'statut', 'note' - ))) continue; // Discard if not into a dedicated list - if (!is_object($value) && !is_null($value) && $value !== '') $this->object_data->{$key} = $value; + ))) { + continue; // Discard if not into a dedicated list + } + if (!is_object($value) && !is_null($value) && $value !== '') { + $this->object_data->{$key} = $value; + } } - if (!empty($object->newref)) $this->object_data->ref = $object->newref; + if (!empty($object->newref)) { + $this->object_data->ref = $object->newref; + } } else // Generic case { - foreach ($object as $key=>$value) - { - if (in_array($key, $arrayoffieldstoexclude)) continue; // Discard some properties - if (!is_object($value) && !is_null($value) && $value !== '') $this->object_data->{$key} = $value; + foreach ($object as $key => $value) { + if (in_array($key, $arrayoffieldstoexclude)) { + continue; // Discard some properties + } + if (!is_object($value) && !is_null($value) && $value !== '') { + $this->object_data->{$key} = $value; + } } - if (!empty($object->newref)) $this->object_data->ref = $object->newref; + if (!empty($object->newref)) { + $this->object_data->ref = $object->newref; + } } return 1; @@ -675,8 +713,7 @@ class BlockedLog { global $langs; - if (empty($id)) - { + if (empty($id)) { $this->error = 'BadParameter'; return -1; } @@ -684,11 +721,12 @@ class BlockedLog $sql = "SELECT b.rowid, b.date_creation, b.signature, b.signature_line, b.amounts, b.action, b.element, b.fk_object, b.entity,"; $sql .= " b.certified, b.tms, b.fk_user, b.user_fullname, b.date_object, b.ref_object, b.object_data, b.object_version"; $sql .= " FROM ".MAIN_DB_PREFIX."blockedlog as b"; - if ($id) $sql .= " WHERE b.rowid = ".((int) $id); + if ($id) { + $sql .= " WHERE b.rowid = ".((int) $id); + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); if ($obj) { $this->id = $obj->rowid; @@ -758,8 +796,10 @@ class BlockedLog public function setCertified() { - $res = $this->db->query("UPDATE ".MAIN_DB_PREFIX."blockedlog SET certified=1 WHERE rowid=".$this->id); - if ($res === false) return false; + $res = $this->db->query("UPDATE ".MAIN_DB_PREFIX."blockedlog SET certified=1 WHERE rowid=".((int) $this->id)); + if ($res === false) { + return false; + } return true; } @@ -785,8 +825,7 @@ class BlockedLog dol_syslog(get_class($this).'::create action='.$this->action.' fk_user='.$this->fk_user.' user_fullname='.$this->user_fullname, LOG_DEBUG); // Check parameters/properties - if (!isset($this->amounts)) // amount can be 0 for some events (like when module is disabled) - { + if (!isset($this->amounts)) { // amount can be 0 for some events (like when module is disabled) $this->error = $langs->trans("BlockLogNeedAmountsValue"); dol_syslog($this->error, LOG_WARNING); return -1; @@ -803,7 +842,9 @@ class BlockedLog dol_syslog($this->error, LOG_WARNING); return -3; } - if (empty($this->fk_user)) $this->user_fullname = '(Anonymous)'; + if (empty($this->fk_user)) { + $this->user_fullname = '(Anonymous)'; + } $this->date_creation = dol_now(); @@ -817,7 +858,9 @@ class BlockedLog $this->signature_line = dol_hash($keyforsignature, '5'); // Not really usefull $this->signature = dol_hash($previoushash.$keyforsignature, '5'); - if ($forcesignature) $this->signature = $forcesignature; + if ($forcesignature) { + $this->signature = $forcesignature; + } //var_dump($keyforsignature);var_dump($previoushash);var_dump($this->signature_line);var_dump($this->signature); $sql = "INSERT INTO ".MAIN_DB_PREFIX."blockedlog ("; @@ -855,12 +898,10 @@ class BlockedLog $sql .= ")"; $res = $this->db->query($sql); - if ($res) - { + if ($res) { $id = $this->db->last_insert_id(MAIN_DB_PREFIX."blockedlog"); - if ($id > 0) - { + if ($id > 0) { $this->id = $id; $this->db->commit(); @@ -888,8 +929,7 @@ class BlockedLog */ public function checkSignature($previoushash = '', $returnarray = 0) { - if (empty($previoushash)) - { + if (empty($previoushash)) { $previoushash = $this->getPreviousHash(0, $this->id); } // Recalculate hash @@ -949,31 +989,31 @@ class BlockedLog $previoussignature = ''; - $sql = "SELECT rowid, signature FROM ".MAIN_DB_PREFIX."blockedlog"; - $sql .= " WHERE entity=".$conf->entity; - if ($beforeid) $sql .= " AND rowid < ".(int) $beforeid; - $sql .= " ORDER BY rowid DESC LIMIT 1"; - $sql .= ($withlock ? " FOR UPDATE " : ""); + $sql = "SELECT rowid, signature FROM ".MAIN_DB_PREFIX."blockedlog"; + $sql .= " WHERE entity=".$conf->entity; + if ($beforeid) { + $sql .= " AND rowid < ".(int) $beforeid; + } + $sql .= " ORDER BY rowid DESC LIMIT 1"; + $sql .= ($withlock ? " FOR UPDATE " : ""); - $resql = $this->db->query($sql); - if ($resql) { - $obj = $this->db->fetch_object($resql); - if ($obj) - { - $previoussignature = $obj->signature; - } - } else { - dol_print_error($this->db); - exit; - } + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + if ($obj) { + $previoussignature = $obj->signature; + } + } else { + dol_print_error($this->db); + exit; + } - if (empty($previoussignature)) - { + if (empty($previoussignature)) { // First signature line (line 0) - $previoussignature = $this->getSignature(); - } + $previoussignature = $this->getSignature(); + } - return $previoussignature; + return $previoussignature; } /** @@ -1001,7 +1041,7 @@ class BlockedLog //if (empty($cachedlogs)) $cachedlogs = array(); if ($element == 'all') { - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."blockedlog + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."blockedlog WHERE entity=".$conf->entity; } elseif ($element == 'not_certified') { $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."blockedlog @@ -1014,13 +1054,27 @@ class BlockedLog WHERE entity=".$conf->entity." AND element='".$this->db->escape($element)."'"; } - if ($fk_object) $sql .= natural_search("rowid", $fk_object, 1); - if ($search_fk_user > 0) $sql .= natural_search("fk_user", $search_fk_user, 2); - if ($search_start > 0) $sql .= " AND date_creation >= '".$this->db->idate($search_start)."'"; - if ($search_end > 0) $sql .= " AND date_creation <= '".$this->db->idate($search_end)."'"; - if ($search_ref != '') $sql .= natural_search("ref_object", $search_ref); - if ($search_amount != '') $sql .= natural_search("amounts", $search_amount, 1); - if ($search_code != '' && $search_code != '-1') $sql .= natural_search("action", $search_code, 3); + if ($fk_object) { + $sql .= natural_search("rowid", $fk_object, 1); + } + if ($search_fk_user > 0) { + $sql .= natural_search("fk_user", $search_fk_user, 2); + } + if ($search_start > 0) { + $sql .= " AND date_creation >= '".$this->db->idate($search_start)."'"; + } + if ($search_end > 0) { + $sql .= " AND date_creation <= '".$this->db->idate($search_end)."'"; + } + if ($search_ref != '') { + $sql .= natural_search("ref_object", $search_ref); + } + if ($search_amount != '') { + $sql .= natural_search("amounts", $search_amount, 1); + } + if ($search_code != '' && $search_code != '-1') { + $sql .= natural_search("action", $search_code, 3); + } $sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->plimit($limit + 1); // We want more, because we will stop into loop later with error if we reach max @@ -1030,11 +1084,9 @@ class BlockedLog $results = array(); $i = 0; - while ($obj = $this->db->fetch_object($res)) - { + while ($obj = $this->db->fetch_object($res)) { $i++; - if ($i > $limit) - { + if ($i > $limit) { // Too many record, we will consume too much memory return -2; } @@ -1096,15 +1148,20 @@ class BlockedLog $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."blockedlog"; $sql .= " WHERE entity = ".$conf->entity; - if ($ignoresystem) $sql .= " AND action not in ('MODULE_SET','MODULE_RESET')"; + if ($ignoresystem) { + $sql .= " AND action not in ('MODULE_SET','MODULE_RESET')"; + } $sql .= $this->db->plimit(1); $res = $this->db->query($sql); - if ($res !== false) - { + if ($res !== false) { $obj = $this->db->fetch_object($res); - if ($obj) $result = true; - } else dol_print_error($this->db); + if ($obj) { + $result = true; + } + } else { + dol_print_error($this->db); + } dol_syslog("Module Blockedlog alreadyUsed with ignoresystem=".$ignoresystem." is ".$result); diff --git a/htdocs/blockedlog/lib/blockedlog.lib.php b/htdocs/blockedlog/lib/blockedlog.lib.php index 11b85567a41..44f7074d582 100644 --- a/htdocs/blockedlog/lib/blockedlog.lib.php +++ b/htdocs/blockedlog/lib/blockedlog.lib.php @@ -44,8 +44,7 @@ function blockedlogadmin_prepare_head() require_once DOL_DOCUMENT_ROOT.'/blockedlog/class/blockedlog.class.php'; $b = new BlockedLog($db); - if ($b->alreadyUsed()) - { + if ($b->alreadyUsed()) { $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '...' : ''); } $head[$h][2] = 'fingerprints'; diff --git a/htdocs/bom/bom_list.php b/htdocs/bom/bom_list.php index 4eaef9b096c..eb1852699c0 100644 --- a/htdocs/bom/bom_list.php +++ b/htdocs/bom/bom_list.php @@ -539,7 +539,7 @@ print ''."\n"; // -------------------------------------------------------------------- print ''; foreach ($object->fields as $key => $val) { - $cssforfield = (empty($val['css']) ? '' : $val['css']); + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); if ($key == 'status') { $cssforfield .= ($cssforfield ? ' ' : '').'center'; } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { @@ -591,7 +591,7 @@ while ($i < ($limit ? min($num, $limit) : $num)) { // Show here line of result print ''; foreach ($object->fields as $key => $val) { - $cssforfield = (empty($val['css']) ? '' : $val['css']); + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { $cssforfield .= ($cssforfield ? ' ' : '').'center'; } elseif ($key == 'status') { diff --git a/htdocs/bom/class/bom.class.php b/htdocs/bom/class/bom.class.php index e71ec49da38..47246b8423d 100644 --- a/htdocs/bom/class/bom.class.php +++ b/htdocs/bom/class/bom.class.php @@ -63,24 +63,29 @@ class BOM extends CommonObject /** - * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password') + * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password') * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)" * 'label' the translation key. - * 'enabled' is a condition when the field must be managed. + * 'picto' is code of a picto to show before value in forms + * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM) + * 'position' is the sort order of field. + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing) * 'noteditable' says if field is not editable (1 or 0) - * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). - * 'default' is a default value for creation (can still be replaced by the global setup of default values) + * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created. * 'index' if we want an index in database. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...). - * 'position' is the sort order of field. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8). - * 'css' is the CSS style to use on field. For example: 'maxwidth200' - * 'help' is a string visible as a tooltip on field - * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'maxwidth200', 'wordbreak', 'tdoverflowmax200' + * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record + * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code. * 'arraykeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel") + * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1. + * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * + * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor. */ // BEGIN MODULEBUILDER PROPERTIES @@ -92,8 +97,8 @@ class BOM extends CommonObject 'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'notnull'=> 1, 'default'=>1, 'index'=>1, 'position'=>5), 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'noteditable'=>1, 'visible'=>4, 'position'=>10, 'notnull'=>1, 'default'=>'(PROV)', 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of BOM", 'showoncombobox'=>'1',), 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'notnull'=>1, 'searchall'=>1, 'showoncombobox'=>'1', 'autofocusoncreate'=>1), - //'bomtype' => array('type'=>'integer', 'label'=>'Type', 'enabled'=>1, 'visible'=>1, 'position'=>10, 'notnull'=>1, 'default'=>'0', 'arrayofkeyval'=>array(0=>'Manufacturing', 1=>'Disassembly')), - 'bomtype' => array('type'=>'integer', 'label'=>'Type', 'enabled'=>1, 'visible'=>-1, 'position'=>32, 'notnull'=>1, 'default'=>'0', 'arrayofkeyval'=>array(0=>'Manufacturing')), + 'bomtype' => array('type'=>'integer', 'label'=>'Type', 'enabled'=>1, 'visible'=>1, 'position'=>33, 'notnull'=>1, 'default'=>'0', 'arrayofkeyval'=>array(0=>'Manufacturing', 1=>'Disassemble'), 'css'=>'minwidth150', 'csslist'=>'minwidth150'), + //'bomtype' => array('type'=>'integer', 'label'=>'Type', 'enabled'=>1, 'visible'=>-1, 'position'=>32, 'notnull'=>1, 'default'=>'0', 'arrayofkeyval'=>array(0=>'Manufacturing')), 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php:1:(finished IS NULL or finished <> 0)', 'label'=>'Product', 'picto'=>'product', 'enabled'=>1, 'visible'=>1, 'position'=>35, 'notnull'=>1, 'index'=>1, 'help'=>'ProductBOMHelp', 'css'=>'maxwidth500'), 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>-1, 'position'=>60, 'notnull'=>-1,), 'qty' => array('type'=>'real', 'label'=>'Quantity', 'enabled'=>1, 'visible'=>1, 'default'=>1, 'position'=>55, 'notnull'=>1, 'isameasure'=>'1', 'css'=>'maxwidth75imp'), @@ -892,7 +897,7 @@ class BOM extends CommonObject $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; $sql .= ' fk_user_creat, fk_user_modif'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - $sql .= ' WHERE t.rowid = '.$id; + $sql .= ' WHERE t.rowid = '.((int) $id); $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) { @@ -1469,7 +1474,7 @@ class BOMLine extends CommonObjectLine $sql = 'SELECT rowid, date_creation as datec, tms as datem,'; $sql .= ' fk_user_creat, fk_user_modif'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - $sql .= ' WHERE t.rowid = '.$id; + $sql .= ' WHERE t.rowid = '.((int) $id); $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) { diff --git a/htdocs/bom/lib/bom.lib.php b/htdocs/bom/lib/bom.lib.php index a5be872a096..8f3cadeedc2 100644 --- a/htdocs/bom/lib/bom.lib.php +++ b/htdocs/bom/lib/bom.lib.php @@ -1,6 +1,6 @@ - * Copyright (C) 2019 Frédéric France + * Copyright (C) 2019-2021 Frédéric France * * 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 @@ -41,17 +41,11 @@ function bomAdminPrepareHead() $head[$h][2] = 'settings'; $h++; - $head[$h][0] = dol_buildpath("/admin/bom_extrafields.php", 1); + $head[$h][0] = DOL_URL_ROOT."/admin/bom_extrafields.php"; $head[$h][1] = $langs->trans("ExtraFields"); $head[$h][2] = 'bom_extrafields'; $h++; - /*$head[$h][0] = DOL_URL_ROOT."/bom/admin/about.php"; - $head[$h][1] = $langs->trans("About"); - $head[$h][2] = 'about'; - $h++; - */ - // Show more tabs from modules // Entries must be declared in modules descriptor with line //$this->tabs = array( diff --git a/htdocs/bookmarks/card.php b/htdocs/bookmarks/card.php index ddb043292f6..3c3e03ecb37 100644 --- a/htdocs/bookmarks/card.php +++ b/htdocs/bookmarks/card.php @@ -52,8 +52,7 @@ $object = new Bookmark($db); * Actions */ -if ($action == 'add' || $action == 'addproduct' || $action == 'update') -{ +if ($action == 'add' || $action == 'addproduct' || $action == 'update') { if ($action == 'update') { $invertedaction = 'edit'; } else { @@ -62,14 +61,17 @@ if ($action == 'add' || $action == 'addproduct' || $action == 'update') $error = 0; - if (GETPOST('cancel', 'alpha')) - { - if (empty($backtopage)) $backtopage = ($urlsource ? $urlsource : ((!empty($url) && !preg_match('/^http/i', $url)) ? $url : DOL_URL_ROOT.'/bookmarks/list.php')); + if (GETPOST('cancel', 'alpha')) { + if (empty($backtopage)) { + $backtopage = ($urlsource ? $urlsource : ((!empty($url) && !preg_match('/^http/i', $url)) ? $url : DOL_URL_ROOT.'/bookmarks/list.php')); + } header("Location: ".$backtopage); exit; } - if ($action == 'update') $object->fetch(GETPOST("id", 'int')); + if ($action == 'update') { + $object->fetch(GETPOST("id", 'int')); + } // Check if null because user not admin can't set an user and send empty value here. if (!empty($userid)) { $object->fk_user = $userid; @@ -89,21 +91,23 @@ if ($action == 'add' || $action == 'addproduct' || $action == 'update') setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->trans("UrlOrLink")), null, 'errors'); } - if (!$error) - { + if (!$error) { $object->favicon = 'none'; - if ($action == 'update') $res = $object->update(); - else $res = $object->create(); + if ($action == 'update') { + $res = $object->update(); + } else { + $res = $object->create(); + } - if ($res > 0) - { - if (empty($backtopage)) $backtopage = ($urlsource ? $urlsource : ((!empty($url) && !preg_match('/^http/i', $url)) ? $url : DOL_URL_ROOT.'/bookmarks/list.php')); + if ($res > 0) { + if (empty($backtopage)) { + $backtopage = ($urlsource ? $urlsource : ((!empty($url) && !preg_match('/^http/i', $url)) ? $url : DOL_URL_ROOT.'/bookmarks/list.php')); + } header("Location: ".$backtopage); exit; } else { - if ($object->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->transnoentities("WarningBookmarkAlreadyExists"), null, 'warnings'); } else { @@ -137,8 +141,7 @@ $h++; $hselected = 'card'; -if ($action == 'create') -{ +if ($action == 'create') { /* * Fact bookmark creation mode */ @@ -189,8 +192,7 @@ if ($action == 'create') } -if ($id > 0 && !preg_match('/^add/i', $action)) -{ +if ($id > 0 && !preg_match('/^add/i', $action)) { /* * Fact bookmark mode or visually edition */ @@ -205,8 +207,7 @@ if ($id > 0 && !preg_match('/^add/i', $action)) ) ); - if ($action == 'edit') - { + if ($action == 'edit') { print ''; print ''; print ''; @@ -239,8 +240,11 @@ if ($id > 0 && !preg_match('/^add/i', $action)) } print ''; print ''; print ''; print ''; // Date creation @@ -298,8 +309,7 @@ if ($id > 0 && !preg_match('/^add/i', $action)) print dol_get_fiche_end(); - if ($action == 'edit') - { + if ($action == 'edit') { print '
   
'; print ''; } @@ -310,14 +320,12 @@ if ($id > 0 && !preg_match('/^add/i', $action)) print "
\n"; // Edit - if ($user->rights->bookmark->creer && $action != 'edit') - { + if ($user->rights->bookmark->creer && $action != 'edit') { print ''.$langs->trans("Edit").''."\n"; } // Remove - if ($user->rights->bookmark->supprimer && $action != 'edit') - { + if ($user->rights->bookmark->supprimer && $action != 'edit') { print ''.$langs->trans("Delete").''."\n"; } diff --git a/htdocs/bookmarks/class/bookmark.class.php b/htdocs/bookmarks/class/bookmark.class.php index f5bbefae3d3..4fe8c3cee83 100644 --- a/htdocs/bookmarks/class/bookmark.class.php +++ b/htdocs/bookmarks/class/bookmark.class.php @@ -117,7 +117,7 @@ class Bookmark extends CommonObject $sql = "SELECT rowid, fk_user, dateb as datec, url, target,"; $sql .= " title, position, favicon"; $sql .= " FROM ".MAIN_DB_PREFIX."bookmark"; - $sql .= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".((int) $id); $sql .= " AND entity = ".$conf->entity; dol_syslog("Bookmark::fetch", LOG_DEBUG); @@ -239,7 +239,7 @@ class Bookmark extends CommonObject public function remove($id) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."bookmark"; - $sql .= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".((int) $id); dol_syslog("Bookmark::remove", LOG_DEBUG); $resql = $this->db->query($sql); diff --git a/htdocs/bookmarks/list.php b/htdocs/bookmarks/list.php index 6ad2770aa25..e4405f0aea6 100644 --- a/htdocs/bookmarks/list.php +++ b/htdocs/bookmarks/list.php @@ -45,12 +45,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action +if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { + $page = 0; +} // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = 'position'; -if (!$sortorder) $sortorder = 'ASC'; +if (!$sortfield) { + $sortfield = 'position'; +} +if (!$sortorder) { + $sortorder = 'ASC'; +} $id = GETPOST("id", 'int'); @@ -65,11 +71,9 @@ $permissiontodelete = $user->rights->bookmark->delete; * Actions */ -if ($action == 'delete') -{ +if ($action == 'delete') { $res = $object->remove($id); - if ($res > 0) - { + if ($res > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -93,32 +97,30 @@ $sql .= " u.login, u.lastname, u.firstname"; $sql .= " FROM ".MAIN_DB_PREFIX."bookmark as b LEFT JOIN ".MAIN_DB_PREFIX."user as u ON b.fk_user=u.rowid"; $sql .= " WHERE 1=1"; $sql .= " AND b.entity IN (".getEntity('bookmark').")"; -if (!$user->admin) $sql .= " AND (b.fk_user = ".$user->id." OR b.fk_user is NULL OR b.fk_user = 0)"; +if (!$user->admin) { + $sql .= " AND (b.fk_user = ".$user->id." OR b.fk_user is NULL OR b.fk_user = 0)"; +} $sql .= $db->order($sortfield.", position", $sortorder); // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $resql = $db->query($sql); $nbtotalofrecords = $db->num_rows($resql); - if (($page * $limit) > $nbtotalofrecords) // if total of record found is smaller than page * limit, goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0 $page = 0; $offset = 0; } } // if total of record found is smaller than limit, no need to do paging and to restart another select with limits set. -if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) -{ +if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) { $num = $nbtotalofrecords; } else { $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); exit; } @@ -127,9 +129,15 @@ if (is_numeric($nbtotalofrecords) && $limit > $nbtotalofrecords) } $param = ""; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -if ($optioncss != '') $param = '&optioncss='.urlencode($optioncss); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +if ($optioncss != '') { + $param = '&optioncss='.urlencode($optioncss); +} $moreforfilter = ''; @@ -140,12 +148,18 @@ $arrayofmassactions = array( //'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); -if ($permissiontodelete) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($permissiontodelete) { + $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print '
'; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -176,8 +190,7 @@ print "\n"; $cacheOfUsers = array(); $i = 0; -while ($i < min($num, $limit)) -{ +while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $object->id = $obj->rowid; @@ -197,28 +210,39 @@ while ($i < min($num, $limit)) // Title print "
\n"; // Url print '\n"; // Target print '\n"; // Author print ''; print ''; print ''; + // Payment mode + print ''; + print ''; + // Delivery date $langs->load('deliveries'); print ''; print ''; - // Payment mode - print ''; - print ''; - // Multicurrency if (!empty($conf->multicurrency->enabled)) { // Multicurrency code @@ -2350,7 +2351,7 @@ if ($action == 'create') { print '
'.$langs->trans('Field').''.$langs->trans('Value').'
'.($prefix ? $prefix.' > ' : '').$key.''; - if (in_array($key, array('date', 'datef', 'dateh', 'datec', 'datem', 'datep'))) - { + if (in_array($key, array('date', 'datef', 'dateh', 'datec', 'datem', 'datep'))) { /*var_dump(is_object($val)); var_dump(is_array($val)); var_dump(is_array($val)); @@ -99,11 +102,9 @@ function formatObject($objtoshow, $prefix) $s .= $val; } $s .= '
'; - if ($action == 'edit') print 'title).'">'; - else print $object->title; + if ($action == 'edit') { + print 'title).'">'; + } else { + print $object->title; + } print '
'; @@ -252,28 +256,32 @@ if ($id > 0 && !preg_match('/^add/i', $action)) print ''; } print ''; - if ($action == 'edit') print 'url).'">'; - else print 'target ? ' target="_blank"' : '').'>'.$object->url.''; + if ($action == 'edit') { + print 'url).'">'; + } else { + print 'target ? ' target="_blank"' : '').'>'.$object->url.''; + } print '
'.$langs->trans("BehaviourOnClick").''; - if ($action == 'edit') - { + if ($action == 'edit') { $liste = array(1=>$langs->trans("OpenANewWindow"), 0=>$langs->trans("ReplaceWindow")); print $form->selectarray('target', $liste, GETPOSTISSET("target") ? GETPOST("target") : $object->target); } else { - if ($object->target == 0) print $langs->trans("ReplaceWindow"); - if ($object->target == 1) print $langs->trans("OpenANewWindow"); + if ($object->target == 0) { + print $langs->trans("ReplaceWindow"); + } + if ($object->target == 1) { + print $langs->trans("OpenANewWindow"); + } } print '
'.$langs->trans("Owner").''; - if ($action == 'edit' && $user->admin) - { + if ($action == 'edit' && $user->admin) { print img_picto('', 'user').' '.$form->select_dolusers(GETPOSTISSET('userid') ? GETPOST('userid', 'int') : ($object->fk_user ? $object->fk_user : ''), 'userid', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); } else { - if ($object->fk_user > 0) - { + if ($object->fk_user > 0) { $fuser = new User($db); $fuser->fetch($object->fk_user); print $fuser->getNomUrl(1); @@ -285,8 +293,11 @@ if ($id > 0 && !preg_match('/^add/i', $action)) // Position print '
'.$langs->trans("Position").''; - if ($action == 'edit') print 'position).'">'; - else print $object->position; + if ($action == 'edit') { + print 'position).'">'; + } else { + print $object->position; + } print '
"; $linkintern = 1; - if ($linkintern) print ''; + if ($linkintern) { + print ''; + } print $title; - if ($linkintern) print ""; + if ($linkintern) { + print ""; + } print "'; - if (!$linkintern) print 'target ? ' target="newlink" rel="noopener"' : '').'>'; + if (!$linkintern) { + print 'target ? ' target="newlink" rel="noopener"' : '').'>'; + } print $link; - if (!$linkintern) print ''; + if (!$linkintern) { + print ''; + } print "'; - if ($obj->target == 0) print $langs->trans("BookmarkTargetReplaceWindowShort"); - if ($obj->target == 1) print $langs->trans("BookmarkTargetNewWindowShort"); + if ($obj->target == 0) { + print $langs->trans("BookmarkTargetReplaceWindowShort"); + } + if ($obj->target == 1) { + print $langs->trans("BookmarkTargetNewWindowShort"); + } print "'; - if ($obj->fk_user) - { + if ($obj->fk_user) { if (empty($cacheOfUsers[$obj->fk_user])) { $tmpuser = new User($db); $tmpuser->fetch($obj->fk_user); @@ -239,12 +263,10 @@ while ($i < min($num, $limit)) // Actions print ''; - if ($user->rights->bookmark->creer) - { + if ($user->rights->bookmark->creer) { print ''.img_edit().""; } - if ($user->rights->bookmark->supprimer) - { + if ($user->rights->bookmark->supprimer) { print 'rowid.'">'.img_delete().''; } else { print " "; diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index d83bc794baa..ba8ffe0e89f 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -323,8 +323,8 @@ class Categorie extends CommonObject $sql = "SELECT rowid, fk_parent, entity, label, description, color, fk_soc, visible, type, ref_ext"; $sql .= ", date_creation, tms, fk_user_creat, fk_user_modif"; $sql .= " FROM ".MAIN_DB_PREFIX."categorie"; - if ($id > 0) { - $sql .= " WHERE rowid = ".$id; + if ($id) { + $sql .= " WHERE rowid = ".((int) $id); } elseif (!empty($ref_ext)) { $sql .= " WHERE ref_ext LIKE '".$this->db->escape($ref_ext)."'"; } else { diff --git a/htdocs/categories/index.php b/htdocs/categories/index.php index aa2dc20e2b2..6ca392aef47 100644 --- a/htdocs/categories/index.php +++ b/htdocs/categories/index.php @@ -5,6 +5,7 @@ * Copyright (C) 2007 Patrick Raguin * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2015 Raphaël Doursenaud + * Copyright (C) 2021 Frédéric France * * 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 @@ -151,7 +152,7 @@ $cate_arbo = $categstatic->get_full_arbo($typetext); $fulltree = $cate_arbo; // Load possible missing includes -if ($conf->global->CATEGORY_SHOW_COUNTS) { +if (!empty($conf->global->CATEGORY_SHOW_COUNTS)) { if ($type == Categorie::TYPE_MEMBER) { require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; } @@ -177,7 +178,7 @@ foreach ($fulltree as $key => $val) { $desc = dol_htmlcleanlastbr($val['description']); $counter = ''; - if ($conf->global->CATEGORY_SHOW_COUNTS) { + if (!empty($conf->global->CATEGORY_SHOW_COUNTS)) { // we need only a count of the elements, so it is enough to consume only the id's from the database $elements = $type == Categorie::TYPE_ACCOUNT ? $categstatic->getObjectsInCateg("account", 1) // Categorie::TYPE_ACCOUNT is "bank_account" instead of "account" diff --git a/htdocs/categories/info.php b/htdocs/categories/info.php index 5666664b848..f5b54f50de9 100644 --- a/htdocs/categories/info.php +++ b/htdocs/categories/info.php @@ -71,11 +71,11 @@ $title = Categorie::$MAP_TYPE_TITLE_AREA[$type]; $head = categories_prepare_head($object, $type); print dol_get_fiche_head($head, 'info', $langs->trans($title), -1, 'category'); -$backtolist = (GETPOST('backtolist') ? GETPOST('backtolist') : DOL_URL_ROOT.'/categories/index.php?leftmenu=cat&type='.$type); -$linkback = ''.$langs->trans("BackToList").''; +$backtolist = (GETPOST('backtolist') ? GETPOST('backtolist') : DOL_URL_ROOT.'/categories/index.php?leftmenu=cat&type='.urlencode($type)); +$linkback = ''.$langs->trans("BackToList").''; $object->next_prev_filter = ' type = '.$object->type; $object->ref = $object->label; -$morehtmlref = '
'.$langs->trans("Root").' >> '; +$morehtmlref = '
'.$langs->trans("Root").' >> '; $ways = $object->print_all_ways(" >> ", '', 1); foreach ($ways as $way) { $morehtmlref .= $way."
\n"; diff --git a/htdocs/categories/photos.php b/htdocs/categories/photos.php index cfc722df83f..c7e574939ff 100644 --- a/htdocs/categories/photos.php +++ b/htdocs/categories/photos.php @@ -108,7 +108,8 @@ if ($object->id) { $head = categories_prepare_head($object, $type); print dol_get_fiche_head($head, 'photos', $langs->trans($title), -1, 'category'); - $linkback = ''.$langs->trans("BackToList").''; + $backtolist = (GETPOST('backtolist') ? GETPOST('backtolist') : DOL_URL_ROOT.'/categories/index.php?leftmenu=cat&type='.urlencode($type)); + $linkback = ''.$langs->trans("BackToList").''; $object->next_prev_filter = ' type = '.$object->type; $object->ref = $object->label; $morehtmlref = '
'.$langs->trans("Root").' >> '; diff --git a/htdocs/categories/traduction.php b/htdocs/categories/traduction.php index 9f2ed6936ef..de59aca376d 100644 --- a/htdocs/categories/traduction.php +++ b/htdocs/categories/traduction.php @@ -184,7 +184,8 @@ if (!empty($object->multilangs)) { print dol_get_fiche_head($head, 'translation', $langs->trans($title), -1, 'category'); -$linkback = ''.$langs->trans("BackToList").''; +$backtolist = (GETPOST('backtolist') ? GETPOST('backtolist') : DOL_URL_ROOT.'/categories/index.php?leftmenu=cat&type='.urlencode($type)); +$linkback = ''.$langs->trans("BackToList").''; $object->next_prev_filter = ' type = '.$object->type; $object->ref = $object->label; $morehtmlref = '
'.$langs->trans("Root").' >> '; diff --git a/htdocs/categories/viewcat.php b/htdocs/categories/viewcat.php index 7f19194a3c3..dedb368202d 100644 --- a/htdocs/categories/viewcat.php +++ b/htdocs/categories/viewcat.php @@ -215,18 +215,18 @@ $title = Categorie::$MAP_TYPE_TITLE_AREA[$type]; $head = categories_prepare_head($object, $type); print dol_get_fiche_head($head, 'card', $langs->trans($title), -1, 'category'); -$backtolist = (GETPOST('backtolist') ? GETPOST('backtolist') : DOL_URL_ROOT.'/categories/index.php?leftmenu=cat&type='.$type); -$linkback = ''.$langs->trans("BackToList").''; +$backtolist = (GETPOST('backtolist') ? GETPOST('backtolist') : DOL_URL_ROOT.'/categories/index.php?leftmenu=cat&type='.urlencode($type)); +$linkback = ''.$langs->trans("BackToList").''; $object->next_prev_filter = ' type = '.$object->type; $object->ref = $object->label; -$morehtmlref = '
'.$langs->trans("Root").' >> '; +$morehtmlref = '
'.$langs->trans("Root").' >> '; $ways = $object->print_all_ways(" >> ", '', 1); foreach ($ways as $way) { $morehtmlref .= $way."
\n"; } $morehtmlref .= '
'; -dol_banner_tab($object, 'label', $linkback, ($user->socid ? 0 : 1), 'label', 'label', $morehtmlref, '&type='.$type, 0, '', '', 1); +dol_banner_tab($object, 'label', $linkback, ($user->socid ? 0 : 1), 'label', 'label', $morehtmlref, '&type='.urlencode($type), 0, '', '', 1); /* diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php index 3b539895348..066001f6aa7 100644 --- a/htdocs/comm/action/card.php +++ b/htdocs/comm/action/card.php @@ -7,7 +7,7 @@ * Copyright (C) 2013 Florian Henry * Copyright (C) 2014 Cedric GROSS * Copyright (C) 2015 Alexandre Spangaro - * Copyright (C) 2018-2019 Frédéric France + * Copyright (C) 2018-2021 Frédéric France * Copyright (C) 2019 Ferran Marcet * * This program is free software; you can redistribute it and/or modify @@ -1072,7 +1072,7 @@ if ($action == 'create') { // Status print '
'.$langs->trans("Status").' / '.$langs->trans("Percentage").''; - $percent = -1; + $percent = GETPOST('complete')!=='' ? GETPOST('complete') : -1; if (GETPOSTISSET('status')) { $percent = GETPOST('status'); } elseif (GETPOSTISSET('percentage')) { @@ -1180,11 +1180,12 @@ if ($action == 'create') { $projectid = GETPOST('projectid', 'int'); - print '
'.$langs->trans("Project").''; + print '
'.$langs->trans("Project").''; print img_picto('', 'project', 'class="paddingrightonly"'); print $formproject->select_projects((!empty($societe->id) ? $societe->id : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500 widthcentpercentminusxx'); - print ' '; + print ' '; + print ''; $urloption = '?action=create&donotclearsession=1'; $url = dol_buildpath('comm/action/card.php', 2).$urloption; diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index f381351f818..ab6de76f340 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -349,6 +349,21 @@ class ActionComm extends CommonObject */ public $errors_to; + /** + * @var int number of vote for an event + */ + public $num_vote; + + /** + * @var int if event is paid + */ + public $event_paid; + + /** + * @var int status use but Event organisation module + */ + public $status; + /** * Typical value for a event that is in a todo state */ @@ -481,7 +496,8 @@ class ActionComm extends CommonObject $this->db->begin(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."actioncomm"; - $sql .= "(datec,"; + $sql .= "(ref,"; + $sql .= "datec,"; $sql .= "datep,"; $sql .= "datep2,"; $sql .= "durationp,"; // deprecated @@ -509,8 +525,12 @@ class ActionComm extends CommonObject $sql .= "email_tocc,"; $sql .= "email_tobcc,"; $sql .= "email_subject,"; - $sql .= "errors_to"; + $sql .= "errors_to,"; + $sql .= "num_vote,"; + $sql .= "event_paid,"; + $sql .= "status"; $sql .= ") VALUES ("; + $sql .= "'(PROV)', "; $sql .= "'".$this->db->idate($now)."', "; $sql .= (strval($this->datep) != '' ? "'".$this->db->idate($this->datep)."'" : "null").", "; $sql .= (strval($this->datef) != '' ? "'".$this->db->idate($this->datef)."'" : "null").", "; @@ -539,14 +559,23 @@ class ActionComm extends CommonObject $sql .= (!empty($this->email_tocc) ? "'".$this->db->escape($this->email_tocc)."'" : "null").", "; $sql .= (!empty($this->email_tobcc) ? "'".$this->db->escape($this->email_tobcc)."'" : "null").", "; $sql .= (!empty($this->email_subject) ? "'".$this->db->escape($this->email_subject)."'" : "null").", "; - $sql .= (!empty($this->errors_to) ? "'".$this->db->escape($this->errors_to)."'" : "null"); + $sql .= (!empty($this->errors_to) ? "'".$this->db->escape($this->errors_to)."'" : "null").", "; + $sql .= (!empty($this->num_vote) ? (int) $this->num_vote : "null").", "; + $sql .= (!empty($this->event_paid) ? (int) $this->event_paid : 0).", "; + $sql .= (!empty($this->status) ? (int) $this->status : "0"); $sql .= ")"; dol_syslog(get_class($this)."::add", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $this->ref = $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."actioncomm", "id"); - + $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm SET ref='".$this->db->escape($this->ref)."' WHERE id=".$this->id; + $resql = $this->db->query($sql); + if (!$resql) { + $error++; + dol_syslog('Error to process ref: '.$this->db->lasterror(), LOG_ERR); + $this->errors[] = $this->db->lasterror(); + } // Now insert assigned users if (!$error) { //dol_syslog(var_export($this->userassigned, true)); @@ -697,7 +726,7 @@ class ActionComm extends CommonObject global $langs; $sql = "SELECT a.id,"; - $sql .= " a.id as ref,"; + $sql .= " a.ref as ref,"; $sql .= " a.entity,"; $sql .= " a.ref_ext,"; $sql .= " a.datep,"; @@ -716,14 +745,15 @@ class ActionComm extends CommonObject $sql .= " a.email_msgid, a.email_subject, a.email_from, a.email_to, a.email_tocc, a.email_tobcc, a.errors_to,"; $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label, c.color as type_color, c.picto as type_picto,"; $sql .= " s.nom as socname,"; - $sql .= " u.firstname, u.lastname as lastname"; + $sql .= " u.firstname, u.lastname as lastname,"; + $sql .= " num_vote, event_paid, a.status"; $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a "; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action=c.id "; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc"; $sql .= " WHERE "; if ($ref) { - $sql .= " a.id = ".((int) $ref); // No field ref, we use id + $sql .= " a.ref = '".$this->db->escape($ref)."'"; } elseif ($ref_ext) { $sql .= " a.ref_ext = '".$this->db->escape($ref_ext)."'"; } elseif ($email_msgid) { @@ -798,6 +828,10 @@ class ActionComm extends CommonObject $this->elementid = $obj->elementid; $this->elementtype = $obj->elementtype; + $this->num_vote = $obj->num_vote; + $this->event_paid = $obj->event_paid; + $this->status = $obj->status; + $this->fetchResources(); } $this->db->free($resql); @@ -1004,7 +1038,7 @@ class ActionComm extends CommonObject * @param int $notrigger 1 = disable triggers, 0 = enable triggers * @return int <0 if KO, >0 if OK */ - public function update($user, $notrigger = 0) + public function update(User $user, $notrigger = 0) { global $langs, $conf, $hookmanager; @@ -1080,6 +1114,15 @@ class ActionComm extends CommonObject if (!empty($this->elementtype)) { $sql .= ", elementtype=".($this->elementtype ? "'".$this->db->escape($this->elementtype)."'" : "null"); } + if (!empty($this->num_vote)) { + $sql .= ", num_vote=".($this->num_vote ? (int) $this->num_vote : null); + } + if (!empty($this->event_paid)) { + $sql .= ", event_paid=".($this->event_paid ? (int) $this->event_paid : 0); + } + if (!empty($this->status)) { + $sql .= ", status=".($this->status ? (int) $this->status : 0); + } $sql .= " WHERE id=".$this->id; dol_syslog(get_class($this)."::update", LOG_DEBUG); @@ -1759,7 +1802,8 @@ class ActionComm extends CommonObject $sql .= " a.priority, a.fulldayevent, a.location, a.transparency,"; $sql .= " u.firstname, u.lastname, u.email,"; $sql .= " s.nom as socname,"; - $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label"; + $sql .= " c.id as type_id, c.code as type_code, c.libelle as type_label,"; + $sql .= " num_vote, event_paid, a.status"; $sql .= " FROM (".MAIN_DB_PREFIX."c_actioncomm as c, ".MAIN_DB_PREFIX."actioncomm as a)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; // Link to get author of event for export $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc"; @@ -1889,6 +1933,9 @@ class ActionComm extends CommonObject $event['url'] = $url; $event['created'] = $this->db->jdate($obj->datec) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600)); $event['modified'] = $this->db->jdate($obj->datem) - (empty($conf->global->AGENDA_EXPORT_FIX_TZ) ? 0 : ($conf->global->AGENDA_EXPORT_FIX_TZ * 3600)); + $event['num_vote'] = $this->num_vote; + $event['event_paid'] = $this->event_paid; + $event['status'] = $this->status; // TODO: find a way to call "$this->fetch_userassigned();" without override "$this" properties $this->id = $obj->id; @@ -2079,6 +2126,7 @@ class ActionComm extends CommonObject $this->datef = $now; $this->fulldayevent = 0; $this->percentage = 0; + $this->status = 0; $this->location = 'Location'; $this->transparency = 1; // 1 means opaque $this->priority = 1; diff --git a/htdocs/comm/action/class/api_agendaevents.class.php b/htdocs/comm/action/class/api_agendaevents.class.php index a2961b97974..9ad3dd8ce51 100644 --- a/htdocs/comm/action/class/api_agendaevents.class.php +++ b/htdocs/comm/action/class/api_agendaevents.class.php @@ -16,9 +16,10 @@ * along with this program. If not, see . */ - use Luracast\Restler\RestException; +use Luracast\Restler\RestException; + +require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; - require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; /** * API class for Agenda Events @@ -66,7 +67,7 @@ class AgendaEvents extends DolibarrApi if (!DolibarrApiAccess::$user->rights->agenda->myactions->read) { throw new RestException(401, "Insufficient rights to read an event"); } - if ($id == 0) { + if ($id === 0) { $result = $this->actioncomm->initAsSpecimen(); } else { $result = $this->actioncomm->fetch($id); diff --git a/htdocs/comm/action/class/cactioncomm.class.php b/htdocs/comm/action/class/cactioncomm.class.php index 3b759db4098..8483839b944 100644 --- a/htdocs/comm/action/class/cactioncomm.class.php +++ b/htdocs/comm/action/class/cactioncomm.class.php @@ -153,7 +153,7 @@ class CActionComm public function liste_array($active = '', $idorcode = 'id', $excludetype = '', $onlyautoornot = 0, $morefilter = '', $shortlabel = 0) { // phpcs:enable - global $langs, $conf; + global $langs, $conf, $user; $langs->load("commercial"); $repid = array(); @@ -191,23 +191,29 @@ class CActionComm $qualified = 0; // We discard detailed system events. We keep only the 2 generic lines (AC_OTH and AC_OTH_AUTO) } - if ($qualified && $obj->module) { - if ($obj->module == 'invoice' && !$conf->facture->enabled) { + if ($qualified && !empty($obj->module)) { + if ($obj->module == 'invoice' && empty($conf->facture->enabled) && empty($user->facture->lire)) { $qualified = 0; } - if ($obj->module == 'order' && !$conf->commande->enabled) { + if ($obj->module == 'order' && empty($conf->commande->enabled) && empty($user->commande->lire)) { $qualified = 0; } - if ($obj->module == 'propal' && !$conf->propal->enabled) { + if ($obj->module == 'propal' && empty($conf->propal->enabled) && empty($user->propale->lire)) { $qualified = 0; } - if ($obj->module == 'invoice_supplier' && ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !$conf->supplier_invoice->enabled)) { + if ($obj->module == 'invoice_supplier' && ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || empty($conf->supplier_invoice->enabled)) && empty($user->fournisseur->facture->lire)) { $qualified = 0; } - if ($obj->module == 'order_supplier' && ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !$conf->supplier_order->enabled)) { + if ($obj->module == 'order_supplier' && ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || empty($conf->supplier_order->enabled)) && empty($user->fournisseur->commande->lire)) { $qualified = 0; } - if ($obj->module == 'shipping' && !$conf->expedition->enabled) { + if ($obj->module == 'shipping' && empty($conf->expedition->enabled) && empty($user->expedition->lire)) { + $qualified = 0; + } + if (preg_match('/@eventorganization/', $obj->module) && empty($conf->eventorganization->enabled) && empty($user->eventorganization->read)) { + $qualified = 0; + } + if (!preg_match('/^system/', $obj->type) && isset($conf->{$obj->module}) && empty($conf->{$obj->module}->enabled)) { $qualified = 0; } } @@ -247,12 +253,18 @@ class CActionComm $repcode['AC_ALL_AUTO'] = '-- '.$langs->trans("ActionAC_AUTO"); } if ($typecalendar == 'module') { + //TODO check if possible to push it between system and systemauto + if (preg_match('/@/', $obj->module)) { + $module = explode('@', $obj->module)[1]; + } else { + $module = $obj->module; + } $label = '   '.$label; - if (!isset($repcode['AC_ALL_'.strtoupper($obj->module)])) { // If first time for this module + if (!isset($repcode['AC_ALL_'.strtoupper($module)])) { // If first time for this module $idforallfornewmodule--; } - $repid[$idforallfornewmodule] = $langs->trans("ActionAC_ALL_".strtoupper($obj->module)); - $repcode['AC_ALL_'.strtoupper($obj->module)] = '-- '.$langs->trans("Module").' '.ucfirst($obj->module); + $repid[$idforallfornewmodule] = $langs->trans("ActionAC_ALL_".strtoupper($module)); + $repcode['AC_ALL_'.strtoupper($module)] = '-- '.$langs->trans("Module").' '.ucfirst($module); } } $repid[$obj->id] = $label; diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php index a125dc466f8..3616de126be 100644 --- a/htdocs/comm/action/index.php +++ b/htdocs/comm/action/index.php @@ -7,7 +7,7 @@ * Copyright (C) 2014 Cedric GROSS * Copyright (C) 2015 Marcos García * Copyright (C) 2017 Open-DSI - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-2021 Frédéric France * * 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 @@ -258,7 +258,13 @@ if (empty($conf->global->AGENDA_DISABLE_EXT)) { $buggedfile = 'AGENDA_EXT_BUGGEDFILE'.$i; if (!empty($conf->global->$source) && !empty($conf->global->$name)) { // Note: $conf->global->buggedfile can be empty or 'uselocalandtznodaylight' or 'uselocalandtzdaylight' - $listofextcals[] = array('src'=>$conf->global->$source, 'name'=>$conf->global->$name, 'offsettz'=>$conf->global->$offsettz, 'color'=>$conf->global->$color, 'buggedfile'=>(isset($conf->global->buggedfile) ? $conf->global->buggedfile : 0)); + $listofextcals[] = array( + 'src'=>$conf->global->$source, + 'name'=>$conf->global->$name, + 'offsettz' => (!empty($conf->global->$offsettz) ? $conf->global->$offsettz : 0), + 'color'=>$conf->global->$color, + 'buggedfile'=>(isset($conf->global->buggedfile) ? $conf->global->buggedfile : 0) + ); } } } @@ -275,7 +281,13 @@ if (empty($user->conf->AGENDA_DISABLE_EXT)) { $buggedfile = 'AGENDA_EXT_BUGGEDFILE_'.$user->id.'_'.$i; if (!empty($user->conf->$source) && !empty($user->conf->$name)) { // Note: $conf->global->buggedfile can be empty or 'uselocalandtznodaylight' or 'uselocalandtzdaylight' - $listofextcals[] = array('src'=>$user->conf->$source, 'name'=>$user->conf->$name, 'offsettz'=>$user->conf->$offsettz, 'color'=>$user->conf->$color, 'buggedfile'=>(isset($user->conf->buggedfile) ? $user->conf->buggedfile : 0)); + $listofextcals[] = array( + 'src'=>$user->conf->$source, + 'name'=>$user->conf->$name, + 'offsettz' => (!empty($user->conf->$offsettz) ? $user->conf->$offsettz : 0), + 'color'=>$user->conf->$color, + 'buggedfile'=>(isset($user->conf->buggedfile) ? $user->conf->buggedfile : 0) + ); } } } diff --git a/htdocs/comm/action/rapport/index.php b/htdocs/comm/action/rapport/index.php index 44bd8547e8a..908819e1d1a 100644 --- a/htdocs/comm/action/rapport/index.php +++ b/htdocs/comm/action/rapport/index.php @@ -38,6 +38,7 @@ $action = GETPOST('action', 'aZ09'); $month = GETPOST('month', 'int'); $year = GETPOST('year', 'int'); +$optioncss = GETPOST('optioncss', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); diff --git a/htdocs/comm/index.php b/htdocs/comm/index.php index d9fce1551e3..87345bb905e 100644 --- a/htdocs/comm/index.php +++ b/htdocs/comm/index.php @@ -720,17 +720,17 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU /* * Last actions */ -if ($user->rights->agenda->myactions->read) { +/*if ($user->rights->agenda->myactions->read) { show_array_last_actions_done($max); -} +}*/ /* * Actions to do */ -if ($user->rights->agenda->myactions->read) { +/*if ($user->rights->agenda->myactions->read) { show_array_actions_to_do($max); -} +}*/ /* diff --git a/htdocs/comm/mailing/card.php b/htdocs/comm/mailing/card.php index bd427115a57..e0a9138244d 100644 --- a/htdocs/comm/mailing/card.php +++ b/htdocs/comm/mailing/card.php @@ -207,8 +207,8 @@ if (empty($reshook)) { $substitutionarray['__OTHER4__'] = $other4; $substitutionarray['__OTHER5__'] = $other5; $substitutionarray['__USER_SIGNATURE__'] = $signature; // Signature is empty when ran from command line or taken from user in parameter) - $substitutionarray['__CHECK_READ__'] = ''; - $substitutionarray['__UNSUBSCRIBE__'] = ''.$langs->trans("MailUnsubcribe").''; + $substitutionarray['__CHECK_READ__'] = ''; + $substitutionarray['__UNSUBSCRIBE__'] = ''.$langs->trans("MailUnsubcribe").''; $onlinepaymentenabled = 0; if (!empty($conf->paypal->enabled)) { diff --git a/htdocs/comm/mailing/class/advtargetemailing.class.php b/htdocs/comm/mailing/class/advtargetemailing.class.php index 719ec5b6c49..c811b673197 100644 --- a/htdocs/comm/mailing/class/advtargetemailing.class.php +++ b/htdocs/comm/mailing/class/advtargetemailing.class.php @@ -228,7 +228,7 @@ class AdvanceTargetingMailing extends CommonObject $sql .= " t.tms"; $sql .= " FROM ".MAIN_DB_PREFIX."advtargetemailing as t"; - $sql .= " WHERE t.rowid = ".$id; + $sql .= " WHERE t.rowid = ".((int) $id); dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); $resql = $this->db->query($sql); @@ -419,7 +419,7 @@ class AdvanceTargetingMailing extends CommonObject $sql .= " filtervalue=".(isset($this->filtervalue) ? "'".$this->db->escape($this->filtervalue)."'" : "null").","; $sql .= " fk_user_mod=".$user->id; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); @@ -459,7 +459,7 @@ class AdvanceTargetingMailing extends CommonObject if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."advtargetemailing"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::delete sql=".$sql); $resql = $this->db->query($sql); diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index 754d01e3b78..a206e61064f 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -215,8 +215,8 @@ if (empty($reshook)) { } } } - } // Delete proposal - elseif ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) { + } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) { + // Delete proposal $result = $object->delete($user); if ($result > 0) { header('Location: '.DOL_URL_ROOT.'/comm/propal/list.php?restore_lastsearch_values=1'); @@ -225,8 +225,8 @@ if (empty($reshook)) { $langs->load("errors"); setEventMessages($object->error, $object->errors, 'errors'); } - } // Remove line - elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) { + } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) { + // Remove line $result = $object->deleteline($lineid); // reorder lines if ($result) { @@ -250,8 +250,8 @@ if (empty($reshook)) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit(); - } // Validation - elseif ($action == 'confirm_validate' && $confirm == 'yes' && $usercanvalidate) { + } elseif ($action == 'confirm_validate' && $confirm == 'yes' && $usercanvalidate) { + // Validation $idwarehouse = GETPOST('idwarehouse', 'int'); $result = $object->valid($user); if ($result >= 0) { @@ -308,17 +308,17 @@ if (empty($reshook)) { if ($result < 0) { dol_print_error($db, $object->error); } - } // Positionne ref client - elseif ($action == 'setref_client' && $usercancreate) { + } elseif ($action == 'setref_client' && $usercancreate) { + // Positionne ref client $result = $object->set_ref_client($user, GETPOST('ref_client')); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } // Set incoterm - elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled) && $usercancreate) { + } elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled) && $usercancreate) { + // Set incoterm $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); - } // Create proposal - elseif ($action == 'add' && $usercancreate) { + } elseif ($action == 'add' && $usercancreate) { + // Create proposal $object->socid = $socid; $object->fetch_thirdparty(); @@ -554,8 +554,8 @@ if (empty($reshook)) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } - } // Standard creation - else { + } else { + // Standard creation $id = $object->create($user); } @@ -616,8 +616,8 @@ if (empty($reshook)) { } } } - } // Classify billed - elseif ($action == 'classifybilled' && $usercanclose) { + } elseif ($action == 'classifybilled' && $usercanclose) { + // Classify billed $db->begin(); $result = $object->cloture($user, $object::STATUS_BILLED, ''); @@ -631,8 +631,8 @@ if (empty($reshook)) { } else { $db->rollback(); } - } // Close proposal - elseif ($action == 'confirm_closeas' && $usercanclose && !GETPOST('cancel', 'alpha')) { + } elseif ($action == 'confirm_closeas' && $usercanclose && !GETPOST('cancel', 'alpha')) { + // Close proposal if (!(GETPOST('statut', 'int') > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CloseAs")), null, 'errors'); $action = 'closeas'; @@ -654,8 +654,8 @@ if (empty($reshook)) { } } } - } // Reopen proposal - elseif ($action == 'confirm_reopen' && $usercanclose && !GETPOST('cancel', 'alpha')) { + } elseif ($action == 'confirm_reopen' && $usercanclose && !GETPOST('cancel', 'alpha')) { + // Reopen proposal // prevent browser refresh from reopening proposal several times if ($object->statut == Propal::STATUS_SIGNED || $object->statut == Propal::STATUS_NOTSIGNED || $object->statut == Propal::STATUS_BILLED) { $db->begin(); @@ -672,11 +672,11 @@ if (empty($reshook)) { $db->rollback(); } } - } // add lines from objectlinked - elseif ($action == 'import_lines_from_object' + } elseif ($action == 'import_lines_from_object' && $user->rights->propal->creer && $object->statut == Propal::STATUS_DRAFT ) { + // add lines from objectlinked $fromElement = GETPOST('fromelement'); $fromElementid = GETPOST('fromelementid'); $importLines = GETPOST('line_checkbox'); @@ -795,8 +795,8 @@ if (empty($reshook)) { // Set if we used free entry or predefined product $predef = ''; $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : ''); - $price_ht = price2num(GETPOST('price_ht')); - $price_ht_devise = price2num(GETPOST('multicurrency_price_ht')); + $price_ht = price2num(GETPOST('price_ht'), 'MU', 2); + $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2); $prod_entry_mode = GETPOST('prod_entry_mode'); if ($prod_entry_mode == 'free') { $idprod = 0; @@ -898,8 +898,8 @@ if (empty($reshook)) { $tva_npr = $prod->multiprices_recuperableonly[$object->thirdparty->price_level]; } } - } // If price per customer - elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { + } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { + // If price per customer require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php'; $prodcustprice = new Productcustomerprice($db); @@ -924,8 +924,8 @@ if (empty($reshook)) { } } } - } // If price per quantity - elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) { + } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) { + // If price per quantity if ($prod->prices_by_qty[0]) { // yes, this product has some prices per quantity // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp']. $pqp = GETPOST('pbq', 'int'); @@ -945,8 +945,8 @@ if (empty($reshook)) { break; } } - } // If price per quantity and customer - elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { + } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { + // If price per quantity and customer if ($prod->prices_by_qty[$object->thirdparty->price_level]) { // yes, this product has some prices per quantity // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp']. $pqp = GETPOST('pbq', 'int'); @@ -975,9 +975,9 @@ if (empty($reshook)) { if (!empty($price_ht) || $price_ht === '0') { $pu_ht = price2num($price_ht, 'MU'); $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); - } // On reevalue prix selon taux tva car taux tva transaction peut etre different - // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). - elseif ($tmpvat != $tmpprodvat) { + } elseif ($tmpvat != $tmpprodvat) { + // On reevalue prix selon taux tva car taux tva transaction peut etre different + // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). if ($price_base_type != 'HT') { $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU'); } else { @@ -1167,15 +1167,15 @@ if (empty($reshook)) { } } } - } // Update a line within proposal - elseif ($action == 'updateline' && $usercancreate && GETPOST('save')) { + } elseif ($action == 'updateline' && $usercancreate && GETPOST('save')) { + // Update a line within proposal // Define info_bits $info_bits = 0; if (preg_match('/\*/', GETPOST('tva_tx'))) { $info_bits |= 0x01; } - // Clean parameters + // Clean parameters $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml')); // Define vat_rate @@ -1183,13 +1183,13 @@ if (empty($reshook)) { $vat_rate = str_replace('*', '', $vat_rate); $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc); $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc); - $pu_ht = GETPOST('price_ht'); + $pu_ht = price2num(GETPOST('price_ht'), '', 2); // Add buying price $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : ''); $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value - $pu_ht_devise = GETPOST('multicurrency_subprice'); + $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2); $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); @@ -1313,36 +1313,36 @@ if (empty($reshook)) { } elseif ($action == 'classin' && $usercancreate) { // Set project $object->setProject(GETPOST('projectid', 'int')); - } // Delivery time - elseif ($action == 'setavailability' && $usercancreate) { + } elseif ($action == 'setavailability' && $usercancreate) { + // Delivery time $result = $object->set_availability($user, GETPOST('availability_id', 'int')); - } // Origin of the commercial proposal - elseif ($action == 'setdemandreason' && $usercancreate) { + } elseif ($action == 'setdemandreason' && $usercancreate) { + // Origin of the commercial proposal $result = $object->set_demand_reason($user, GETPOST('demand_reason_id', 'int')); - } // Terms of payment - elseif ($action == 'setconditions' && $usercancreate) { + } elseif ($action == 'setconditions' && $usercancreate) { + // Terms of payment $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); } elseif ($action == 'setremisepercent' && $usercancreate) { $result = $object->set_remise_percent($user, $_POST['remise_percent']); } elseif ($action == 'setremiseabsolue' && $usercancreate) { $result = $object->set_remise_absolue($user, $_POST['remise_absolue']); - } // Payment choice - elseif ($action == 'setmode' && $usercancreate) { + } elseif ($action == 'setmode' && $usercancreate) { + // Payment choice $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); - } // Multicurrency Code - elseif ($action == 'setmulticurrencycode' && $usercancreate) { + } elseif ($action == 'setmulticurrencycode' && $usercancreate) { + // Multicurrency Code $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha')); - } // Multicurrency rate - elseif ($action == 'setmulticurrencyrate' && $usercancreate) { - $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx'))); - } // bank account - elseif ($action == 'setbankaccount' && $usercancreate) { + } elseif ($action == 'setmulticurrencyrate' && $usercancreate) { + // Multicurrency rate + $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')), GETPOST('calculation_mode', 'int')); + } elseif ($action == 'setbankaccount' && $usercancreate) { + // bank account $result = $object->setBankAccount(GETPOST('fk_account', 'int')); - } // shipping method - elseif ($action == 'setshippingmethod' && $usercancreate) { + } elseif ($action == 'setshippingmethod' && $usercancreate) { + // shipping method $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int')); - }// warehouse - elseif ($action == 'setwarehouse' && $usercancreate) { + } elseif ($action == 'setwarehouse' && $usercancreate) { + // warehouse $result = $object->setWarehouse(GETPOST('warehouse_id', 'int')); } elseif ($action == 'update_extras') { $object->oldcopy = dol_clone($object); @@ -1383,15 +1383,15 @@ if (empty($reshook)) { setEventMessages($object->error, $object->errors, 'errors'); } } - } // Toggle the status of a contact - elseif ($action == 'swapstatut') { + } elseif ($action == 'swapstatut') { + // Toggle the status of a contact if ($object->fetch($id) > 0) { $result = $object->swapContactStatus(GETPOST('ligne')); } else { dol_print_error($db); } - } // Delete a contact - elseif ($action == 'deletecontact') { + } elseif ($action == 'deletecontact') { + // Delete a contact $object->fetch($id); $result = $object->delete_contact($lineid); @@ -1570,7 +1570,8 @@ if ($action == 'create') { console.log("We have changed the company - Reload page"); var socid = $(this).val(); // reload page - window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid+"&ref_client="+$("input[name=ref_client]").val(); + $("input[name=action]").val("create"); + $("form[name=addprop]").submit(); }); }); '; @@ -1907,17 +1908,17 @@ if ($action == 'create') { } $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('SetAcceptedRefused'), $text, 'confirm_closeas', $formquestion, '', 1, 250); - } // Confirm delete - elseif ($action == 'delete') { + } elseif ($action == 'delete') { + // Confirm delete $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteProp'), $langs->trans('ConfirmDeleteProp', $object->ref), 'confirm_delete', '', 0, 1); - } // Confirm reopen - elseif ($action == 'reopen') { + } elseif ($action == 'reopen') { + // Confirm reopen $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ReOpen'), $langs->trans('ConfirmReOpenProp', $object->ref), 'confirm_reopen', '', 0, 1); - } // Confirmation delete product/service line - elseif ($action == 'ask_deleteline') { + } elseif ($action == 'ask_deleteline') { + // Confirmation delete product/service line $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1); - } // Confirm validate proposal - elseif ($action == 'validate') { + } elseif ($action == 'validate') { + // Confirm validate proposal $error = 0; // We verify whether the object is provisionally numbering @@ -2113,6 +2114,24 @@ if ($action == 'create') { print '
'; + print ''; + if ($action != 'editmode' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) { + print ''; + } + print '
'; + print $langs->trans('PaymentMode'); + print 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetMode'), 1).'
'; + print '
'; + if ($object->statut == Propal::STATUS_DRAFT && $action == 'editmode' && $usercancreate) { + $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1); + } else { + $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none'); + } + print '
'; @@ -2200,24 +2219,6 @@ if ($action == 'create') { print '
'; - print ''; - if ($action != 'editmode' && $object->statut == Propal::STATUS_DRAFT && $usercancreate) { - print ''; - } - print '
'; - print $langs->trans('PaymentMode'); - print 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetMode'), 1).'
'; - print '
'; - if ($object->statut == Propal::STATUS_DRAFT && $action == 'editmode' && $usercancreate) { - $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1); - } else { - $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none'); - } - print '
'; - if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) { // Multicurrency Amount HT print ''; print ''; diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index 553362687b6..197c9c7074f 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -1644,14 +1644,15 @@ class Propal extends CommonObject $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").","; $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").","; $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").""; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } if (!$error) { @@ -1891,7 +1892,8 @@ class Propal extends CommonObject $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'propale/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->error = $this->db->lasterror(); + $error++; + $this->error = $this->db->lasterror(); } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments @@ -2457,7 +2459,8 @@ class Propal extends CommonObject dol_syslog(get_class($this)."::reopen", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } if (!$error) { if (!$notrigger) { @@ -2993,7 +2996,7 @@ class Propal extends CommonObject $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal'; $sql .= ' SET fk_availability = '.$availability_id; - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); dol_syslog(__METHOD__.' availability('.$availability_id.')', LOG_DEBUG); $resql = $this->db->query($sql); @@ -3057,7 +3060,7 @@ class Propal extends CommonObject $sql = 'UPDATE '.MAIN_DB_PREFIX.'propal'; $sql .= ' SET fk_input_reason = '.$demand_reason_id; - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); dol_syslog(__METHOD__.' demand_reason('.$demand_reason_id.')', LOG_DEBUG); $resql = $this->db->query($sql); diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php index a1cae674f68..4c8ee0894f5 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -95,6 +95,7 @@ $search_availability = GETPOST('search_availability', 'int'); $search_categ_cus = GETPOST("search_categ_cus", 'int'); $search_fk_cond_reglement = GETPOST("search_fk_cond_reglement", 'int'); $search_fk_shipping_method = GETPOST("search_fk_shipping_method", 'int'); +$search_fk_input_reason = GETPOST("search_fk_input_reason", 'int'); $search_fk_mode_reglement = GETPOST("search_fk_mode_reglement", 'int'); $search_btn = GETPOST('button_search', 'alpha'); $search_remove_btn = GETPOST('button_removefilter', 'alpha'); @@ -189,6 +190,7 @@ $arrayfields = array( 'p.date_livraison'=>array('label'=>"DeliveryDate", 'checked'=>0), 'ava.rowid'=>array('label'=>"AvailabilityPeriod", 'checked'=>0), 'p.fk_shipping_method'=>array('label'=>"SendingMethod", 'checked'=>0, 'enabled'=>!empty($conf->expedition->enabled)), + 'p.fk_input_reason'=>array('label'=>"Origin", 'checked'=>0, 'enabled'=>1), 'p.fk_cond_reglement'=>array('label'=>"PaymentConditionsShort", 'checked'=>0), 'p.fk_mode_reglement'=>array('label'=>"PaymentMode", 'checked'=>0), 'p.total_ht'=>array('label'=>"AmountHT", 'checked'=>1), @@ -222,7 +224,8 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; */ if (GETPOST('cancel', 'alpha')) { - $action = 'list'; $massaction = ''; + $action = 'list'; + $massaction = ''; } if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; @@ -277,6 +280,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_categ_cus = 0; $search_fk_cond_reglement = ''; $search_fk_shipping_method = ''; + $search_fk_input_reason = ''; $search_fk_mode_reglement = ''; } if ($object_statut != '') { @@ -414,7 +418,7 @@ $sql .= ' p.rowid, p.entity, p.note_private, p.total_ht, p.total_tva, p.total_tt $sql .= ' p.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva, p.multicurrency_total_ttc,'; $sql .= ' p.datec as date_creation, p.tms as date_update, p.date_cloture as date_cloture,'; $sql .= ' p.note_public, p.note_private,'; -$sql .= ' p.fk_cond_reglement,p.fk_mode_reglement,p.fk_shipping_method,'; +$sql .= ' p.fk_cond_reglement,p.fk_mode_reglement,p.fk_shipping_method,p.fk_input_reason,'; $sql .= " pr.rowid as project_id, pr.ref as project_ref, pr.title as project_label,"; $sql .= ' u.login'; if (!$user->rights->societe->client->voir && !$socid) { @@ -547,6 +551,9 @@ if ($search_fk_cond_reglement > 0) { if ($search_fk_shipping_method > 0) { $sql .= " AND p.fk_shipping_method = ".$db->escape($search_fk_shipping_method); } +if ($search_fk_input_reason > 0) { + $sql .= " AND p.fk_input_reason = ".$db->escape($search_fk_input_reason); +} if ($search_fk_mode_reglement > 0) { $sql .= " AND p.fk_mode_reglement = ".$db->escape($search_fk_mode_reglement); } @@ -735,6 +742,9 @@ if ($resql) { if ($search_fk_shipping_method > 0) { $param .= '&search_fk_shipping_method='.$search_fk_shipping_method; } + if ($search_fk_input_reason > 0) { + $param .= '&search_fk_input_reason='.$search_fk_input_reason; + } if ($search_fk_mode_reglement > 0) { $param .= '&search_fk_mode_reglement='.$search_fk_mode_reglement; } @@ -983,6 +993,12 @@ if ($resql) { $form->selectShippingMethod($search_fk_shipping_method, 'search_fk_shipping_method', '', 1, '', 1); print ''; } + // Source - Input reason + if (!empty($arrayfields['p.fk_input_reason']['checked'])) { + print ''; + } // Payment term if (!empty($arrayfields['p.fk_cond_reglement']['checked'])) { print ''; + if (!$i) { + $totalarray['nbfield']++; + } + } // Payment terms if (!empty($arrayfields['p.fk_cond_reglement']['checked'])) { print '
'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).''.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).''; + $form->selectInputReason($search_fk_input_reason, 'search_fk_input_reason', '', 1, 'maxwidth125', 1); + print ''; @@ -1169,6 +1185,9 @@ if ($resql) { if (!empty($arrayfields['p.fk_shipping_method']['checked'])) { print_liste_field_titre($arrayfields['p.fk_shipping_method']['label'], $_SERVER["PHP_SELF"], "p.fk_shipping_method", "", $param, '', $sortfield, $sortorder); } + if (!empty($arrayfields['p.fk_input_reason']['checked'])) { + print_liste_field_titre($arrayfields['p.fk_input_reason']['label'], $_SERVER["PHP_SELF"], "p.fk_input_reason", "", $param, '', $sortfield, $sortorder); + } if (!empty($arrayfields['p.fk_cond_reglement']['checked'])) { print_liste_field_titre($arrayfields['p.fk_cond_reglement']['label'], $_SERVER["PHP_SELF"], "p.fk_cond_reglement", "", $param, '', $sortfield, $sortorder); } @@ -1182,7 +1201,7 @@ if ($resql) { print_liste_field_titre($arrayfields['p.total_tva']['label'], $_SERVER["PHP_SELF"], 'p.total_tva', '', $param, 'class="right"', $sortfield, $sortorder); } if (!empty($arrayfields['p.total_ttc']['checked'])) { - print_liste_field_titre($arrayfields['p.total_ttc']['label'], $_SERVER["PHP_SELF"], 'p.total', '', $param, 'class="right"', $sortfield, $sortorder); + print_liste_field_titre($arrayfields['p.total_ttc']['label'], $_SERVER["PHP_SELF"], 'p.total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); } if (!empty($arrayfields['p.total_ht_invoiced']['checked'])) { print_liste_field_titre($arrayfields['p.total_ht_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $param, 'class="right"', $sortfield, $sortorder); @@ -1473,7 +1492,7 @@ if ($resql) { $totalarray['nbfield']++; } } - //Shipping Method + // Shipping Method if (!empty($arrayfields['p.fk_shipping_method']['checked'])) { print ''; $form->formSelectShippingMethod('', $obj->fk_shipping_method, 'none', 1); @@ -1482,6 +1501,17 @@ if ($resql) { $totalarray['nbfield']++; } } + // Source - input reason + if (!empty($arrayfields['p.fk_input_reason']['checked'])) { + print ''; + if ($obj->fk_input_reason > 0) { + print $form->cache_demand_reason[$obj->fk_input_reason]['label']; + } + print ''; diff --git a/htdocs/comm/propal/stats/index.php b/htdocs/comm/propal/stats/index.php index 326299448f7..e18891f3c60 100644 --- a/htdocs/comm/propal/stats/index.php +++ b/htdocs/comm/propal/stats/index.php @@ -123,7 +123,8 @@ $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); if (!$mesg) { $px1->SetData($data); - $i = $startyear; $legend = array(); + $i = $startyear; + $legend = array(); while ($i <= $endyear) { $legend[] = $i; $i++; @@ -158,7 +159,8 @@ $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); if (!$mesg) { $px2->SetData($data); - $i = $startyear; $legend = array(); + $i = $startyear; + $legend = array(); while ($i <= $endyear) { $legend[] = $i; $i++; @@ -202,7 +204,8 @@ $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); if (!$mesg) { $px3->SetData($data); - $i = $startyear; $legend = array(); + $i = $startyear; + $legend = array(); while ($i <= $endyear) { $legend[] = $i; $i++; diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index 375ba4a53ff..74de84b861a 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -490,7 +490,7 @@ if (empty($reshook)) { setEventMessages($object->error, $object->errors, 'errors'); } } elseif ($action == 'classifyunbilled' && $usercancreate) { - $ret = $object->classifyUnBilled(); + $ret = $object->classifyUnBilled($user); if ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); } @@ -540,7 +540,7 @@ if (empty($reshook)) { $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha')); } elseif ($action == 'setmulticurrencyrate' && $usercancreate) { // Multicurrency rate - $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx'))); + $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')), GETPOST('calculation_mode', 'int')); } elseif ($action == 'setavailability' && $usercancreate) { $result = $object->availability(GETPOST('availability_id')); if ($result < 0) { @@ -616,8 +616,8 @@ if (empty($reshook)) { // Set if we used free entry or predefined product $predef = ''; $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : ''); - $price_ht = price2num(GETPOST('price_ht'), 'MU'); - $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU'); + $price_ht = price2num(GETPOST('price_ht'), 'MU', 2); + $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2); $prod_entry_mode = GETPOST('prod_entry_mode'); if ($prod_entry_mode == 'free') { $idprod = 0; @@ -984,9 +984,9 @@ if (empty($reshook)) { $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml')); - $pu_ht = GETPOST('price_ht'); + $pu_ht = price2num(GETPOST('price_ht'), '', 2); $vat_rate = (GETPOST('tva_tx') ?GETPOST('tva_tx') : 0); - $pu_ht_devise = GETPOST('multicurrency_subprice'); + $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2); // Define info_bits $info_bits = 0; @@ -1580,7 +1580,8 @@ if ($action == 'create' && $usercancreate) { console.log("We have changed the company - Reload page"); var socid = $(this).val(); // reload page - window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid+"&ref_client="+$("input[name=ref_client]").val(); + $("input[name=action]").val("create"); + $("form[name=crea_commande]").submit(); }); }); '; diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index aac06dc4775..0975bfbd7ef 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -1060,7 +1060,7 @@ class Commande extends CommonOrder $initialref = $this->ref; } - $sql = 'UPDATE '.MAIN_DB_PREFIX."commande SET ref='".$this->db->escape($initialref)."' WHERE rowid=".$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX."commande SET ref='".$this->db->escape($initialref)."' WHERE rowid=".((int) $this->id); if ($this->db->query($sql)) { $this->ref = $initialref; @@ -2741,7 +2741,7 @@ class Commande extends CommonOrder $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande'; $sql .= ' SET fk_availability = '.$availability_id; - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); @@ -2805,7 +2805,7 @@ class Commande extends CommonOrder $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande'; $sql .= ' SET fk_input_reason = '.$demand_reason_id; - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); @@ -2962,11 +2962,12 @@ class Commande extends CommonOrder /** * Classify the order as not invoiced * - * @return int <0 if ko, >0 if ok + * @param User $user Object user making the change + * @param int $notrigger 1=Does not execute triggers, 0=execute triggers + * @return int <0 if ko, >0 if ok */ - public function classifyUnBilled() + public function classifyUnBilled(User $user, $notrigger = 0) { - global $conf, $user, $langs; $error = 0; $this->db->begin(); @@ -2981,12 +2982,14 @@ class Commande extends CommonOrder $this->billed = 1; } - // Call trigger - $result = $this->call_trigger('ORDER_CLASSIFY_UNBILLED', $user); - if ($result < 0) { - $error++; + if (!$notrigger && empty($error)) { + // Call trigger + $result = $this->call_trigger('ORDER_CLASSIFY_UNBILLED', $user); + if ($result < 0) { + $error++; + } + // End call triggers } - // End call triggers if (!$error) { $this->billed = 0; @@ -3307,7 +3310,7 @@ class Commande extends CommonOrder $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").","; $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").""; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); @@ -3683,7 +3686,7 @@ class Commande extends CommonOrder $label .= ' '.$this->getLibStatut(5); } $label .= '
'.$langs->trans('Ref').': '.$this->ref; - $label .= '
'.$langs->trans('RefCustomer').': '.($this->ref_customer ? $this->ref_customer : $this->ref_client); + $label .= '
'.$langs->trans('RefCustomer').': '.(empty($this->ref_customer) ? (empty($this->ref_client) ? '' : $this-ref_client) : $this->ref_customer); if (!empty($this->total_ht)) { $label .= '
'.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); } @@ -3760,7 +3763,7 @@ class Commande extends CommonOrder $sql .= ' date_cloture as datecloture,'; $sql .= ' fk_user_author, fk_user_valid, fk_user_cloture'; $sql .= ' FROM '.MAIN_DB_PREFIX.'commande as c'; - $sql .= ' WHERE c.rowid = '.$id; + $sql .= ' WHERE c.rowid = '.((int) $id); $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) { diff --git a/htdocs/compta/accounting-files.php b/htdocs/compta/accounting-files.php index 337baeba65c..600c27b609e 100644 --- a/htdocs/compta/accounting-files.php +++ b/htdocs/compta/accounting-files.php @@ -3,6 +3,7 @@ * Copyright (C) 2004-2019 Laurent Destailleur * Copyright (C) 2017 Pierre-Henry Favre * Copyright (C) 2020 Maxime DEMAREST + * Copyright (C) 2021 Gauthier VERDOL * * 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 @@ -693,7 +694,7 @@ if (!empty($date_start) && !empty($date_stop)) { } elseif ($data['item'] == 'SalaryPayment') { $salary_payment->id = $data['id']; $salary_payment->ref = $data['ref']; - print $salary_payment->getNomUrl(1, '', 0, '', 0); + print $salary_payment->getNomUrl(1); } elseif ($data['item'] == 'Donation') { $don->id = $data['id']; $don->ref = $data['ref']; diff --git a/htdocs/compta/bank/account_statement_document.php b/htdocs/compta/bank/account_statement_document.php index 929a7a483bb..ea4911e7050 100644 --- a/htdocs/compta/bank/account_statement_document.php +++ b/htdocs/compta/bank/account_statement_document.php @@ -186,14 +186,14 @@ if ($id > 0 || !empty($ref)) { $permission = $user->rights->banque->modifier; $permtoedit = $user->rights->banque->modifier; $param = '&id='.$object->id.'&num='.urlencode($numref); - $moreparam = '&num='.urlencode($numref); ; + $moreparam = '&num='.urlencode($numref); $relativepathwithnofile = $id."/statement/".dol_sanitizeFileName($numref)."/"; include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { dol_print_error($db); } } else { - Header('Location: index.php'); + header('Location: index.php'); exit; } diff --git a/htdocs/compta/bank/bankentries_list.php b/htdocs/compta/bank/bankentries_list.php index 390972912c1..217b735a299 100644 --- a/htdocs/compta/bank/bankentries_list.php +++ b/htdocs/compta/bank/bankentries_list.php @@ -182,7 +182,8 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); */ if (GETPOST('cancel', 'alpha')) { - $action = 'list'; $massaction = ''; + $action = 'list'; + $massaction = ''; } if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; @@ -1115,7 +1116,7 @@ if ($resql) { print_liste_field_titre($arrayfields['b.num_chq']['label'], $_SERVER['PHP_SELF'], 'b.num_chq', '', $param, '', $sortfield, $sortorder, "center "); } if (!empty($arrayfields['bu.label']['checked'])) { - print_liste_field_titre($arrayfields['bu.label']['label'], $_SERVER['PHP_SELF'], 'bu.label', '', $param, '', $sortfield, $sortorder); + print_liste_field_titre($arrayfields['bu.label']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); } if (!empty($arrayfields['ba.ref']['checked'])) { print_liste_field_titre($arrayfields['ba.ref']['label'], $_SERVER['PHP_SELF'], 'ba.ref', '', $param, '', $sortfield, $sortorder); @@ -1188,8 +1189,8 @@ if ($resql) { // If sort is desc,desc,desc then total of previous date + amount is the balancebefore of the previous line before the line to show if ($sortfield == 'b.datev,b.dateo,b.rowid' && $sortorder == 'desc,desc,desc') { $balancebefore = $objforbalance->previoustotal + ($sign * $objp->amount); - } // If sort is asc,asc,asc then total of previous date is balance of line before the next line to show - else { + } else { + // If sort is asc,asc,asc then total of previous date is balance of line before the next line to show $balance = $objforbalance->previoustotal; } } @@ -1419,6 +1420,7 @@ if ($resql) { } elseif ($links[$key]['type'] == 'member') { } elseif ($links[$key]['type'] == 'sc') { } elseif ($links[$key]['type'] == 'vat') { + } elseif ($links[$key]['type'] == 'salary') { } else { // Show link with label $links[$key]['label'] if (!empty($objp->label) && !empty($links[$key]['label'])) { diff --git a/htdocs/compta/bank/budget.php b/htdocs/compta/bank/budget.php index dda8f13437d..d3ffbb37916 100644 --- a/htdocs/compta/bank/budget.php +++ b/htdocs/compta/bank/budget.php @@ -72,7 +72,9 @@ $sql .= " ORDER BY c.label"; $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); - $i = 0; $total = 0; $totalnb = 0; + $i = 0; + $total = 0; + $totalnb = 0; while ($i < $num) { $objp = $db->fetch_object($result); diff --git a/htdocs/compta/bank/categ.php b/htdocs/compta/bank/categ.php index 48976f8ba25..fb9fead3089 100644 --- a/htdocs/compta/bank/categ.php +++ b/htdocs/compta/bank/categ.php @@ -126,7 +126,8 @@ $sql .= " ORDER BY rowid"; $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); - $i = 0; $total = 0; + $i = 0; + $total = 0; while ($i < $num) { $objp = $db->fetch_object($result); diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index 7cabbc98500..16e26b9bc94 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -2271,7 +2271,7 @@ class AccountLine extends CommonObject $sql = 'SELECT b.rowid, b.datec, b.tms as datem,'; $sql .= ' b.fk_user_author, b.fk_user_rappro'; $sql .= ' FROM '.MAIN_DB_PREFIX.'bank as b'; - $sql .= ' WHERE b.rowid = '.$id; + $sql .= ' WHERE b.rowid = '.((int) $id); $result = $this->db->query($sql); if ($result) { @@ -2319,7 +2319,7 @@ class AccountLine extends CommonObject $label = img_picto('', $this->picto).' '.$langs->trans("Transaction").':
'; $label .= ''.$langs->trans("Ref").': '.$this->ref; - $linkstart = ''; + $linkstart = ''; $linkend = ''; $result .= $linkstart; diff --git a/htdocs/compta/bank/class/bankcateg.class.php b/htdocs/compta/bank/class/bankcateg.class.php index be023fe630c..ccf5828d40a 100644 --- a/htdocs/compta/bank/class/bankcateg.class.php +++ b/htdocs/compta/bank/class/bankcateg.class.php @@ -126,7 +126,7 @@ class BankCateg // extends CommonObject $sql .= " t.rowid,"; $sql .= " t.label"; $sql .= " FROM ".MAIN_DB_PREFIX."bank_categ as t"; - $sql .= " WHERE t.rowid = ".$id; + $sql .= " WHERE t.rowid = ".((int) $id); $sql .= " AND t.entity = ".$conf->entity; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); @@ -170,7 +170,7 @@ class BankCateg // extends CommonObject // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."bank_categ SET"; $sql .= " label=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").""; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $sql .= " AND entity = ".$conf->entity; $this->db->begin(); @@ -237,7 +237,7 @@ class BankCateg // extends CommonObject // Delete bank categ if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_categ"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $resql = $this->db->query($sql); if (!$resql) { diff --git a/htdocs/compta/bank/class/paymentvarious.class.php b/htdocs/compta/bank/class/paymentvarious.class.php index 7919f3c60df..dccdcd5cd24 100644 --- a/htdocs/compta/bank/class/paymentvarious.class.php +++ b/htdocs/compta/bank/class/paymentvarious.class.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2017-2021 Alexandre Spangaro * Copyright (C) 2018-2020 Frédéric France * * This program is free software; you can redistribute it and/or modify @@ -70,6 +70,8 @@ class PaymentVarious extends CommonObject public $amount; public $type_payment; public $num_payment; + public $chqemetteur; + public $chqbank; public $category_transaction; /** @@ -212,7 +214,7 @@ class PaymentVarious extends CommonObject $sql .= " fk_bank=".($this->fk_bank > 0 ? $this->fk_bank : "null").","; $sql .= " fk_user_author=".(int) $this->fk_user_author.","; $sql .= " fk_user_modif=".(int) $this->fk_user_modif; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); @@ -272,7 +274,7 @@ class PaymentVarious extends CommonObject $sql .= " b.rappro"; $sql .= " FROM ".MAIN_DB_PREFIX."payment_various as v"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON v.fk_bank = b.rowid"; - $sql .= " WHERE v.rowid = ".$id; + $sql .= " WHERE v.rowid = ".((int) $id); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); @@ -332,7 +334,7 @@ class PaymentVarious extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_various"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); @@ -504,8 +506,8 @@ class PaymentVarious extends CommonObject $this->num_payment, ($this->category_transaction > 0 ? $this->category_transaction : 0), $user, - '', - '', + $this->chqemetteur, + $this->chqbank, '', $this->datev ); @@ -740,7 +742,7 @@ class PaymentVarious extends CommonObject { $sql = 'SELECT v.rowid, v.datec, v.fk_user_author'; $sql .= ' FROM '.MAIN_DB_PREFIX.'payment_various as v'; - $sql .= ' WHERE v.rowid = '.$id; + $sql .= ' WHERE v.rowid = '.((int) $id); dol_syslog(get_class($this).'::info', LOG_DEBUG); $result = $this->db->query($sql); diff --git a/htdocs/compta/bank/graph.php b/htdocs/compta/bank/graph.php index c2dd1c316a6..6dd588f51e1 100644 --- a/htdocs/compta/bank/graph.php +++ b/htdocs/compta/bank/graph.php @@ -795,13 +795,17 @@ print '
'; // Graphs if ($mode == 'standard') { - $prevyear = $year; $nextyear = $year; - $prevmonth = $month - 1; $nextmonth = $month + 1; + $prevyear = $year; + $nextyear = $year; + $prevmonth = $month - 1; + $nextmonth = $month + 1; if ($prevmonth < 1) { - $prevmonth = 12; $prevyear--; + $prevmonth = 12; + $prevyear--; } if ($nextmonth > 12) { - $nextmonth = 1; $nextyear++; + $nextmonth = 1; + $nextyear++; } // For month @@ -818,7 +822,8 @@ if ($mode == 'standard') { print '
'; // For year - $prevyear = $year - 1; $nextyear = $year + 1; + $prevyear = $year - 1; + $nextyear = $year + 1; $link = "".img_previous('', 'class="valignbottom"')." ".$langs->trans("Year")." ".img_next('', 'class="valignbottom"').""; print '
'.$link.'
'; diff --git a/htdocs/compta/bank/line.php b/htdocs/compta/bank/line.php index 1f22b67ac7c..419a0a41cdf 100644 --- a/htdocs/compta/bank/line.php +++ b/htdocs/compta/bank/line.php @@ -272,7 +272,8 @@ $sql .= " WHERE rowid=".$rowid; $sql .= " ORDER BY dateo ASC"; $result = $db->query($sql); if ($result) { - $i = 0; $total = 0; + $i = 0; + $total = 0; if ($db->num_rows($result)) { $objp = $db->fetch_object($result); @@ -314,10 +315,11 @@ if ($result) { $i++; // Bank account - print ''.$langs->trans("Account").''; + print ''.$langs->trans("Account").''; print ''; if (!$objp->rappro && !$bankline->getVentilExportCompta()) { - $form->select_comptes($acct->id, 'accountid', 0, '', 0); + print img_picto('', 'bank_account', 'class="paddingright"'); + print $form->select_comptes($acct->id, 'accountid', 0, '', 0, '', 0, '', 1); } else { print $acct->getNomUrl(1, 'transactions', 'reflabel'); } @@ -366,6 +368,11 @@ if ($result) { print img_object($langs->trans('VATDeclaration'), 'bill').' '; print $langs->trans("VATDeclaration").($links[$key]['label'] ? ' '.$links[$key]['label'] : ''); print ''; + } elseif ($links[$key]['type'] == 'salary') { + print ''; + print img_object($langs->trans('Salary'), 'bill').' '; + print $langs->trans("Salary").($links[$key]['label'] ? ' - '.$links[$key]['label'] : ''); + print ''; } elseif ($links[$key]['type'] == 'payment_sc') { print ''; print img_object($langs->trans('Payment'), 'payment').' '; @@ -377,7 +384,7 @@ if ($result) { print $langs->trans("VATPayment"); print ''; } elseif ($links[$key]['type'] == 'payment_salary') { - print ''; + print ''; print img_object($langs->trans('PaymentSalary'), 'payment').' '; print $langs->trans("SalaryPayment"); print ''; @@ -560,7 +567,7 @@ if ($result) { // Bank line print ''.$form->editfieldkey('RubriquesTransactions', 'custcats', '', $object, 0).''; $cate_arbo = $form->select_all_categories(Categorie::TYPE_BANK_LINE, null, 'parent', null, null, 1); - print $form->multiselectarray('custcats', $cate_arbo, $arrayselected, null, null, null, null, "90%"); + print img_picto('', 'category', 'class="paddingright"').$form->multiselectarray('custcats', $cate_arbo, $arrayselected, null, null, null, null, "90%"); print ""; } diff --git a/htdocs/compta/bank/list.php b/htdocs/compta/bank/list.php index 6c2e595e3d1..9375cf8aaa1 100644 --- a/htdocs/compta/bank/list.php +++ b/htdocs/compta/bank/list.php @@ -62,6 +62,7 @@ if (!empty($conf->categorie->enabled)) { $search_category_list = GETPOST("search_category_".Categorie::TYPE_ACCOUNT."_list", "array"); } +$socid = 0; // Security check if ($user->socid) { $socid = $user->socid; @@ -134,7 +135,8 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); */ if (GETPOST('cancel', 'alpha')) { - $action = 'list'; $massaction = ''; + $action = 'list'; + $massaction = ''; } if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; @@ -490,7 +492,10 @@ print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $ print "\n"; -$totalarray = array(); $found = 0; $i = 0; $lastcurrencycode = ''; +$totalarray = array(); +$found = 0; +$i = 0; +$lastcurrencycode = ''; foreach ($accounts as $key => $type) { if ($i >= $limit) { diff --git a/htdocs/compta/bank/various_payment/card.php b/htdocs/compta/bank/various_payment/card.php index 19b56169f8d..d19ccbed908 100644 --- a/htdocs/compta/bank/various_payment/card.php +++ b/htdocs/compta/bank/various_payment/card.php @@ -49,7 +49,7 @@ $accountid = GETPOST("accountid") > 0 ? GETPOST("accountid", "int") : 0; $label = GETPOST("label", "alpha"); $sens = GETPOST("sens", "int"); $amount = price2num(GETPOST("amount", "alpha")); -$paymenttype = GETPOST("paymenttype", "int"); +$paymenttype = GETPOST("paymenttype", "aZ09"); $accountancy_code = GETPOST("accountancy_code", "alpha"); $projectid = (GETPOST('projectid', 'int') ? GETPOST('projectid', 'int') : GETPOST('fk_project', 'int')); if (!empty($conf->accounting->enabled) && !empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { @@ -116,8 +116,10 @@ if (empty($reshook)) { $object->amount = price2num(GETPOST("amount", 'alpha')); $object->label = GETPOST("label", 'restricthtml'); $object->note = GETPOST("note", 'restricthtml'); - $object->type_payment = GETPOST("paymenttype", 'int') > 0 ? GETPOST("paymenttype", "int") : 0; + $object->type_payment = dol_getIdFromCode($db, GETPOST('paymenttype'), 'c_paiement', 'code', 'id', 1); $object->num_payment = GETPOST("num_payment", 'alpha'); + $object->chqemetteur = GETPOST("chqemetteur", 'alpha'); + $object->chqbank = GETPOST("chqbank", 'alpha'); $object->fk_user_author = $user->id; $object->category_transaction = GETPOST("category_transaction", 'alpha'); @@ -338,6 +340,42 @@ foreach ($bankcateg->fetchAll() as $bankcategory) { /* */ /* ************************************************************************** */ if ($action == 'create') { + // Update fields properties in realtime + if (!empty($conf->use_javascript_ajax)) { + print "\n".''."\n"; + } + print ''; print ''; print ''; @@ -382,18 +420,29 @@ if ($action == 'create') { } // Type payment - print ''; - print $form->editfieldkey('PaymentMode', 'selectpaymenttype', '', $object, 0, 'string', '', 1).''; - $form->select_types_paiements($paymenttype, "paymenttype"); - print ''; + print ''.$langs->trans('PaymentMode').''; + $form->select_types_paiements($paymenttype, 'paymenttype', '', 2); + print "\n"; + print ''; // Number if (!empty($conf->banque->enabled)) { - // Number print ''; print ''."\n"; + + // Check transmitter + print ''; + print ''; + + // Bank name + print ''; + print ''; } // Accountancy account diff --git a/htdocs/compta/cashcontrol/cashcontrol_card.php b/htdocs/compta/cashcontrol/cashcontrol_card.php index d4bec1929ee..da018dd1f06 100644 --- a/htdocs/compta/cashcontrol/cashcontrol_card.php +++ b/htdocs/compta/cashcontrol/cashcontrol_card.php @@ -413,9 +413,11 @@ if ($action == "create" || $action == "start" || $action == 'close') { for ($i = 1; $i <= $numterminals; $i++) { $array[$i] = $i; } - $selectedposnumber = 0; $showempty = 1; + $selectedposnumber = 0; + $showempty = 1; if ($conf->global->TAKEPOS_NUM_TERMINALS == '1') { - $selectedposnumber = 1; $showempty = 0; + $selectedposnumber = 1; + $showempty = 0; } print $form->selectarray('posnumber', $array, GETPOSTISSET('posnumber') ?GETPOST('posnumber', 'int') : $selectedposnumber, $showempty); //print ''; diff --git a/htdocs/compta/cashcontrol/cashcontrol_list.php b/htdocs/compta/cashcontrol/cashcontrol_list.php index a301caff80f..6c4141e4b6a 100644 --- a/htdocs/compta/cashcontrol/cashcontrol_list.php +++ b/htdocs/compta/cashcontrol/cashcontrol_list.php @@ -140,7 +140,8 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); */ if (GETPOST('cancel', 'alpha')) { - $action = 'list'; $massaction = ''; + $action = 'list'; + $massaction = ''; } if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; diff --git a/htdocs/compta/cashcontrol/class/cashcontrol.class.php b/htdocs/compta/cashcontrol/class/cashcontrol.class.php index fd6d7d9fa25..1b9860c976a 100644 --- a/htdocs/compta/cashcontrol/class/cashcontrol.class.php +++ b/htdocs/compta/cashcontrol/class/cashcontrol.class.php @@ -244,7 +244,7 @@ class CashControl extends CommonObject $sql .= " SET status = ".self::STATUS_VALIDATED.","; $sql .= " date_valid='".$this->db->idate($now)."',"; $sql .= " fk_user_valid = ".$user->id; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); diff --git a/htdocs/compta/cashcontrol/report.php b/htdocs/compta/cashcontrol/report.php index 8f85f5779a0..f6c58aa858c 100644 --- a/htdocs/compta/cashcontrol/report.php +++ b/htdocs/compta/cashcontrol/report.php @@ -233,10 +233,9 @@ if ($resql) { } else { if ($conf->global->$var1 == $bankaccount->id) { $cash += $objp->amount; - } - //elseif ($conf->global->$var2 == $bankaccount->id) $bank+=$objp->amount; - //elseif ($conf->global->$var3 == $bankaccount->id) $cheque+=$objp->amount; - else { + // } elseif ($conf->global->$var2 == $bankaccount->id) $bank+=$objp->amount; + //elseif ($conf->global->$var3 == $bankaccount->id) $cheque+=$objp->amount; + } else { $other += $objp->amount; } } diff --git a/htdocs/compta/charges/index.php b/htdocs/compta/charges/index.php index 4963a24d43d..2661678d411 100644 --- a/htdocs/compta/charges/index.php +++ b/htdocs/compta/charges/index.php @@ -6,6 +6,7 @@ * Copyright (C) 2011-2014 Juanjo Menent * Copyright (C) 2015 Jean-François Ferry * Copyright (C) 2019 Nicolas ZABOURI + * Copyright (C) 2021 Gauthier VERDOL * * 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 @@ -31,7 +32,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/paymentsocialcontribution.class.php'; -require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php'; +require_once DOL_DOCUMENT_ROOT.'/salaries/class/salary.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; @@ -84,7 +85,7 @@ if (!$sortorder) { $tva_static = new Tva($db); $socialcontrib = new ChargeSociales($db); $payment_sc_static = new PaymentSocialContribution($db); -$sal_static = new PaymentSalary($db); +$sal_static = new Salary($db); $accountstatic = new Account($db); llxHeader('', $langs->trans("SpecialExpensesArea")); @@ -414,6 +415,8 @@ while ($j < $numlt) { $num = $db->num_rows($result); $i = 0; $total = 0; + + print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table print ''; print ''; print_liste_field_titre("PeriodEndDate", $_SERVER["PHP_SELF"], "pv.datev", "", $param, 'width="120"', $sortfield, $sortorder); @@ -455,6 +458,8 @@ while ($j < $numlt) { print ""; print "
"; + print '
'; + $db->free($result); } else { dol_print_error($db); @@ -463,115 +468,6 @@ while ($j < $numlt) { $j++; } - -// Payment Salary -/* -if (!empty($conf->salaries->enabled) && !empty($user->rights->salaries->read)) -{ - $sal = new PaymentSalary($db); - - print "
"; - - print load_fiche_titre($langs->trans("SalariesPayments").($year ? ' ('.$langs->trans("Year").' '.$year.')' : ''), '', ''); - - $sql = "SELECT s.rowid, s.amount, s.label, s.datep as datep, s.datev as datev, s.datesp, s.dateep, s.salary, s.fk_bank, u.salary as current_salary,"; - $sql .= " pct.code as payment_code,"; - $sql .= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel"; - $sql .= " FROM ".MAIN_DB_PREFIX."payment_salary as s"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON s.fk_typepayment = pct.id"; - $sql .= " , ".MAIN_DB_PREFIX."user as u"; - $sql .= " WHERE s.entity IN (".getEntity('user').")"; - $sql .= " AND u.rowid = s.fk_user"; - if ($year > 0) - { - $sql .= " AND (s.datesp between '".$db->idate(dol_get_first_day($year, 1, false))."' AND '".$db->idate(dol_get_last_day($year, 12, false))."'"; - $sql .= " OR s.dateep between '".$db->idate(dol_get_first_day($year, 1, false))."' AND '".$db->idate(dol_get_last_day($year, 12, false))."')"; - } - if (preg_match('/^s\./', $sortfield)) $sql .= $db->order($sortfield, $sortorder); - - $result = $db->query($sql); - if ($result) - { - $num = $db->num_rows($result); - $i = 0; - $total = 0; - print ''; - print ''; - print_liste_field_titre("PeriodEndDate", $_SERVER["PHP_SELF"], "s.dateep", "", $param, 'width="140px"', $sortfield, $sortorder); - print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "s.label", "", $param, '', $sortfield, $sortorder); - print_liste_field_titre("RefPayment", $_SERVER["PHP_SELF"], "s.rowid", "", $param, '', $sortfield, $sortorder); - print_liste_field_titre("DatePayment", $_SERVER["PHP_SELF"], "s.datep", "", $param, 'align="center"', $sortfield, $sortorder); - print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "pct.code", "", $param, '', $sortfield, $sortorder); - if (!empty($conf->banque->enabled)) print_liste_field_titre("Account", $_SERVER["PHP_SELF"], "ba.label", "", $param, "", $sortfield, $sortorder); - print_liste_field_titre("PayedByThisPayment", $_SERVER["PHP_SELF"], "s.amount", "", $param, 'class="right"', $sortfield, $sortorder); - print "\n"; - - while ($i < $num) - { - $obj = $db->fetch_object($result); - - $total = $total + $obj->amount; - - - print ''; - - print ''."\n"; - - print "\n"; - - // Ref payment - $sal_static->id = $obj->rowid; - $sal_static->ref = $obj->rowid; - print '\n"; - - // Date - print '\n"; - - // Type payment - print ''; - - // Account - if (!empty($conf->banque->enabled)) - { - print ''; - } - - // Paid - print '"; - print "\n"; - - $i++; - } - print ''; - print '"; - print ""; - - print "
'.dol_print_date($db->jdate($obj->dateep), 'day').'".$obj->label."'.$sal_static->getNomUrl(1)."'.dol_print_date($db->jdate($obj->datep), 'day')."'; - if ($obj->payment_code) print $langs->trans("PaymentTypeShort".$obj->payment_code).' '; - print $obj->num_payment.''; - if ($obj->fk_bank > 0) - { - //$accountstatic->fetch($obj->fk_bank); - $accountstatic->id = $obj->bid; - $accountstatic->ref = $obj->bref; - $accountstatic->number = $obj->bnumber; - $accountstatic->accountancy_number = $obj->account_number; - $accountstatic->accountancy_journal = $obj->accountancy_journal; - $accountstatic->label = $obj->blabel; - print $accountstatic->getNomUrl(1); - } else print ' '; - print ''.price($obj->amount)."
'.$langs->trans("Total").''.price($total)."
"; - $db->free($result); - - print "
"; - } else { - dol_print_error($db); - } -} -*/ - print ''; $parameters = array('user' => $user); diff --git a/htdocs/compta/deplacement/card.php b/htdocs/compta/deplacement/card.php index 7ca8a2d591e..1d294df8cff 100644 --- a/htdocs/compta/deplacement/card.php +++ b/htdocs/compta/deplacement/card.php @@ -134,8 +134,8 @@ if ($action == 'validate' && $user->rights->deplacement->creer) { header("Location: index.php"); exit; } -} // Update record -elseif ($action == 'update' && $user->rights->deplacement->creer) { +} elseif ($action == 'update' && $user->rights->deplacement->creer) { + // Update record if (!GETPOST('cancel', 'alpha')) { $result = $object->fetch($id); @@ -159,15 +159,15 @@ elseif ($action == 'update' && $user->rights->deplacement->creer) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); exit; } -} // Set into a project -elseif ($action == 'classin' && $user->rights->deplacement->creer) { +} elseif ($action == 'classin' && $user->rights->deplacement->creer) { + // Set into a project $object->fetch($id); $result = $object->setProject(GETPOST('projectid', 'int')); if ($result < 0) { dol_print_error($db, $object->error); } -} // Set fields -elseif ($action == 'setdated' && $user->rights->deplacement->creer) { +} elseif ($action == 'setdated' && $user->rights->deplacement->creer) { + // Set fields $dated = dol_mktime(GETPOST('datedhour', 'int'), GETPOST('datedmin', 'int'), GETPOST('datedsec', 'int'), GETPOST('datedmonth', 'int'), GETPOST('datedday', 'int'), GETPOST('datedyear', 'int')); $object->fetch($id); $result = $object->setValueFrom('dated', $dated, '', '', 'date', '', $user, 'DEPLACEMENT_MODIFY'); diff --git a/htdocs/compta/deplacement/class/deplacement.class.php b/htdocs/compta/deplacement/class/deplacement.class.php index 1c7a4e75552..c34d89bfa2f 100644 --- a/htdocs/compta/deplacement/class/deplacement.class.php +++ b/htdocs/compta/deplacement/class/deplacement.class.php @@ -278,7 +278,7 @@ class Deplacement extends CommonObject if ($ref) { $sql .= " AND ref ='".$this->db->escape($ref)."'"; } else { - $sql .= " AND rowid = ".$id; + $sql .= " AND rowid = ".((int) $id); } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); @@ -317,7 +317,7 @@ class Deplacement extends CommonObject { $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."deplacement WHERE rowid = ".$id; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."deplacement WHERE rowid = ".((int) $id); dol_syslog(get_class($this)."::delete", LOG_DEBUG); $result = $this->db->query($sql); @@ -471,7 +471,7 @@ class Deplacement extends CommonObject $sql = 'SELECT c.rowid, c.datec, c.fk_user_author, c.fk_user_modif,'; $sql .= ' c.tms'; $sql .= ' FROM '.MAIN_DB_PREFIX.'deplacement as c'; - $sql .= ' WHERE c.rowid = '.$id; + $sql .= ' WHERE c.rowid = '.((int) $id); dol_syslog(get_class($this).'::info', LOG_DEBUG); $result = $this->db->query($sql); diff --git a/htdocs/compta/deplacement/stats/index.php b/htdocs/compta/deplacement/stats/index.php index 4786e2ea1b5..892b2b86dff 100644 --- a/htdocs/compta/deplacement/stats/index.php +++ b/htdocs/compta/deplacement/stats/index.php @@ -110,7 +110,8 @@ $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); if (!$mesg) { $px1->SetData($data); - $i = $startyear; $legend = array(); + $i = $startyear; + $legend = array(); while ($i <= $endyear) { $legend[] = $i; $i++; @@ -140,7 +141,8 @@ $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); if (!$mesg) { $px2->SetData($data); - $i = $startyear; $legend = array(); + $i = $startyear; + $legend = array(); while ($i <= $endyear) { $legend[] = $i; $i++; @@ -184,7 +186,8 @@ $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); if (!$mesg) { $px3->SetData($data); - $i = $startyear; $legend = array(); + $i = $startyear; + $legend = array(); while ($i <= $endyear) { $legend[] = $i; $i++; diff --git a/htdocs/compta/facture/card-rec.php b/htdocs/compta/facture/card-rec.php index 988dea7e45e..1978a6115b5 100644 --- a/htdocs/compta/facture/card-rec.php +++ b/htdocs/compta/facture/card-rec.php @@ -133,7 +133,8 @@ $error = 0; */ if (GETPOST('cancel', 'alpha')) { - $action = 'list'; $massaction = ''; + $action = 'list'; + $massaction = ''; } if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; @@ -279,14 +280,14 @@ if (empty($reshook)) { // Set condition if ($action == 'setconditions' && $user->rights->facture->creer) { $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); - } // Set mode - elseif ($action == 'setmode' && $user->rights->facture->creer) { + } elseif ($action == 'setmode' && $user->rights->facture->creer) { + // Set mode $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); - } // Set project - elseif ($action == 'classin' && $user->rights->facture->creer) { + } elseif ($action == 'classin' && $user->rights->facture->creer) { + // Set project $object->setProject(GETPOST('projectid', 'int')); - } // Set bank account - elseif ($action == 'setref' && $user->rights->facture->creer) { + } elseif ($action == 'setref' && $user->rights->facture->creer) { + // Set bank account //var_dump(GETPOST('ref', 'alpha'));exit; $result = $object->setValueFrom('titre', $ref, '', null, 'text', '', $user, 'BILLREC_MODIFY'); if ($result > 0) { @@ -302,32 +303,32 @@ if (empty($reshook)) { setEventMessages($object->error, $object->errors, 'errors'); } } - } // Set bank account - elseif ($action == 'setbankaccount' && $user->rights->facture->creer) { + } elseif ($action == 'setbankaccount' && $user->rights->facture->creer) { + // Set bank account $result = $object->setBankAccount(GETPOST('fk_account', 'int')); - } // Set frequency and unit frequency - elseif ($action == 'setfrequency' && $user->rights->facture->creer) { + } elseif ($action == 'setfrequency' && $user->rights->facture->creer) { + // Set frequency and unit frequency $object->setFrequencyAndUnit(GETPOST('frequency', 'int'), GETPOST('unit_frequency', 'alpha')); - } // Set next date of execution - elseif ($action == 'setdate_when' && $user->rights->facture->creer) { + } elseif ($action == 'setdate_when' && $user->rights->facture->creer) { + // Set next date of execution $date = dol_mktime(GETPOST('date_whenhour'), GETPOST('date_whenmin'), 0, GETPOST('date_whenmonth'), GETPOST('date_whenday'), GETPOST('date_whenyear')); if (!empty($date)) { $object->setNextDate($date); } - } // Set max period - elseif ($action == 'setnb_gen_max' && $user->rights->facture->creer) { + } elseif ($action == 'setnb_gen_max' && $user->rights->facture->creer) { + // Set max period $object->setMaxPeriod(GETPOST('nb_gen_max', 'int')); - } // Set auto validate - elseif ($action == 'setauto_validate' && $user->rights->facture->creer) { + } elseif ($action == 'setauto_validate' && $user->rights->facture->creer) { + // Set auto validate $object->setAutoValidate(GETPOST('auto_validate', 'int')); - } // Set generate pdf - elseif ($action == 'setgenerate_pdf' && $user->rights->facture->creer) { + } elseif ($action == 'setgenerate_pdf' && $user->rights->facture->creer) { + // Set generate pdf $object->setGeneratepdf(GETPOST('generate_pdf', 'int')); - } // Set model pdf - elseif ($action == 'setmodelpdf' && $user->rights->facture->creer) { + } elseif ($action == 'setmodelpdf' && $user->rights->facture->creer) { + // Set model pdf $object->setModelpdf(GETPOST('modelpdf', 'alpha')); - } // Set status disabled - elseif ($action == 'disable' && $user->rights->facture->creer) { + } elseif ($action == 'disable' && $user->rights->facture->creer) { + // Set status disabled $db->begin(); $object->fetch($id); @@ -343,8 +344,8 @@ if (empty($reshook)) { $db->rollback(); setEventMessages($object->error, $object->errors, 'errors'); } - } // Set status enabled - elseif ($action == 'enable' && $user->rights->facture->creer) { + } elseif ($action == 'enable' && $user->rights->facture->creer) { + // Set status enabled $db->begin(); $object->fetch($id); @@ -360,11 +361,11 @@ if (empty($reshook)) { $db->rollback(); setEventMessages($object->error, $object->errors, 'errors'); } - } // Multicurrency Code - elseif ($action == 'setmulticurrencycode' && $usercancreate) { + } elseif ($action == 'setmulticurrencycode' && $usercancreate) { + // Multicurrency Code $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha')); - } // Multicurrency rate - elseif ($action == 'setmulticurrencyrate' && $usercancreate) { + } elseif ($action == 'setmulticurrencyrate' && $usercancreate) { + // Multicurrency rate $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')), GETPOST('calculation_mode', 'int')); } @@ -420,8 +421,8 @@ if (empty($reshook)) { // Set if we used free entry or predefined product $predef = ''; $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : ''); - $price_ht = price2num(GETPOST('price_ht'), 'MU'); - $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU'); + $price_ht = price2num(GETPOST('price_ht'), 'MU', 2); + $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2); $prod_entry_mode = GETPOST('prod_entry_mode', 'alpha'); if ($prod_entry_mode == 'free') { $idprod = 0; @@ -525,9 +526,9 @@ if (empty($reshook)) { if (!empty($price_ht)) { $pu_ht = price2num($price_ht, 'MU'); $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); - } // On reevalue prix selon taux tva car taux tva transaction peut etre different - // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). - elseif ($tmpvat != $tmpprodvat) { + } elseif ($tmpvat != $tmpprodvat) { + // On reevalue prix selon taux tva car taux tva transaction peut etre different + // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). if ($price_base_type != 'HT') { $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU'); } else { @@ -718,10 +719,10 @@ if (empty($reshook)) { //$date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); //$date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml') ? GETPOST('product_desc', 'restricthtml') : GETPOST('desc', 'restricthtml')); - $pu_ht = GETPOST('price_ht'); + $pu_ht = price2num(GETPOST('price_ht'), '', 2); $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); $qty = GETPOST('qty'); - $pu_ht_devise = GETPOST('multicurrency_subprice'); + $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2); // Define info_bits $info_bits = 0; diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index ba4e4e8e8d1..8c291a0839b 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -233,8 +233,8 @@ if (empty($reshook)) { $action = ''; } } - } // Delete line - elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) { + } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) { + // Delete line $object->fetch($id); $object->fetch_thirdparty(); @@ -386,7 +386,7 @@ if (empty($reshook)) { } elseif ($action == 'setinvoicedate' && $usercancreate) { $object->fetch($id); $old_date_lim_reglement = $object->date_lim_reglement; - $date = dol_mktime(12, 0, 0, $_POST['invoicedatemonth'], $_POST['invoicedateday'], $_POST['invoicedateyear']); + $date = dol_mktime(12, 0, 0, GETPOST('invoicedatemonth', 'int'), GETPOST('invoicedateday', 'int'), GETPOST('invoicedateyear', 'int')); if (empty($date)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id.'&action=editinvoicedate'); @@ -563,8 +563,8 @@ if (empty($reshook)) { } elseif ($action == 'setref_client' && $usercancreate) { $object->fetch($id); $object->set_ref_client(GETPOST('ref_client')); - } // Classify to validated - elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) { + } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) { + // Classify to validated $idwarehouse = GETPOST('idwarehouse', 'int'); $object->fetch($id); @@ -1955,8 +1955,8 @@ if (empty($reshook)) { // Set if we used free entry or predefined product $predef = ''; $product_desc =(GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : ''); - $price_ht = price2num(GETPOST('price_ht')); - $price_ht_devise = price2num(GETPOST('multicurrency_price_ht')); + $price_ht = price2num(GETPOST('price_ht'), 'MU', 2); + $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2); $prod_entry_mode = GETPOST('prod_entry_mode', 'alpha'); if ($prod_entry_mode == 'free') { $idprod = 0; @@ -2299,10 +2299,10 @@ if (empty($reshook)) { $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml') ? GETPOST('product_desc', 'restricthtml') : GETPOST('desc', 'restricthtml')); - $pu_ht = GETPOST('price_ht'); + $pu_ht = price2num(GETPOST('price_ht'), '', 2); $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); $qty = GETPOST('qty'); - $pu_ht_devise = GETPOST('multicurrency_subprice'); + $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2); // Define info_bits $info_bits = 0; @@ -2770,15 +2770,15 @@ if (empty($reshook)) { setEventMessages($object->error, $object->errors, 'errors'); } } - } // bascule du statut d'un contact - elseif ($action == 'swapstatut') { + } elseif ($action == 'swapstatut') { + // bascule du statut d'un contact if ($object->fetch($id)) { $result = $object->swapContactStatus(GETPOST('ligne')); } else { dol_print_error($db); } - } // Efface un contact - elseif ($action == 'deletecontact') { + } elseif ($action == 'deletecontact') { + // Efface un contact $object->fetch($id); $result = $object->delete_contact($lineid); diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index f9f6eeb28e4..7e2fc70c10e 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -79,9 +79,14 @@ class FactureRec extends CommonInvoice */ public $title; + public $socid; public $number; public $date; public $remise; + public $db_table; + public $propalid; + public $remise_absolue; + public $remise_percent; /** * @deprecated @@ -94,14 +99,14 @@ class FactureRec extends CommonInvoice * @see $total_tva */ public $tva; - public $db_table; - public $propalid; public $date_last_gen; public $date_when; public $nb_gen_done; public $nb_gen_max; + public $user_author; + /** * @var int Frequency */ @@ -117,8 +122,22 @@ class FactureRec extends CommonInvoice public $usenewprice = 0; + public $date_lim_reglement; + public $cond_reglement_code; // Code in llx_c_paiement + public $mode_reglement_code; // Code in llx_c_paiement + public $suspended; // status + public $auto_validate; // 0 to create in draft, 1 to create and validate the new invoice + public $generate_pdf; // 1 to generate PDF on invoice generation (default) + + /** + * @var int 1 if status is draft + * @deprecated + */ + public $brouillon; + + /** * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password') * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)" @@ -345,14 +364,20 @@ class FactureRec extends CommonInvoice $facsrc->lines[$i]->special_code, $facsrc->lines[$i]->label, $facsrc->lines[$i]->fk_unit, - $facsrc->lines[$i]->multicurrency_subprice + $facsrc->lines[$i]->multicurrency_subprice, + 0, + 0, + null, + $facsrc->lines[$i]->pa_ht ); if ($result_insert < 0) { $error++; } else { $objectline = new FactureLigneRec($this->db); - if ($objectline->fetch($result_insert)) { + + $result2 = $objectline->fetch($result_insert); + if ($result2 > 0) { // Extrafields if (method_exists($facsrc->lines[$i], 'fetch_optionals')) { $facsrc->lines[$i]->fetch_optionals($facsrc->lines[$i]->id); @@ -363,6 +388,9 @@ class FactureRec extends CommonInvoice if ($result < 0) { $error++; } + } elseif ($result2 < 0) { + $this->errors[] = $objectline->error; + $error++; } } } @@ -413,6 +441,7 @@ class FactureRec extends CommonInvoice if ($error) { $this->db->rollback(); + return -3; } else { $this->db->commit(); return $this->id; @@ -504,14 +533,15 @@ class FactureRec extends CommonInvoice //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture'"; $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')'; if ($rowid) { - $sql .= ' AND f.rowid='.$rowid; + $sql .= ' AND f.rowid='.((int) $rowid); } elseif ($ref) { $sql .= " AND f.titre='".$this->db->escape($ref)."'"; + } else { + $sql .= ' AND f.rowid = 0'; } /* This field are not used for template invoice - if ($ref_ext) $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'"; - if ($ref_int) $sql.= " AND f.ref_int='".$this->db->escape($ref_int)."'"; - */ + if ($ref_ext) $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'"; + */ $result = $this->db->query($sql); if ($result) { @@ -523,11 +553,7 @@ class FactureRec extends CommonInvoice $this->titre = $obj->title; // deprecated $this->title = $obj->title; $this->ref = $obj->title; - $this->ref_client = $obj->ref_client; $this->suspended = $obj->suspended; - $this->type = $obj->type; - $this->datep = $obj->dp; - $this->date = $obj->df; $this->remise_percent = $obj->remise_percent; $this->remise_absolue = $obj->remise_absolue; $this->remise = $obj->remise; @@ -536,9 +562,6 @@ class FactureRec extends CommonInvoice $this->total_localtax1 = $obj->localtax1; $this->total_localtax2 = $obj->localtax2; $this->total_ttc = $obj->total_ttc; - $this->paye = $obj->paye; - $this->close_code = $obj->close_code; - $this->close_note = $obj->close_note; $this->socid = $obj->fk_soc; $this->date_lim_reglement = $this->db->jdate($obj->dlr); $this->mode_reglement_id = $obj->fk_mode_reglement; @@ -550,14 +573,12 @@ class FactureRec extends CommonInvoice $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; $this->fk_project = $obj->fk_project; $this->fk_account = $obj->fk_account; - $this->fk_facture_source = $obj->fk_facture_source; $this->note_private = $obj->note_private; $this->note_public = $obj->note_public; $this->user_author = $obj->fk_user_author; $this->modelpdf = $obj->model_pdf; // deprecated $this->model_pdf = $obj->model_pdf; - $this->rang = $obj->rang; - $this->special_code = $obj->special_code; + //$this->special_code = $obj->special_code; $this->frequency = $obj->frequency; $this->unit_frequency = $obj->unit_frequency; $this->date_when = $this->db->jdate($obj->date_when); @@ -639,11 +660,8 @@ class FactureRec extends CommonInvoice $sql = 'SELECT l.rowid, l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx, '; $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,'; - $sql .= ' l.info_bits, l.date_start_fill, l.date_end_fill, l.total_ht, l.total_tva, l.total_ttc, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht,'; - //$sql.= ' l.situation_percent, l.fk_prev_id,'; - //$sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice,'; + $sql .= ' l.info_bits, l.date_start_fill, l.date_end_fill, l.total_ht, l.total_tva, l.total_ttc, l.fk_product_fournisseur_price, l.buy_price_ht as pa_ht,'; $sql .= ' l.rang, l.special_code,'; - //$sql.= ' l.info_bits, l.total_ht, l.total_tva, l.total_localtax1, l.total_localtax2, l.total_ttc, l.fk_code_ventilation, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht,'; $sql .= ' l.fk_unit, l.fk_contract_line,'; $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,'; $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc'; @@ -665,12 +683,12 @@ class FactureRec extends CommonInvoice $line->rowid = $objp->rowid; $line->desc = $objp->description; // Description line $line->description = $objp->description; // Description line - $line->product_type = $objp->product_type; // Type of line $line->ref = $objp->product_ref; // Ref product $line->product_ref = $objp->product_ref; // Ref product $line->libelle = $objp->product_label; // deprecated $line->product_label = $objp->product_label; // Label product $line->product_desc = $objp->product_desc; // Description product + $line->product_type = $objp->product_type; // Type of line $line->fk_product_type = $objp->fk_product_type; // Type of product $line->qty = $objp->qty; $line->subprice = $objp->subprice; @@ -684,7 +702,7 @@ class FactureRec extends CommonInvoice $line->localtax1_type = $objp->localtax1_type; $line->localtax2_type = $objp->localtax2_type; $line->remise_percent = $objp->remise_percent; - $line->fk_remise_except = $objp->fk_remise_except; + //$line->fk_remise_except = $objp->fk_remise_except; $line->fk_product = $objp->fk_product; $line->date_start_fill = $objp->date_start_fill; $line->date_end_fill = $objp->date_end_fill; @@ -692,10 +710,16 @@ class FactureRec extends CommonInvoice $line->total_ht = $objp->total_ht; $line->total_tva = $objp->total_tva; $line->total_ttc = $objp->total_ttc; + //$line->code_ventilation = $objp->fk_code_ventilation; - $line->fk_fournprice = $objp->fk_fournprice; - $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht); - $line->pa_ht = $marginInfos[0]; + + $line->fk_product_fournisseur_price = $objp->fk_product_fournisseur_price; + $line->fk_fournprice = $objp->fk_product_fournisseur_price; // For backward compatibility + + $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_product_fournisseur_price, $objp->pa_ht); + + $line->buyprice = $marginInfos[0]; + $line->pa_ht = $marginInfos[0]; // For backward compatibility $line->marge_tx = $marginInfos[1]; $line->marque_tx = $marginInfos[2]; $line->rang = $objp->rang; @@ -831,6 +855,7 @@ class FactureRec extends CommonInvoice $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); // Clean vat code + $reg = array(); $vat_src_code = ''; if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; @@ -1271,6 +1296,8 @@ class FactureRec extends CommonInvoice $facture->type = self::TYPE_STANDARD; $facture->brouillon = 1; + $facture->statut = self::STATUS_DRAFT; + $facture->status = self::STATUS_DRAFT; $facture->date = (empty($facturerec->date_when) ? $now : $facturerec->date_when); // We could also use dol_now here but we prefer date_when so invoice has real date when we would like even if we generate later. $facture->socid = $facturerec->socid; @@ -1596,6 +1623,7 @@ class FactureRec extends CommonInvoice // Initialize parameters $this->id = 0; $this->ref = 'SPECIMEN'; + $this->title = 'SPECIMEN'; $this->specimen = 1; $this->socid = 1; $this->date = $nownotime; @@ -1906,6 +1934,18 @@ class FactureLigneRec extends CommonInvoiceLine public $table_element = 'facturedet_rec'; + public $fk_product_fournisseur_price; + public $fk_fournprice; // For backward compatibility + + public $rang; + + public $desc; + public $description; + + public $fk_product_type; // Use instead product_type + + public $fk_contract_line; + /** * Delete line in database @@ -1939,7 +1979,7 @@ class FactureLigneRec extends CommonInvoiceLine } if (!$error) { - $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id; + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.((int) $this->id); $res = $this->db->query($sql); if ($res === false) { @@ -1972,6 +2012,10 @@ class FactureLigneRec extends CommonInvoiceLine $sql .= ' l.date_start_fill, l.date_end_fill, l.info_bits, l.total_ht, l.total_tva, l.total_ttc,'; $sql .= ' l.rang, l.special_code,'; $sql .= ' l.fk_unit, l.fk_contract_line,'; + $sql .= ' l.import_key, l.fk_multicurrency,'; + $sql .= ' l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,'; + $sql .= ' l.buy_price_ht, l.fk_product_fournisseur_price,'; + $sql .= ' l.fk_user_author, l.fk_user_modif,'; $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc'; $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid'; @@ -2018,7 +2062,19 @@ class FactureLigneRec extends CommonInvoiceLine $this->special_code = $objp->special_code; $this->fk_unit = $objp->fk_unit; $this->fk_contract_line = $objp->fk_contract_line; + $this->import_key = $objp->import_key; + $this->fk_multicurrency = $objp->fk_multicurrency; + $this->multicurrency_code = $objp->multicurrency_code; + $this->multicurrency_subprice = $objp->multicurrency_subprice; + $this->multicurrency_total_ht = $objp->multicurrency_total_ht; + $this->multicurrency_total_tva = $objp->multicurrency_total_tva; + $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc; + $this->buy_price_ht = $objp->buy_price_ht; + + $this->fk_product_fournisseur_price = $objp->fk_product_fournisseur_price; + $this->fk_user_author = $objp->fk_user_author; + $this->fk_user_modif = $objp->fk_user_modif; $this->db->free($result); return 1; diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index 604147e3966..16880cd2369 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -99,6 +99,12 @@ class Facture extends CommonInvoice */ protected $table_ref_field = 'ref'; + /** + * @var int 1 if status is draft + * @deprecated + */ + public $brouillon; + /** * @var int thirdparty ID */ @@ -171,6 +177,7 @@ class Facture extends CommonInvoice //! id of source invoice if replacement invoice or credit note public $fk_facture_source; public $linked_objects = array(); + public $date_lim_reglement; public $cond_reglement_code; // Code in llx_c_paiement public $mode_reglement_code; // Code in llx_c_paiement @@ -446,6 +453,8 @@ class Facture extends CommonInvoice $this->mode_reglement_id = 0; } $this->brouillon = 1; + $this->status = self::STATUS_DRAFT; + $this->statut = self::STATUS_DRAFT; // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate) if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) { @@ -537,6 +546,8 @@ class Facture extends CommonInvoice $this->mode_reglement_id = 0; } $this->brouillon = 1; + $this->status = self::STATUS_DRAFT; + $this->statut = self::STATUS_DRAFT; $this->linked_objects = $_facrec->linkedObjectsIds; // We do not add link to template invoice or next invoice will be linked to all generated invoices @@ -683,7 +694,7 @@ class Facture extends CommonInvoice // Update ref with new one $this->ref = '(PROV'.$this->id.')'; - $sql = 'UPDATE '.MAIN_DB_PREFIX."facture SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; + $sql = 'UPDATE '.MAIN_DB_PREFIX."facture SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id); $resql = $this->db->query($sql); if (!$resql) { @@ -917,8 +928,9 @@ class Facture extends CommonInvoice $localtax1_tx = $_facrec->lines[$i]->localtax1_tx; $localtax2_tx = $_facrec->lines[$i]->localtax2_tx; - $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ?null:$_facrec->lines[$i]->fk_product_fournisseur_price; + $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price; $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice; + // If buyprice not defined from template invoice, we try to guess the best value if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) { require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; @@ -1181,6 +1193,7 @@ class Facture extends CommonInvoice foreach ($object->lines as $i => $line) { if (($object->lines[$i]->info_bits & 0x02) == 0x02) { // We do not clone line of discounts unset($object->lines[$i]); + continue; } // Bloc to update dates of service (month by month only if previously filled and similare to start and end of month) @@ -1207,7 +1220,7 @@ class Facture extends CommonInvoice } } - $object->lines[$i]->ref_ext = ''; // Do not clone ref_ext + $object->lines[$i]->ref_ext = ''; // Do not clone ref_ext } // Create clone @@ -1681,7 +1694,7 @@ class Facture extends CommonInvoice $this->fetchPreviousNextSituationInvoice(); } - if ($this->statut == self::STATUS_DRAFT) { + if ($this->status == self::STATUS_DRAFT) { $this->brouillon = 1; } @@ -1965,14 +1978,15 @@ class Facture extends CommonInvoice $sql .= " retained_warranty=".(empty($this->retained_warranty) ? "0" : $this->db->escape($this->retained_warranty)).","; $sql .= " retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) != '' ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'null').","; $sql .= " retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ?intval($this->retained_warranty_fk_cond_reglement) : "null"); - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } if (!$error) { @@ -2361,7 +2375,7 @@ class Facture extends CommonInvoice $now = dol_now(); - dol_syslog(get_class($this)."::set_paid rowid=".$this->id, LOG_DEBUG); + dol_syslog(get_class($this)."::set_paid rowid=".((int) $this->id), LOG_DEBUG); $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET'; $sql .= ' fk_statut='.self::STATUS_CLOSED; @@ -2499,7 +2513,7 @@ class Facture extends CommonInvoice */ public function setCanceled($user, $close_code = '', $close_note = '') { - dol_syslog(get_class($this)."::setCanceled rowid=".$this->id, LOG_DEBUG); + dol_syslog(get_class($this)."::setCanceled rowid=".((int) $this->id), LOG_DEBUG); $this->db->begin(); @@ -2581,8 +2595,8 @@ class Facture extends CommonInvoice $this->fetch_lines(); // Check parameters - if (!$this->brouillon) { - dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING); + if ($this->statut != self::STATUS_DRAFT) { + dol_syslog(get_class($this)."::validate status is not draft. operation canceled.", LOG_WARNING); return 0; } if (count($this->lines) <= 0) { @@ -2807,7 +2821,8 @@ class Facture extends CommonInvoice $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->error = $this->db->lasterror(); + $error++; + $this->error = $this->db->lasterror(); } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments @@ -2845,6 +2860,7 @@ class Facture extends CommonInvoice $this->ref = $num; $this->ref = $num; $this->statut = self::STATUS_VALIDATED; + $this->status = self::STATUS_VALIDATED; $this->brouillon = 0; $this->date_validation = $now; $i = 0; @@ -2883,7 +2899,7 @@ class Facture extends CommonInvoice * Update price of next invoice * * @param Translate $langs Translate object - * @return bool false if KO, true if OK + * @return bool false if KO, true if OK */ public function updatePriceNextInvoice(&$langs) { @@ -2896,6 +2912,7 @@ class Facture extends CommonInvoice } $next_invoice->brouillon = 1; + foreach ($next_invoice->lines as $line) { $result = $next_invoice->updateline( $line->id, @@ -2991,12 +3008,14 @@ class Facture extends CommonInvoice $old_statut = $this->statut; $this->brouillon = 1; $this->statut = self::STATUS_DRAFT; + $this->status = self::STATUS_DRAFT; // Call trigger $result = $this->call_trigger('BILL_UNVALIDATE', $user); if ($result < 0) { $error++; $this->statut = $old_statut; + $this->status = $old_statut; $this->brouillon = 0; } // End call triggers @@ -3358,7 +3377,7 @@ class Facture extends CommonInvoice dol_syslog(get_class($this)."::updateline rowid=$rowid, desc=$desc, pu=$pu, qty=$qty, remise_percent=$remise_percent, date_start=$date_start, date_end=$date_end, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, price_base_type=$price_base_type, info_bits=$info_bits, type=$type, fk_parent_line=$fk_parent_line pa_ht=$pa_ht, special_code=$special_code, fk_unit=$fk_unit, pu_ht_devise=$pu_ht_devise", LOG_DEBUG); - if ($this->brouillon) { + if ($this->statut == self::STATUS_DRAFT) { if (!$this->is_last_in_cycle() && empty($this->error)) { if (!$this->checkProgressLine($rowid, $situation_percent)) { if (!$this->error) { @@ -3627,7 +3646,7 @@ class Facture extends CommonInvoice dol_syslog(get_class($this)."::deleteline rowid=".$rowid, LOG_DEBUG); - if (!$this->brouillon) { + if ($this->statut != self::STATUS_DRAFT) { $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; return -1; } @@ -3936,7 +3955,7 @@ class Facture extends CommonInvoice $sql .= ' date_closing as dateclosing,'; $sql .= ' fk_user_author, fk_user_valid, fk_user_closing'; $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as c'; - $sql .= ' WHERE c.rowid = '.$id; + $sql .= ' WHERE c.rowid = '.((int) $id); $result = $this->db->query($sql); if ($result) { @@ -4806,7 +4825,7 @@ class Facture extends CommonInvoice $fieldname = 'retained_warranty'; $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= ' SET '.$fieldname.' = '.floatval($value); - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); if ($this->db->query($sql)) { $this->retained_warranty = floatval($value); @@ -4843,7 +4862,7 @@ class Facture extends CommonInvoice $fieldname = 'retained_warranty_date_limit'; $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= ' SET '.$fieldname.' = '.(strval($timestamp) != '' ? '\''.$this->db->idate($timestamp).'\'' : 'null'); - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); if ($this->db->query($sql)) { $this->retained_warranty_date_limit = $timestamp; diff --git a/htdocs/compta/facture/class/paymentterm.class.php b/htdocs/compta/facture/class/paymentterm.class.php index 4795a9b2062..87cd50d27c6 100644 --- a/htdocs/compta/facture/class/paymentterm.class.php +++ b/htdocs/compta/facture/class/paymentterm.class.php @@ -145,7 +145,8 @@ class PaymentTerm // extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } if (!$error) { @@ -191,7 +192,7 @@ class PaymentTerm // extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; - $sql .= " WHERE t.rowid = ".$id; + $sql .= " WHERE t.rowid = ".((int) $id); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); @@ -317,7 +318,8 @@ class PaymentTerm // extends CommonObject dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } // Commit or rollback @@ -355,7 +357,8 @@ class PaymentTerm // extends CommonObject dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } // Commit or rollback diff --git a/htdocs/compta/facture/invoicetemplate_list.php b/htdocs/compta/facture/invoicetemplate_list.php index f34b34a6347..b271ea2e876 100644 --- a/htdocs/compta/facture/invoicetemplate_list.php +++ b/htdocs/compta/facture/invoicetemplate_list.php @@ -170,7 +170,8 @@ if ($socid > 0) { */ if (GETPOST('cancel', 'alpha')) { - $action = 'list'; $massaction = ''; + $action = 'list'; + $massaction = ''; } if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index 4a4aa3f3f33..abbb116da60 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -248,7 +248,8 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); */ if (GETPOST('cancel', 'alpha')) { - $action = 'list'; $massaction = ''; + $action = 'list'; + $massaction = ''; } if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php index b6cf7ec5c06..719c92ca6f0 100644 --- a/htdocs/compta/facture/prelevement.php +++ b/htdocs/compta/facture/prelevement.php @@ -576,7 +576,9 @@ if ($object->id > 0) { print dol_get_fiche_end(); - $numopen = 0; $pending = 0; $numclosed = 0; + $numopen = 0; + $pending = 0; + $numclosed = 0; // How many Direct debit opened requests ? diff --git a/htdocs/compta/facture/stats/index.php b/htdocs/compta/facture/stats/index.php index 536beff168d..2818fa5f3b9 100644 --- a/htdocs/compta/facture/stats/index.php +++ b/htdocs/compta/facture/stats/index.php @@ -133,7 +133,8 @@ $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); if (!$mesg) { $px1->SetData($data); - $i = $startyear; $legend = array(); + $i = $startyear; + $legend = array(); while ($i <= $endyear) { $legend[] = $i; $i++; @@ -168,7 +169,8 @@ $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); if (!$mesg) { $px2->SetData($data); - $i = $startyear; $legend = array(); + $i = $startyear; + $legend = array(); while ($i <= $endyear) { $legend[] = $i; $i++; @@ -212,7 +214,8 @@ $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); if (!$mesg) { $px3->SetData($data); - $i = $startyear; $legend = array(); + $i = $startyear; + $legend = array(); while ($i <= $endyear) { $legend[] = $i; $i++; diff --git a/htdocs/compta/index.php b/htdocs/compta/index.php index f46b1e7f8fb..b74c863bc30 100644 --- a/htdocs/compta/index.php +++ b/htdocs/compta/index.php @@ -9,6 +9,7 @@ * Copyright (C) 2019 Nicolas ZABOURI * Copyright (C) 2020 Tobias Sekan * Copyright (C) 2020 Josep Lluís Amador + * Copyright (C) 2021 Frédéric France * * 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 @@ -271,6 +272,7 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $sql = "SELECT f.ref, f.rowid, f.total_ht, f.total_tva, f.total_ttc, f.type, f.ref_supplier, f.fk_statut as status, f.paye"; $sql .= ", s.nom as name"; $sql .= ", s.rowid as socid, s.email"; + $sql .= ", s.code_client, s.code_compta"; $sql .= ", s.code_fournisseur, s.code_compta_fournisseur"; $sql .= ", cc.rowid as country_id, cc.code as country_code"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f, ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays"; @@ -997,6 +999,7 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $sql .= ", s.nom as name"; $sql .= ", s.rowid as socid, s.email"; $sql .= ", s.code_client, s.code_compta"; + $sql .= ", s.code_fournisseur, s.code_compta_fournisseur"; $sql .= ", cc.rowid as country_id, cc.code as country_code"; $sql .= ", sum(pf.amount) as am"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays,".MAIN_DB_PREFIX."facture as f"; @@ -1019,6 +1022,7 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $sql .= " GROUP BY f.rowid, f.ref, f.fk_statut, f.datef, f.type, f.total_ht, f.total_tva, f.total_ttc, f.paye, f.tms, f.date_lim_reglement,"; $sql .= " s.nom, s.rowid, s.email, s.code_client, s.code_compta, cc.rowid, cc.code"; + $sql .= ", s.code_fournisseur, s.code_compta_fournisseur"; $sql .= " ORDER BY f.datef ASC, f.ref ASC"; $resql = $db->query($sql); diff --git a/htdocs/compta/journal/sellsjournal.php b/htdocs/compta/journal/sellsjournal.php index 39faf295c45..46c56f3dca5 100644 --- a/htdocs/compta/journal/sellsjournal.php +++ b/htdocs/compta/journal/sellsjournal.php @@ -88,7 +88,8 @@ $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_starty $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); if (empty($date_start) || empty($date_end)) { // We define date_start and date_end - $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false); $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false); + $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false); + $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false); } $name = $langs->trans("SellsJournal"); diff --git a/htdocs/compta/localtax/class/localtax.class.php b/htdocs/compta/localtax/class/localtax.class.php index cdea12902bc..46b2b2b7805 100644 --- a/htdocs/compta/localtax/class/localtax.class.php +++ b/htdocs/compta/localtax/class/localtax.class.php @@ -180,7 +180,7 @@ class Localtax extends CommonObject $sql .= " fk_bank=".(int) $this->fk_bank.","; $sql .= " fk_user_creat=".(int) $this->fk_user_creat.","; $sql .= " fk_user_modif=".(int) $this->fk_user_modif; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); @@ -234,7 +234,7 @@ class Localtax extends CommonObject $sql .= " b.rappro"; $sql .= " FROM ".MAIN_DB_PREFIX."localtax as t"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON t.fk_bank = b.rowid"; - $sql .= " WHERE t.rowid = ".$id; + $sql .= " WHERE t.rowid = ".((int) $id); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); @@ -284,7 +284,7 @@ class Localtax extends CommonObject // End call triggers $sql = "DELETE FROM ".MAIN_DB_PREFIX."localtax"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); diff --git a/htdocs/compta/localtax/clients.php b/htdocs/compta/localtax/clients.php index 603e8564927..72155845b0c 100644 --- a/htdocs/compta/localtax/clients.php +++ b/htdocs/compta/localtax/clients.php @@ -51,7 +51,8 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $q = GETPOST("q"); if (empty($q)) { if (GETPOST("month")) { - $date_start = dol_get_first_day($year_start, GETPOST("month"), false); $date_end = dol_get_last_day($year_start, GETPOST("month"), false); + $date_start = dol_get_first_day($year_start, GETPOST("month"), false); + $date_end = dol_get_last_day($year_start, GETPOST("month"), false); } else { $date_start = dol_get_first_day($year_start, empty($conf->global->SOCIETE_FISCAL_MONTH_START) ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START, false); if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) { @@ -64,16 +65,20 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e } } else { if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + $date_start = dol_get_first_day($year_start, 1, false); + $date_end = dol_get_last_day($year_start, 3, false); } if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + $date_start = dol_get_first_day($year_start, 4, false); + $date_end = dol_get_last_day($year_start, 6, false); } if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + $date_start = dol_get_first_day($year_start, 7, false); + $date_end = dol_get_last_day($year_start, 9, false); } if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + $date_start = dol_get_first_day($year_start, 10, false); + $date_end = dol_get_last_day($year_start, 12, false); } } } @@ -206,7 +211,8 @@ if ($calc == 0 || $calc == 2) { $reshook = $hookmanager->executeHooks('addVatLine', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if (is_array($coll_list)) { - $total = 0; $totalamount = 0; + $total = 0; + $totalamount = 0; $i = 1; foreach ($coll_list as $coll) { if (($min == 0 || ($min > 0 && $coll->amount > $min)) && ($local == 1 ? $coll->localtax1 : $coll->localtax2) != 0) { @@ -270,7 +276,8 @@ if ($calc == 0 || $calc == 1) { $reshook = $hookmanager->executeHooks('addVatLine', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if (is_array($coll_list)) { - $total = 0; $totalamount = 0; + $total = 0; + $totalamount = 0; $i = 1; foreach ($coll_list as $coll) { if (($min == 0 || ($min > 0 && $coll->amount > $min)) && ($local == 1 ? $coll->localtax1 : $coll->localtax2) != 0) { diff --git a/htdocs/compta/localtax/index.php b/htdocs/compta/localtax/index.php index 051a98a4b3b..86fa3fe52f0 100644 --- a/htdocs/compta/localtax/index.php +++ b/htdocs/compta/localtax/index.php @@ -50,23 +50,28 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $q = GETPOST("q", "int"); if (empty($q)) { if (GETPOST("month", "int")) { - $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); + $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); + $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); } else { $date_start = dol_get_first_day($year_start, $conf->global->SOCIETE_FISCAL_MONTH_START, false); $date_end = dol_time_plus_duree($date_start, 1, 'y') - 1; } } else { if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + $date_start = dol_get_first_day($year_start, 1, false); + $date_end = dol_get_last_day($year_start, 3, false); } if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + $date_start = dol_get_first_day($year_start, 4, false); + $date_end = dol_get_last_day($year_start, 6, false); } if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + $date_start = dol_get_first_day($year_start, 7, false); + $date_end = dol_get_last_day($year_start, 9, false); } if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + $date_start = dol_get_first_day($year_start, 10, false); + $date_end = dol_get_last_day($year_start, 12, false); } } } @@ -286,8 +291,12 @@ $tmp = dol_getdate($date_end); $yend = $tmp['year']; $mend = $tmp['mon']; -$total = 0; $subtotalcoll = 0; $subtotalpaye = 0; $subtotal = 0; -$i = 0; $mcursor = 0; +$total = 0; +$subtotalcoll = 0; +$subtotalpaye = 0; +$subtotal = 0; +$i = 0; +$mcursor = 0; while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) { // $mcursor is to avoid too large loop //$m = $conf->global->SOCIETE_FISCAL_MONTH_START + ($mcursor % 12); if ($m == 13) { @@ -537,7 +546,8 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) { // $ print " \n"; print "\n"; - $i++; $m++; + $i++; + $m++; if ($i > 2) { print ''; print ''.$langs->trans("SubTotal").':'; @@ -546,7 +556,9 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) { // $ print ''.price(price2num($subtotal, 'MT')).''; print ' '; $i = 0; - $subtotalcoll = 0; $subtotalpaye = 0; $subtotal = 0; + $subtotalcoll = 0; + $subtotalpaye = 0; + $subtotal = 0; } } print ''.$langs->trans("TotalToPay").':'.price(price2num($total, 'MT')).''; diff --git a/htdocs/compta/localtax/quadri_detail.php b/htdocs/compta/localtax/quadri_detail.php index aec90544e09..a2904c861f4 100644 --- a/htdocs/compta/localtax/quadri_detail.php +++ b/htdocs/compta/localtax/quadri_detail.php @@ -61,7 +61,8 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $q = GETPOST("q", "int"); if (empty($q)) { if (GETPOST("month", "int")) { - $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); + $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); + $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); } else { $date_start = dol_get_first_day($year_start, empty($conf->global->SOCIETE_FISCAL_MONTH_START) ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START, false); if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) { @@ -74,16 +75,20 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e } } else { if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + $date_start = dol_get_first_day($year_start, 1, false); + $date_end = dol_get_last_day($year_start, 3, false); } if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + $date_start = dol_get_first_day($year_start, 4, false); + $date_end = dol_get_last_day($year_start, 6, false); } if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + $date_start = dol_get_first_day($year_start, 7, false); + $date_end = dol_get_last_day($year_start, 9, false); } if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + $date_start = dol_get_first_day($year_start, 10, false); + $date_end = dol_get_last_day($year_start, 12, false); } } } diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php index 0fcbf6a914a..7f03f4a569c 100644 --- a/htdocs/compta/paiement.php +++ b/htdocs/compta/paiement.php @@ -559,12 +559,14 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $alreadypayedlabel = $langs->trans('Received'); $multicurrencyalreadypayedlabel = $langs->trans('MulticurrencyReceived'); if ($facture->type == 2) { - $alreadypayedlabel = $langs->trans("PaidBack"); $multicurrencyalreadypayedlabel = $langs->trans("MulticurrencyPaidBack"); + $alreadypayedlabel = $langs->trans("PaidBack"); + $multicurrencyalreadypayedlabel = $langs->trans("MulticurrencyPaidBack"); } $remaindertopay = $langs->trans('RemainderToTake'); $multicurrencyremaindertopay = $langs->trans('MulticurrencyRemainderToTake'); if ($facture->type == 2) { - $remaindertopay = $langs->trans("RemainderToPayBack"); $multicurrencyremaindertopay = $langs->trans("MulticurrencyRemainderToPayBack"); + $remaindertopay = $langs->trans("RemainderToPayBack"); + $multicurrencyremaindertopay = $langs->trans("MulticurrencyRemainderToPayBack"); } $i = 0; diff --git a/htdocs/compta/paiement/cheque/card.php b/htdocs/compta/paiement/cheque/card.php index c8e6691afc6..847dae1bc29 100644 --- a/htdocs/compta/paiement/cheque/card.php +++ b/htdocs/compta/paiement/cheque/card.php @@ -235,8 +235,8 @@ if ($action == 'builddoc' && $user->rights->banque->cheque) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.(empty($conf->global->MAIN_JUMP_TAG) ? '' : '#builddoc')); exit; } -} // Remove file in doc form -elseif ($action == 'remove_file' && $user->rights->banque->cheque) { +} elseif ($action == 'remove_file' && $user->rights->banque->cheque) { + // Remove file in doc form if ($object->fetch($id) > 0) { include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -364,8 +364,9 @@ if ($action == 'new') { print ''; print '
'; - $sql = "SELECT ba.rowid as bid, b.datec as datec, b.dateo as date, b.rowid as transactionid, "; - $sql .= " b.amount, ba.label, b.emetteur, b.num_chq, b.banque,"; + $sql = "SELECT ba.rowid as bid, ba.label,"; + $sql .= " b.rowid as transactionid, b.label as transactionlabel, b.datec as datec, b.dateo as date, "; + $sql .= " b.amount, b.emetteur, b.num_chq, b.banque,"; $sql .= " p.rowid as paymentid, p.ref as paymentref"; $sql .= " FROM ".MAIN_DB_PREFIX."bank as b"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement as p ON p.fk_bank = b.rowid"; @@ -393,6 +394,8 @@ if ($action == 'new') { $lines[$obj->bid][$i]["numero"] = $obj->num_chq; $lines[$obj->bid][$i]["banque"] = $obj->banque; $lines[$obj->bid][$i]["id"] = $obj->transactionid; + $lines[$obj->bid][$i]["ref"] = $obj->transactionid; + $lines[$obj->bid][$i]["label"] = $obj->transactionlabel; $lines[$obj->bid][$i]["paymentid"] = $obj->paymentid; $lines[$obj->bid][$i]["paymentref"] = $obj->paymentref; $i++; @@ -473,8 +476,9 @@ if ($action == 'new') { print ''; // Link to bank transaction print ''; - $accountlinestatic->rowid = $value["id"]; - if ($accountlinestatic->rowid) { + $accountlinestatic->id = $value["id"]; + $accountlinestatic->ref = $value["ref"]; + if ($accountlinestatic->id > 0) { print $accountlinestatic->getNomUrl(1); } else { print ' '; @@ -594,7 +598,7 @@ if ($action == 'new') { // List of bank checks - $sql = "SELECT b.rowid, b.amount, b.num_chq, b.emetteur,"; + $sql = "SELECT b.rowid, b.rowid as ref, b.label, b.amount, b.num_chq, b.emetteur,"; $sql .= " b.dateo as date, b.datec as datec, b.banque,"; $sql .= " p.rowid as pid, p.ref as pref, ba.rowid as bid, p.statut"; $sql .= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; @@ -648,8 +652,9 @@ if ($action == 'new') { print ''; // Link to bank transaction print ''; - $accountlinestatic->rowid = $objp->rowid; - if ($accountlinestatic->rowid) { + $accountlinestatic->id = $objp->rowid; + $accountlinestatic->ref = $objp->ref; + if ($accountlinestatic->id > 0) { print $accountlinestatic->getNomUrl(1); } else { print ' '; diff --git a/htdocs/compta/paiement/cheque/class/remisecheque.class.php b/htdocs/compta/paiement/cheque/class/remisecheque.class.php index 3d73c59d967..8af9d5a6543 100644 --- a/htdocs/compta/paiement/cheque/class/remisecheque.class.php +++ b/htdocs/compta/paiement/cheque/class/remisecheque.class.php @@ -191,7 +191,7 @@ class RemiseCheque extends CommonObject if ($this->id > 0 && $this->errno == 0) { $sql = "UPDATE ".MAIN_DB_PREFIX."bordereau_cheque"; $sql .= " SET ref='(PROV".$this->id.")'"; - $sql .= " WHERE rowid=".$this->id.""; + $sql .= " WHERE rowid=".((int) $this->id).""; $resql = $this->db->query($sql); if (!$resql) { diff --git a/htdocs/compta/paiement/class/paiement.class.php b/htdocs/compta/paiement/class/paiement.class.php index 7db9ff922d9..42b05f39263 100644 --- a/htdocs/compta/paiement/class/paiement.class.php +++ b/htdocs/compta/paiement/class/paiement.class.php @@ -169,7 +169,7 @@ class Paiement extends CommonObject $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; $sql .= ' WHERE p.entity IN ('.getEntity('invoice').')'; if ($id > 0) { - $sql .= ' AND p.rowid = '.$id; + $sql .= ' AND p.rowid = '.((int) $id); } elseif ($ref) { $sql .= " AND p.ref = '".$ref."'"; } elseif ($fk_bank) { @@ -335,9 +335,8 @@ class Paiement extends CommonObject dol_syslog("Invoice ".$facid." is not a standard, nor replacement invoice, nor credit note, nor deposit invoice, nor situation invoice. We do nothing more."); } elseif ($remaintopay) { dol_syslog("Remain to pay for invoice ".$facid." not null. We do nothing more."); - } - //else if ($mustwait) dol_syslog("There is ".$mustwait." differed payment to process, we do nothing more."); - else { + // } else if ($mustwait) dol_syslog("There is ".$mustwait." differed payment to process, we do nothing more."); + } else { // If invoice is a down payment, we also convert down payment to discount if ($invoice->type == Facture::TYPE_DEPOSIT) { $amount_ht = $amount_tva = $amount_ttc = array(); @@ -900,7 +899,7 @@ class Paiement extends CommonObject { $sql = 'SELECT p.rowid, p.datec, p.fk_user_creat, p.fk_user_modif, p.tms'; $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement as p'; - $sql .= ' WHERE p.rowid = '.$id; + $sql .= ' WHERE p.rowid = '.((int) $id); dol_syslog(get_class($this).'::info', LOG_DEBUG); $result = $this->db->query($sql); diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index f70daf75c3a..3d04cf1f6a5 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -427,7 +427,7 @@ class BonPrelevement extends CommonObject $sql .= " SET fk_user_credit = ".$user->id; $sql .= ", statut = ".self::STATUS_CREDITED; $sql .= ", date_credit = '".$this->db->idate($date)."'"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $sql .= " AND entity = ".$conf->entity; $sql .= " AND statut = ".self::STATUS_TRANSFERED; diff --git a/htdocs/compta/prelevement/class/rejetprelevement.class.php b/htdocs/compta/prelevement/class/rejetprelevement.class.php index 70742d24685..0faea8a159c 100644 --- a/htdocs/compta/prelevement/class/rejetprelevement.class.php +++ b/htdocs/compta/prelevement/class/rejetprelevement.class.php @@ -128,7 +128,7 @@ class RejetPrelevement // Tag the line to refused $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes "; $sql .= " SET statut = 3"; - $sql .= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".((int) $id); if (!$this->db->query($sql)) { dol_syslog("RejetPrelevement::create Erreur 5"); diff --git a/htdocs/compta/resultat/clientfourn.php b/htdocs/compta/resultat/clientfourn.php index 374b2b3377e..b30ab96f7e6 100644 --- a/htdocs/compta/resultat/clientfourn.php +++ b/htdocs/compta/resultat/clientfourn.php @@ -111,19 +111,24 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e } else { $month_end = $month_start; } - $date_start = dol_get_first_day($year_start, $month_start, false); $date_end = dol_get_last_day($year_end, $month_end, false); + $date_start = dol_get_first_day($year_start, $month_start, false); + $date_end = dol_get_last_day($year_end, $month_end, false); } if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + $date_start = dol_get_first_day($year_start, 1, false); + $date_end = dol_get_last_day($year_start, 3, false); } if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + $date_start = dol_get_first_day($year_start, 4, false); + $date_end = dol_get_last_day($year_start, 6, false); } if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + $date_start = dol_get_first_day($year_start, 7, false); + $date_end = dol_get_last_day($year_start, 9, false); } if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + $date_start = dol_get_first_day($year_start, 10, false); + $date_end = dol_get_last_day($year_start, 12, false); } } diff --git a/htdocs/compta/resultat/index.php b/htdocs/compta/resultat/index.php index a56b44d6d7c..0616327cc39 100644 --- a/htdocs/compta/resultat/index.php +++ b/htdocs/compta/resultat/index.php @@ -79,19 +79,24 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e } else { $month_end = $month_start; } - $date_start = dol_get_first_day($year_start, $month_start, false); $date_end = dol_get_last_day($year_end, $month_end, false); + $date_start = dol_get_first_day($year_start, $month_start, false); + $date_end = dol_get_last_day($year_end, $month_end, false); } if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + $date_start = dol_get_first_day($year_start, 1, false); + $date_end = dol_get_last_day($year_start, 3, false); } if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + $date_start = dol_get_first_day($year_start, 4, false); + $date_end = dol_get_last_day($year_start, 6, false); } if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + $date_start = dol_get_first_day($year_start, 7, false); + $date_end = dol_get_last_day($year_start, 9, false); } if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + $date_start = dol_get_first_day($year_start, 10, false); + $date_end = dol_get_last_day($year_start, 12, false); } } diff --git a/htdocs/compta/resultat/result.php b/htdocs/compta/resultat/result.php index 75d73eeca31..df3a82a4b7f 100644 --- a/htdocs/compta/resultat/result.php +++ b/htdocs/compta/resultat/result.php @@ -91,19 +91,24 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e } else { $month_end = $month_start; } - $date_start = dol_get_first_day($year_start, $month_start, false); $date_end = dol_get_last_day($year_end, $month_end, false); + $date_start = dol_get_first_day($year_start, $month_start, false); + $date_end = dol_get_last_day($year_end, $month_end, false); } if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + $date_start = dol_get_first_day($year_start, 1, false); + $date_end = dol_get_last_day($year_start, 3, false); } if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + $date_start = dol_get_first_day($year_start, 4, false); + $date_end = dol_get_last_day($year_start, 6, false); } if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + $date_start = dol_get_first_day($year_start, 7, false); + $date_end = dol_get_last_day($year_start, 9, false); } if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + $date_start = dol_get_first_day($year_start, 10, false); + $date_end = dol_get_last_day($year_start, 12, false); } } diff --git a/htdocs/compta/sociales/card.php b/htdocs/compta/sociales/card.php index 3c2b26a83d8..430df926859 100644 --- a/htdocs/compta/sociales/card.php +++ b/htdocs/compta/sociales/card.php @@ -323,7 +323,7 @@ if ($action == 'create') { print $langs->trans("Date"); print ''; print ''; - print $form->selectDate(!empty($dateech) ? $dateech : '-1', 'ech', 0, 0, 0, 'charge', 1); + print $form->selectDate(!empty($dateech) ? $dateech : '-1', 'ech', 0, 0, 0, 'charge', 1, 1); print ''; print "\n"; @@ -536,10 +536,10 @@ if ($id > 0) { // Amount if ($action == 'edit') { print ''.$langs->trans("AmountTTC").""; - print ''; + print ''; print ""; } else { - print ''.$langs->trans("AmountTTC").''.price($object->amount, 0, $outputlangs, 1, -1, -1, $conf->currency).''; + print ''.$langs->trans("AmountTTC").''.price($object->amount, 0, $langs, 1, -1, -1, $conf->currency).''; } // Mode of payment @@ -612,7 +612,8 @@ if ($id > 0) { $totalpaye = 0; $num = $db->num_rows($resql); - $i = 0; $total = 0; + $i = 0; + $total = 0; print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table print ''; diff --git a/htdocs/compta/sociales/class/chargesociales.class.php b/htdocs/compta/sociales/class/chargesociales.class.php index f718a9a48b7..d7fcd9278a9 100644 --- a/htdocs/compta/sociales/class/chargesociales.class.php +++ b/htdocs/compta/sociales/class/chargesociales.class.php @@ -149,7 +149,7 @@ class ChargeSociales extends CommonObject if ($ref) { $sql .= " AND cs.rowid = ".$ref; } else { - $sql .= " AND cs.rowid = ".$id; + $sql .= " AND cs.rowid = ".((int) $id); } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); @@ -311,7 +311,7 @@ class ChargeSociales extends CommonObject } if (!$error) { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."chargesociales WHERE rowid=".$this->id; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."chargesociales WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { @@ -350,13 +350,14 @@ class ChargeSociales extends CommonObject $sql .= ", fk_projet=".($this->fk_project > 0 ? $this->db->escape($this->fk_project) : "NULL"); $sql .= ", fk_user=".($this->fk_user > 0 ? $this->db->escape($this->fk_user) : "NULL"); $sql .= ", fk_user_modif=".$user->id; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } if (!$error) { @@ -671,7 +672,7 @@ class ChargeSociales extends CommonObject $sql = "SELECT e.rowid, e.tms as datem, e.date_creation as datec, e.date_valid as datev, e.import_key,"; $sql .= " e.fk_user_author, e.fk_user_modif, e.fk_user_valid"; $sql .= " FROM ".MAIN_DB_PREFIX."chargesociales as e"; - $sql .= " WHERE e.rowid = ".$id; + $sql .= " WHERE e.rowid = ".((int) $id); dol_syslog(get_class($this)."::info", LOG_DEBUG); $result = $this->db->query($sql); diff --git a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php index 4fda644e1c0..8f7f13e6043 100644 --- a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php +++ b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php @@ -262,7 +262,7 @@ class PaymentSocialContribution extends CommonObject $sql .= ' b.fk_account'; $sql .= " FROM ".MAIN_DB_PREFIX."paiementcharge as t LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepaiement = pt.id"; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; - $sql .= " WHERE t.rowid = ".$id; + $sql .= " WHERE t.rowid = ".((int) $id); // TODO link on entity of tax; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); @@ -362,14 +362,15 @@ class PaymentSocialContribution extends CommonObject $sql .= " fk_user_modif=".(isset($this->fk_user_modif) ? $this->fk_user_modif : "null").""; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } // Commit or rollback @@ -415,12 +416,13 @@ class PaymentSocialContribution extends CommonObject if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."paiementcharge"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } } diff --git a/htdocs/compta/sociales/payments.php b/htdocs/compta/sociales/payments.php index 6a573ea4621..21f599f42dc 100644 --- a/htdocs/compta/sociales/payments.php +++ b/htdocs/compta/sociales/payments.php @@ -6,6 +6,7 @@ * Copyright (C) 2011-2014 Juanjo Menent * Copyright (C) 2015 Jean-François Ferry * Copyright (C) 2019 Nicolas ZABOURI + * Copyright (C) 2021 Gauthier VERDOL * * 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 @@ -31,7 +32,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/paymentsocialcontribution.class.php'; -require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php'; +require_once DOL_DOCUMENT_ROOT.'/salaries/class/salary.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formsocialcontrib.class.php'; @@ -95,7 +96,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $tva_static = new Tva($db); $socialcontrib = new ChargeSociales($db); $payment_sc_static = new PaymentSocialContribution($db); -$sal_static = new PaymentSalary($db); +$sal_static = new Salary($db); $accountstatic = new Account($db); $formsocialcontrib = new FormSocialContrib($db); diff --git a/htdocs/compta/stats/byratecountry.php b/htdocs/compta/stats/byratecountry.php index 1f4de217bac..79379ee0b24 100644 --- a/htdocs/compta/stats/byratecountry.php +++ b/htdocs/compta/stats/byratecountry.php @@ -1,6 +1,6 @@ - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-2021 Frédéric France * * 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 @@ -74,19 +74,24 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $year_end++; } } - $date_start = dol_get_first_day($year_start, $month_start, false); $date_end = dol_get_last_day($year_end, $month_end, false); + $date_start = dol_get_first_day($year_start, $month_start, false); + $date_end = dol_get_last_day($year_end, $month_end, false); } else { if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + $date_start = dol_get_first_day($year_start, 1, false); + $date_end = dol_get_last_day($year_start, 3, false); } if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + $date_start = dol_get_first_day($year_start, 4, false); + $date_end = dol_get_last_day($year_start, 6, false); } if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + $date_start = dol_get_first_day($year_start, 7, false); + $date_end = dol_get_last_day($year_start, 9, false); } if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + $date_start = dol_get_first_day($year_start, 10, false); + $date_end = dol_get_last_day($year_start, 12, false); } } } @@ -109,7 +114,7 @@ if (empty($min)) { // Define modetax (0 or 1) // 0=normal, 1=option vat for services is on debit, 2=option on payments for products -$modetax = $conf->global->TAX_MODE; +$modetax = empty($conf->global->TAX_MODE) ? 0 : $conf->global->TAX_MODE; if (GETPOSTISSET("modetax")) { $modetax = GETPOST("modetax", 'int'); } @@ -175,17 +180,21 @@ if ($modetax == 2) { $calcmode .= '
('.$langs->trans("TaxModuleSetupToModifyRules", DOL_URL_ROOT.'/admin/taxes.php').')'; // Set period $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); -$prevyear = $year_start; $prevquarter = $q; +$prevyear = $year_start; +$prevquarter = $q; if ($prevquarter > 1) { $prevquarter--; } else { - $prevquarter = 4; $prevyear--; + $prevquarter = 4; + $prevyear--; } -$nextyear = $year_start; $nextquarter = $q; +$nextyear = $year_start; +$nextquarter = $q; if ($nextquarter < 4) { $nextquarter++; } else { - $nextquarter = 1; $nextyear++; + $nextquarter = 1; + $nextyear++; } $description .= $fsearch; $builddate = dol_now(); diff --git a/htdocs/compta/stats/cabyprodserv.php b/htdocs/compta/stats/cabyprodserv.php index eb678900112..c6c0e8e0816 100644 --- a/htdocs/compta/stats/cabyprodserv.php +++ b/htdocs/compta/stats/cabyprodserv.php @@ -119,19 +119,24 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $year_end++; } } - $date_start = dol_get_first_day($year_start, $month_start, false); $date_end = dol_get_last_day($year_end, $month_end, false); + $date_start = dol_get_first_day($year_start, $month_start, false); + $date_end = dol_get_last_day($year_end, $month_end, false); } else { if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + $date_start = dol_get_first_day($year_start, 1, false); + $date_end = dol_get_last_day($year_start, 3, false); } if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + $date_start = dol_get_first_day($year_start, 4, false); + $date_end = dol_get_last_day($year_start, 6, false); } if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + $date_start = dol_get_first_day($year_start, 7, false); + $date_end = dol_get_last_day($year_start, 9, false); } if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + $date_start = dol_get_first_day($year_start, 10, false); + $date_end = dol_get_last_day($year_start, 12, false); } } } else { diff --git a/htdocs/compta/stats/cabyuser.php b/htdocs/compta/stats/cabyuser.php index bad94809672..10c938ad8b4 100644 --- a/htdocs/compta/stats/cabyuser.php +++ b/htdocs/compta/stats/cabyuser.php @@ -100,19 +100,24 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $year_end++; } } - $date_start = dol_get_first_day($year_start, $month_start, false); $date_end = dol_get_last_day($year_end, $month_end, false); + $date_start = dol_get_first_day($year_start, $month_start, false); + $date_end = dol_get_last_day($year_end, $month_end, false); } if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + $date_start = dol_get_first_day($year_start, 1, false); + $date_end = dol_get_last_day($year_start, 3, false); } if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + $date_start = dol_get_first_day($year_start, 4, false); + $date_end = dol_get_last_day($year_start, 6, false); } if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + $date_start = dol_get_first_day($year_start, 7, false); + $date_end = dol_get_last_day($year_start, 9, false); } if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + $date_start = dol_get_first_day($year_start, 10, false); + $date_end = dol_get_last_day($year_start, 12, false); } } else { // TODO We define q diff --git a/htdocs/compta/stats/casoc.php b/htdocs/compta/stats/casoc.php index 0bee53574a0..159422c081c 100644 --- a/htdocs/compta/stats/casoc.php +++ b/htdocs/compta/stats/casoc.php @@ -120,19 +120,24 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $year_end++; } } - $date_start = dol_get_first_day($year_start, $month_start, false); $date_end = dol_get_last_day($year_end, $month_end, false); + $date_start = dol_get_first_day($year_start, $month_start, false); + $date_end = dol_get_last_day($year_end, $month_end, false); } if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + $date_start = dol_get_first_day($year_start, 1, false); + $date_end = dol_get_last_day($year_start, 3, false); } if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + $date_start = dol_get_first_day($year_start, 4, false); + $date_end = dol_get_last_day($year_start, 6, false); } if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + $date_start = dol_get_first_day($year_start, 7, false); + $date_end = dol_get_last_day($year_start, 9, false); } if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + $date_start = dol_get_first_day($year_start, 10, false); + $date_end = dol_get_last_day($year_start, 12, false); } } else { // TODO We define q diff --git a/htdocs/compta/stats/index.php b/htdocs/compta/stats/index.php index eb30010b4b8..5f5ecb1de91 100644 --- a/htdocs/compta/stats/index.php +++ b/htdocs/compta/stats/index.php @@ -73,19 +73,24 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e } else { $month_end = $month_start; } - $date_start = dol_get_first_day($year_start, $month_start, false); $date_end = dol_get_last_day($year_end, $month_end, false); + $date_start = dol_get_first_day($year_start, $month_start, false); + $date_end = dol_get_last_day($year_end, $month_end, false); } if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + $date_start = dol_get_first_day($year_start, 1, false); + $date_end = dol_get_last_day($year_start, 3, false); } if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + $date_start = dol_get_first_day($year_start, 4, false); + $date_end = dol_get_last_day($year_start, 6, false); } if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + $date_start = dol_get_first_day($year_start, 7, false); + $date_end = dol_get_last_day($year_start, 9, false); } if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + $date_start = dol_get_first_day($year_start, 10, false); + $date_end = dol_get_last_day($year_start, 12, false); } } diff --git a/htdocs/compta/stats/supplier_turnover.php b/htdocs/compta/stats/supplier_turnover.php index a6adf2a2440..b199dcbeb9c 100644 --- a/htdocs/compta/stats/supplier_turnover.php +++ b/htdocs/compta/stats/supplier_turnover.php @@ -69,19 +69,24 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e } else { $month_end = $month_start; } - $date_start = dol_get_first_day($year_start, $month_start, false); $date_end = dol_get_last_day($year_end, $month_end, false); + $date_start = dol_get_first_day($year_start, $month_start, false); + $date_end = dol_get_last_day($year_end, $month_end, false); } if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + $date_start = dol_get_first_day($year_start, 1, false); + $date_end = dol_get_last_day($year_start, 3, false); } if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + $date_start = dol_get_first_day($year_start, 4, false); + $date_end = dol_get_last_day($year_start, 6, false); } if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + $date_start = dol_get_first_day($year_start, 7, false); + $date_end = dol_get_last_day($year_start, 9, false); } if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + $date_start = dol_get_first_day($year_start, 10, false); + $date_end = dol_get_last_day($year_start, 12, false); } } diff --git a/htdocs/compta/stats/supplier_turnover_by_prodserv.php b/htdocs/compta/stats/supplier_turnover_by_prodserv.php index 553bd62899e..bdf4e5e0f85 100644 --- a/htdocs/compta/stats/supplier_turnover_by_prodserv.php +++ b/htdocs/compta/stats/supplier_turnover_by_prodserv.php @@ -114,19 +114,24 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $year_end++; } } - $date_start = dol_get_first_day($year_start, $month_start, false); $date_end = dol_get_last_day($year_end, $month_end, false); + $date_start = dol_get_first_day($year_start, $month_start, false); + $date_end = dol_get_last_day($year_end, $month_end, false); } else { if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + $date_start = dol_get_first_day($year_start, 1, false); + $date_end = dol_get_last_day($year_start, 3, false); } if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + $date_start = dol_get_first_day($year_start, 4, false); + $date_end = dol_get_last_day($year_start, 6, false); } if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + $date_start = dol_get_first_day($year_start, 7, false); + $date_end = dol_get_last_day($year_start, 9, false); } if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + $date_start = dol_get_first_day($year_start, 10, false); + $date_end = dol_get_last_day($year_start, 12, false); } } } else { diff --git a/htdocs/compta/stats/supplier_turnover_by_thirdparty.php b/htdocs/compta/stats/supplier_turnover_by_thirdparty.php index 0e653d542f6..fbfb0994e4a 100644 --- a/htdocs/compta/stats/supplier_turnover_by_thirdparty.php +++ b/htdocs/compta/stats/supplier_turnover_by_thirdparty.php @@ -114,19 +114,24 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $year_end++; } } - $date_start = dol_get_first_day($year_start, $month_start, false); $date_end = dol_get_last_day($year_end, $month_end, false); + $date_start = dol_get_first_day($year_start, $month_start, false); + $date_end = dol_get_last_day($year_end, $month_end, false); } if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + $date_start = dol_get_first_day($year_start, 1, false); + $date_end = dol_get_last_day($year_start, 3, false); } if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + $date_start = dol_get_first_day($year_start, 4, false); + $date_end = dol_get_last_day($year_start, 6, false); } if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + $date_start = dol_get_first_day($year_start, 7, false); + $date_end = dol_get_last_day($year_start, 9, false); } if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + $date_start = dol_get_first_day($year_start, 10, false); + $date_end = dol_get_last_day($year_start, 12, false); } } else { // TODO We define q diff --git a/htdocs/compta/tva/card.php b/htdocs/compta/tva/card.php old mode 100644 new mode 100755 index 87805ebf947..40261cb7f05 --- a/htdocs/compta/tva/card.php +++ b/htdocs/compta/tva/card.php @@ -549,7 +549,7 @@ if ($id) { print ''; if ($action == 'edit') { - print '
'; + print ''; } else { print ''; } @@ -630,7 +630,8 @@ if ($id) { $totalpaye = 0; $num = $db->num_rows($resql); - $i = 0; $total = 0; + $i = 0; + $total = 0; print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table print '
' . $langs->trans("Amount") . '
' . $langs->trans("Amount") . '
' . $langs->trans("Amount") . '' . price($object->amount) . '
'; diff --git a/htdocs/compta/tva/class/paymentvat.class.php b/htdocs/compta/tva/class/paymentvat.class.php index ff1c8b46040..9ba1bd2ed1d 100644 --- a/htdocs/compta/tva/class/paymentvat.class.php +++ b/htdocs/compta/tva/class/paymentvat.class.php @@ -261,7 +261,7 @@ class PaymentVAT extends CommonObject $sql .= ' b.fk_account'; $sql .= " FROM ".MAIN_DB_PREFIX."payment_vat as t LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepaiement = pt.id"; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; - $sql .= " WHERE t.rowid = ".$id; + $sql .= " WHERE t.rowid = ".((int) $id); // TODO link on entity of tax; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); @@ -365,14 +365,15 @@ class PaymentVAT extends CommonObject $sql .= " fk_user_modif=".(isset($this->fk_user_modif) ? $this->fk_user_modif : "null").""; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } // Commit or rollback @@ -418,12 +419,13 @@ class PaymentVAT extends CommonObject if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_vat"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } } diff --git a/htdocs/compta/tva/class/tva.class.php b/htdocs/compta/tva/class/tva.class.php index 44c8a84ac53..25d622d825d 100644 --- a/htdocs/compta/tva/class/tva.class.php +++ b/htdocs/compta/tva/class/tva.class.php @@ -209,7 +209,7 @@ class Tva extends CommonObject $sql .= " note='".$this->db->escape($this->note)."',"; $sql .= " fk_user_creat=".$this->fk_user_creat.","; $sql .= " fk_user_modif=".($this->fk_user_modif > 0 ? $this->fk_user_modif : $user->id).""; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); @@ -305,7 +305,7 @@ class Tva extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."tva as t"; //$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON t.fk_bank = b.rowid"; - $sql .= " WHERE t.rowid = ".$id; + $sql .= " WHERE t.rowid = ".((int) $id); dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); @@ -360,7 +360,7 @@ class Tva extends CommonObject // End call triggers $sql = "DELETE FROM ".MAIN_DB_PREFIX."tva"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); diff --git a/htdocs/compta/tva/clients.php b/htdocs/compta/tva/clients.php index e0801ba1db2..7ec5ad5b4f1 100644 --- a/htdocs/compta/tva/clients.php +++ b/htdocs/compta/tva/clients.php @@ -66,7 +66,8 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $q = GETPOST("q", "int"); if (empty($q)) { if (GETPOST("month", 'int')) { - $date_start = dol_get_first_day($year_start, GETPOST("month", 'int'), false); $date_end = dol_get_last_day($year_start, GETPOST("month", 'int'), false); + $date_start = dol_get_first_day($year_start, GETPOST("month", 'int'), false); + $date_end = dol_get_last_day($year_start, GETPOST("month", 'int'), false); } else { if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) { // quaterly vat, we take last past complete quarter $date_start = dol_time_plus_duree(dol_get_first_day($year_start, $current_date['mon'], false), -3 - (($current_date['mon'] - $conf->global->SOCIETE_FISCAL_MONTH_START) % 3), 'm'); @@ -90,16 +91,20 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e } } else { if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + $date_start = dol_get_first_day($year_start, 1, false); + $date_end = dol_get_last_day($year_start, 3, false); } if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + $date_start = dol_get_first_day($year_start, 4, false); + $date_end = dol_get_last_day($year_start, 6, false); } if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + $date_start = dol_get_first_day($year_start, 7, false); + $date_end = dol_get_last_day($year_start, 9, false); } if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + $date_start = dol_get_first_day($year_start, 10, false); + $date_end = dol_get_last_day($year_start, 12, false); } } } diff --git a/htdocs/compta/tva/index.php b/htdocs/compta/tva/index.php index c831d5fe61c..ba2669077c9 100644 --- a/htdocs/compta/tva/index.php +++ b/htdocs/compta/tva/index.php @@ -4,8 +4,9 @@ * Copyright (C) 2004-2018 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2014 Ferran Marcet - * Copyright (C) 2018 Frédéric France - * Copyright (C) 2021 Gauthier VERDOL + * Copyright (C) 2018 Frédéric France + * Copyright (C) 2021 Gauthier VERDOL + * Copyright (C) 2021 Open-Dsi * * 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 @@ -43,56 +44,89 @@ if (empty($conf->global->SOCIETE_FISCAL_MONTH_START)) { $conf->global->SOCIETE_FISCAL_MONTH_START = 1; } -// Date range -$year = GETPOST("year", "int"); -if (empty($year)) { - $year_current = $current_date['year']; - $year_start = $year_current; -} else { - $year_current = $year; - $year_start = $year; -} -$date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear")); -$date_end = dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear")); -// Set default period if not defined -if (empty($date_start) || empty($date_end)) { // We define date_start and date_end - $q = GETPOST("q", "int"); - if (empty($q)) { - if (GETPOST("month", "int")) { - $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); +$refresh = GETPOSTISSET('submit') ? true : false; + +if ($refresh === false) { + $year_current = dol_print_date('%Y', $now); + $month_current = dol_print_date('%m', $now); + + // 1 : Monthly (by default) + // 2 : Quarterly + // 3 : Annual + if ($conf->global->MAIN_INFO_VAT_RETURN == 2) { + // quarterly + $year = $year_current; + if ($month_current >= 7 && $month_current <= 9) { + $month_start = 4; + $month_end = 6; + } elseif ($month_current >= 10 && $month_current <= 12) { + $month_start = 7; + $month_end = 9; + } elseif ($month_current >= 1 && $month_current <= 3) { + $month_start = 10; + $month_end = 12; + $year--; } else { - if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) { // quaterly vat, we take last past complete quarter - $date_start = dol_time_plus_duree(dol_get_first_day($year_start, $current_date['mon'], false), -3 - (($current_date['mon'] - $conf->global->SOCIETE_FISCAL_MONTH_START) % 3), 'm'); - $date_end = dol_time_plus_duree($date_start, 3, 'm') - 1; - } elseif ($conf->global->MAIN_INFO_VAT_RETURN == 3) { // yearly vat - if ($current_date['mon'] < $conf->global->SOCIETE_FISCAL_MONTH_START) { - if (($conf->global->SOCIETE_FISCAL_MONTH_START - $current_date['mon']) > 6) { // If period started from less than 6 years, we show past year - $year_start--; - } - } else { - if (($current_date['mon'] - $conf->global->SOCIETE_FISCAL_MONTH_START) < 6) { // If perdio started from less than 6 years, we show past year - $year_start--; - } - } + $month_start = 1; + $month_end = 3; + } + $date_start = dol_get_first_day($year, $month_start); + $date_end = dol_get_last_day($year, $month_end); + } elseif ($conf->global->MAIN_INFO_VAT_RETURN == 3) { + // annual + $date_start = dol_get_first_day($year_current, 1); + $date_end = dol_get_last_day($year_current, 12); + } else { + // monthly by default + $year = $year_current; + $month_last = $month_current - 1; + if ($month_last <= 0) { + $month_last = $month_last + 12; + $year--; + } + $date_start = dol_get_first_day($year, $month_last); + $date_end = dol_get_last_day($year, $month_last); + } +} else { + // Date range + $year = GETPOST("year", "int"); + if (empty($year)) { + $year_current = dol_print_date(dol_now(), "%Y"); + if ($conf->global->SOCIETE_FISCAL_MONTH_START > dol_print_date(dol_now(), "%m")) $year_current--; + $year_start = $year_current; + } else { + $year_current = $year; + $year_start = $year; + } + $date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear")); + $date_end = dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear")); + if (empty($date_start) || empty($date_end)) {// We define date_start and date_end + $q = GETPOST("q", "int"); + if (empty($q)) { + if (GETPOST("month", "int")) { + $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); + $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); + } else { $date_start = dol_get_first_day($year_start, $conf->global->SOCIETE_FISCAL_MONTH_START, false); $date_end = dol_time_plus_duree($date_start, 1, 'y') - 1; - } elseif ($conf->global->MAIN_INFO_VAT_RETURN == 1) { // monthly vat, we take last past complete month - $date_start = dol_time_plus_duree(dol_get_first_day($year_start, $current_date['mon'], false), -1, 'm'); - $date_end = dol_time_plus_duree($date_start, 1, 'm') - 1; } - } - } else { - if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); - } - if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); - } - if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); - } - if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + } else { + if ($q == 1) { + $date_start = dol_get_first_day($year_start, 1, false); + $date_end = dol_get_last_day($year_start, 3, false); + } + if ($q == 2) { + $date_start = dol_get_first_day($year_start, 4, false); + $date_end = dol_get_last_day($year_start, 6, false); + } + if ($q == 3) { + $date_start = dol_get_first_day($year_start, 7, false); + $date_end = dol_get_last_day($year_start, 9, false); + } + if ($q == 4) { + $date_start = dol_get_first_day($year_start, 10, false); + $date_end = dol_get_last_day($year_start, 12, false); + } } } } @@ -281,312 +315,319 @@ report_header($name, '', $period, $periodlink, $description, $builddate, $export print '
'; -print '
'; +if ($refresh === true) { + print '
'; -print load_fiche_titre($langs->trans("VATSummary"), '', ''); + print load_fiche_titre($langs->trans("VATSummary"), '', ''); -print '
'; -print ''; -print ''; -print ''; -print ''; -print ''; -print ''."\n"; -print ''."\n"; + print '
'.$langs->trans("Year")." ".$y.''.$langs->trans("VATToPay").''.$langs->trans("VATToCollect").''.$langs->trans("Balance").' 
'; + print ''; + print ''; + print ''; + print ''; + print ''; + print '' . "\n"; + print '' . "\n"; -$tmp = dol_getdate($date_start); -$y = $tmp['year']; -$m = $tmp['mon']; -$tmp = dol_getdate($date_end); -$yend = $tmp['year']; -$mend = $tmp['mon']; -//var_dump($m); -$total = 0; $subtotalcoll = 0; $subtotalpaye = 0; $subtotal = 0; -$i = 0; $mcursor = 0; + $tmp = dol_getdate($date_start); + $y = $tmp['year']; + $m = $tmp['mon']; + $tmp = dol_getdate($date_end); + $yend = $tmp['year']; + $mend = $tmp['mon']; + //var_dump($m); + $total = 0; + $subtotalcoll = 0; + $subtotalpaye = 0; + $subtotal = 0; + $i = 0; + $mcursor = 0; -while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) { // $mcursor is to avoid too large loop - //$m = $conf->global->SOCIETE_FISCAL_MONTH_START + ($mcursor % 12); - if ($m == 13) { - $y++; - } - if ($m > 12) { - $m -= 12; - } - $mcursor++; - - $x_coll = tax_by_rate('vat', $db, $y, 0, 0, 0, $modetax, 'sell', $m); - $x_paye = tax_by_rate('vat', $db, $y, 0, 0, 0, $modetax, 'buy', $m); - - $x_both = array(); - //now, from these two arrays, get another array with one rate per line - foreach (array_keys($x_coll) as $my_coll_rate) { - $x_both[$my_coll_rate]['coll']['totalht'] = $x_coll[$my_coll_rate]['totalht']; - $x_both[$my_coll_rate]['coll']['vat'] = $x_coll[$my_coll_rate]['vat']; - $x_both[$my_coll_rate]['paye']['totalht'] = 0; - $x_both[$my_coll_rate]['paye']['vat'] = 0; - $x_both[$my_coll_rate]['coll']['links'] = ''; - $x_both[$my_coll_rate]['coll']['detail'] = array(); - foreach ($x_coll[$my_coll_rate]['facid'] as $id => $dummy) { - //$invoice_customer->id=$x_coll[$my_coll_rate]['facid'][$id]; - //$invoice_customer->ref=$x_coll[$my_coll_rate]['facnum'][$id]; - //$invoice_customer->type=$x_coll[$my_coll_rate]['type'][$id]; - //$company_static->fetch($x_coll[$my_coll_rate]['company_id'][$id]); - $x_both[$my_coll_rate]['coll']['detail'][] = array( - 'id' =>$x_coll[$my_coll_rate]['facid'][$id], - 'descr' =>$x_coll[$my_coll_rate]['descr'][$id], - 'pid' =>$x_coll[$my_coll_rate]['pid'][$id], - 'pref' =>$x_coll[$my_coll_rate]['pref'][$id], - 'ptype' =>$x_coll[$my_coll_rate]['ptype'][$id], - 'payment_id'=>$x_coll[$my_coll_rate]['payment_id'][$id], - 'payment_amount'=>$x_coll[$my_coll_rate]['payment_amount'][$id], - 'ftotal_ttc'=>$x_coll[$my_coll_rate]['ftotal_ttc'][$id], - 'dtotal_ttc'=>$x_coll[$my_coll_rate]['dtotal_ttc'][$id], - 'dtype' =>$x_coll[$my_coll_rate]['dtype'][$id], - 'datef' =>$x_coll[$my_coll_rate]['datef'][$id], - 'datep' =>$x_coll[$my_coll_rate]['datep'][$id], - //'company_link'=>$company_static->getNomUrl(1,'',20), - 'ddate_start'=>$x_coll[$my_coll_rate]['ddate_start'][$id], - 'ddate_end' =>$x_coll[$my_coll_rate]['ddate_end'][$id], - 'totalht' =>$x_coll[$my_coll_rate]['totalht_list'][$id], - 'vat' =>$x_coll[$my_coll_rate]['vat_list'][$id], - //'link' =>$invoice_customer->getNomUrl(1,'',12) - ); + while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) { // $mcursor is to avoid too large loop + //$m = $conf->global->SOCIETE_FISCAL_MONTH_START + ($mcursor % 12); + if ($m == 13) { + $y++; } - } - - // tva paid - foreach (array_keys($x_paye) as $my_paye_rate) { - $x_both[$my_paye_rate]['paye']['totalht'] = $x_paye[$my_paye_rate]['totalht']; - $x_both[$my_paye_rate]['paye']['vat'] = $x_paye[$my_paye_rate]['vat']; - if (!isset($x_both[$my_paye_rate]['coll']['totalht'])) { - $x_both[$my_paye_rate]['coll']['totalht'] = 0; - $x_both[$my_paye_rate]['coll']['vat'] = 0; + if ($m > 12) { + $m -= 12; } - $x_both[$my_paye_rate]['paye']['links'] = ''; - $x_both[$my_paye_rate]['paye']['detail'] = array(); + $mcursor++; - foreach ($x_paye[$my_paye_rate]['facid'] as $id => $dummy) { - // ExpenseReport - if ($x_paye[$my_paye_rate]['ptype'][$id] == 'ExpenseReportPayment') { - //$expensereport->id=$x_paye[$my_paye_rate]['facid'][$id]; - //$expensereport->ref=$x_paye[$my_paye_rate]['facnum'][$id]; - //$expensereport->type=$x_paye[$my_paye_rate]['type'][$id]; + $x_coll = tax_by_rate('vat', $db, $y, 0, 0, 0, $modetax, 'sell', $m); + $x_paye = tax_by_rate('vat', $db, $y, 0, 0, 0, $modetax, 'buy', $m); - $x_both[$my_paye_rate]['paye']['detail'][] = array( - 'id' =>$x_paye[$my_paye_rate]['facid'][$id], - 'descr' =>$x_paye[$my_paye_rate]['descr'][$id], - 'pid' =>$x_paye[$my_paye_rate]['pid'][$id], - 'pref' =>$x_paye[$my_paye_rate]['pref'][$id], - 'ptype' =>$x_paye[$my_paye_rate]['ptype'][$id], - 'payment_id' =>$x_paye[$my_paye_rate]['payment_id'][$id], - 'payment_amount' =>$x_paye[$my_paye_rate]['payment_amount'][$id], - 'ftotal_ttc' =>price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]), - 'dtotal_ttc' =>price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]), - 'dtype' =>$x_paye[$my_paye_rate]['dtype'][$id], - 'ddate_start' =>$x_paye[$my_paye_rate]['ddate_start'][$id], - 'ddate_end' =>$x_paye[$my_paye_rate]['ddate_end'][$id], - 'totalht' =>price2num($x_paye[$my_paye_rate]['totalht_list'][$id]), - 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id], - //'link' =>$expensereport->getNomUrl(1) - ); - } else { - //$invoice_supplier->id=$x_paye[$my_paye_rate]['facid'][$id]; - //$invoice_supplier->ref=$x_paye[$my_paye_rate]['facnum'][$id]; - //$invoice_supplier->type=$x_paye[$my_paye_rate]['type'][$id]; - //$company_static->fetch($x_paye[$my_paye_rate]['company_id'][$id]); - $x_both[$my_paye_rate]['paye']['detail'][] = array( - 'id' =>$x_paye[$my_paye_rate]['facid'][$id], - 'descr' =>$x_paye[$my_paye_rate]['descr'][$id], - 'pid' =>$x_paye[$my_paye_rate]['pid'][$id], - 'pref' =>$x_paye[$my_paye_rate]['pref'][$id], - 'ptype' =>$x_paye[$my_paye_rate]['ptype'][$id], - 'payment_id'=>$x_paye[$my_paye_rate]['payment_id'][$id], - 'payment_amount'=>$x_paye[$my_paye_rate]['payment_amount'][$id], - 'ftotal_ttc'=>price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]), - 'dtotal_ttc'=>price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]), - 'dtype' =>$x_paye[$my_paye_rate]['dtype'][$id], - 'datef' =>$x_paye[$my_paye_rate]['datef'][$id], - 'datep' =>$x_paye[$my_paye_rate]['datep'][$id], - //'company_link'=>$company_static->getNomUrl(1,'',20), - 'ddate_start'=>$x_paye[$my_paye_rate]['ddate_start'][$id], - 'ddate_end' =>$x_paye[$my_paye_rate]['ddate_end'][$id], - 'totalht' =>price2num($x_paye[$my_paye_rate]['totalht_list'][$id]), - 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id], - //'link' =>$invoice_supplier->getNomUrl(1,'',12) + $x_both = array(); + //now, from these two arrays, get another array with one rate per line + foreach (array_keys($x_coll) as $my_coll_rate) { + $x_both[$my_coll_rate]['coll']['totalht'] = $x_coll[$my_coll_rate]['totalht']; + $x_both[$my_coll_rate]['coll']['vat'] = $x_coll[$my_coll_rate]['vat']; + $x_both[$my_coll_rate]['paye']['totalht'] = 0; + $x_both[$my_coll_rate]['paye']['vat'] = 0; + $x_both[$my_coll_rate]['coll']['links'] = ''; + $x_both[$my_coll_rate]['coll']['detail'] = array(); + foreach ($x_coll[$my_coll_rate]['facid'] as $id => $dummy) { + //$invoice_customer->id=$x_coll[$my_coll_rate]['facid'][$id]; + //$invoice_customer->ref=$x_coll[$my_coll_rate]['facnum'][$id]; + //$invoice_customer->type=$x_coll[$my_coll_rate]['type'][$id]; + //$company_static->fetch($x_coll[$my_coll_rate]['company_id'][$id]); + $x_both[$my_coll_rate]['coll']['detail'][] = array( + 'id' => $x_coll[$my_coll_rate]['facid'][$id], + 'descr' => $x_coll[$my_coll_rate]['descr'][$id], + 'pid' => $x_coll[$my_coll_rate]['pid'][$id], + 'pref' => $x_coll[$my_coll_rate]['pref'][$id], + 'ptype' => $x_coll[$my_coll_rate]['ptype'][$id], + 'payment_id' => $x_coll[$my_coll_rate]['payment_id'][$id], + 'payment_amount' => $x_coll[$my_coll_rate]['payment_amount'][$id], + 'ftotal_ttc' => $x_coll[$my_coll_rate]['ftotal_ttc'][$id], + 'dtotal_ttc' => $x_coll[$my_coll_rate]['dtotal_ttc'][$id], + 'dtype' => $x_coll[$my_coll_rate]['dtype'][$id], + 'datef' => $x_coll[$my_coll_rate]['datef'][$id], + 'datep' => $x_coll[$my_coll_rate]['datep'][$id], + //'company_link'=>$company_static->getNomUrl(1,'',20), + 'ddate_start' => $x_coll[$my_coll_rate]['ddate_start'][$id], + 'ddate_end' => $x_coll[$my_coll_rate]['ddate_end'][$id], + 'totalht' => $x_coll[$my_coll_rate]['totalht_list'][$id], + 'vat' => $x_coll[$my_coll_rate]['vat_list'][$id], + //'link' =>$invoice_customer->getNomUrl(1,'',12) ); } } - } - //now we have an array (x_both) indexed by rates for coll and paye - $action = "tva"; - $object = array(&$x_coll, &$x_paye, &$x_both); - $parameters["mode"] = $modetax; - $parameters["year"] = $y; - $parameters["month"] = $m; - $parameters["type"] = 'vat'; + // tva paid + foreach (array_keys($x_paye) as $my_paye_rate) { + $x_both[$my_paye_rate]['paye']['totalht'] = $x_paye[$my_paye_rate]['totalht']; + $x_both[$my_paye_rate]['paye']['vat'] = $x_paye[$my_paye_rate]['vat']; + if (!isset($x_both[$my_paye_rate]['coll']['totalht'])) { + $x_both[$my_paye_rate]['coll']['totalht'] = 0; + $x_both[$my_paye_rate]['coll']['vat'] = 0; + } + $x_both[$my_paye_rate]['paye']['links'] = ''; + $x_both[$my_paye_rate]['paye']['detail'] = array(); - // Initialize technical object to manage hooks of expenses. Note that conf->hooks_modules contains array array - $hookmanager->initHooks(array('externalbalance')); - $reshook = $hookmanager->executeHooks('addVatLine', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + foreach ($x_paye[$my_paye_rate]['facid'] as $id => $dummy) { + // ExpenseReport + if ($x_paye[$my_paye_rate]['ptype'][$id] == 'ExpenseReportPayment') { + //$expensereport->id=$x_paye[$my_paye_rate]['facid'][$id]; + //$expensereport->ref=$x_paye[$my_paye_rate]['facnum'][$id]; + //$expensereport->type=$x_paye[$my_paye_rate]['type'][$id]; - if (!is_array($x_coll) && $coll_listbuy == -1) { - $langs->load("errors"); - print ''; - break; - } - if (!is_array($x_paye) && $coll_listbuy == -2) { - print ''; - break; - } - - - print ''; - print ''; - - $x_coll_sum = 0; - foreach (array_keys($x_coll) as $rate) { - $subtot_coll_total_ht = 0; - $subtot_coll_vat = 0; - - foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) { - // Payment - $ratiopaymentinvoice = 1; - if ($modetax != 1) { - // Define type - // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. - $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); - // Try to enhance type detection using date_start and date_end for free lines where type - // was not saved. - if (!empty($fields['ddate_start'])) { - $type = 1; - } - if (!empty($fields['ddate_end'])) { - $type = 1; - } - - if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') - || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) { - //print $langs->trans("NA"); + $x_both[$my_paye_rate]['paye']['detail'][] = array( + 'id' => $x_paye[$my_paye_rate]['facid'][$id], + 'descr' => $x_paye[$my_paye_rate]['descr'][$id], + 'pid' => $x_paye[$my_paye_rate]['pid'][$id], + 'pref' => $x_paye[$my_paye_rate]['pref'][$id], + 'ptype' => $x_paye[$my_paye_rate]['ptype'][$id], + 'payment_id' => $x_paye[$my_paye_rate]['payment_id'][$id], + 'payment_amount' => $x_paye[$my_paye_rate]['payment_amount'][$id], + 'ftotal_ttc' => price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]), + 'dtotal_ttc' => price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]), + 'dtype' => $x_paye[$my_paye_rate]['dtype'][$id], + 'ddate_start' => $x_paye[$my_paye_rate]['ddate_start'][$id], + 'ddate_end' => $x_paye[$my_paye_rate]['ddate_end'][$id], + 'totalht' => price2num($x_paye[$my_paye_rate]['totalht_list'][$id]), + 'vat' => $x_paye[$my_paye_rate]['vat_list'][$id], + //'link' =>$expensereport->getNomUrl(1) + ); } else { - if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { - $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); - } + //$invoice_supplier->id=$x_paye[$my_paye_rate]['facid'][$id]; + //$invoice_supplier->ref=$x_paye[$my_paye_rate]['facnum'][$id]; + //$invoice_supplier->type=$x_paye[$my_paye_rate]['type'][$id]; + //$company_static->fetch($x_paye[$my_paye_rate]['company_id'][$id]); + $x_both[$my_paye_rate]['paye']['detail'][] = array( + 'id' => $x_paye[$my_paye_rate]['facid'][$id], + 'descr' => $x_paye[$my_paye_rate]['descr'][$id], + 'pid' => $x_paye[$my_paye_rate]['pid'][$id], + 'pref' => $x_paye[$my_paye_rate]['pref'][$id], + 'ptype' => $x_paye[$my_paye_rate]['ptype'][$id], + 'payment_id' => $x_paye[$my_paye_rate]['payment_id'][$id], + 'payment_amount' => $x_paye[$my_paye_rate]['payment_amount'][$id], + 'ftotal_ttc' => price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]), + 'dtotal_ttc' => price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]), + 'dtype' => $x_paye[$my_paye_rate]['dtype'][$id], + 'datef' => $x_paye[$my_paye_rate]['datef'][$id], + 'datep' => $x_paye[$my_paye_rate]['datep'][$id], + //'company_link'=>$company_static->getNomUrl(1,'',20), + 'ddate_start' => $x_paye[$my_paye_rate]['ddate_start'][$id], + 'ddate_end' => $x_paye[$my_paye_rate]['ddate_end'][$id], + 'totalht' => price2num($x_paye[$my_paye_rate]['totalht_list'][$id]), + 'vat' => $x_paye[$my_paye_rate]['vat_list'][$id], + //'link' =>$invoice_supplier->getNomUrl(1,'',12) + ); } } - //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice); - $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; - $temp_vat = $fields['vat'] * $ratiopaymentinvoice; - $subtot_coll_total_ht += $temp_ht; - $subtot_coll_vat += $temp_vat; - $x_coll_sum += $temp_vat; } - } - print ''; + //now we have an array (x_both) indexed by rates for coll and paye - $x_paye_sum = 0; - foreach (array_keys($x_paye) as $rate) { - $subtot_paye_total_ht = 0; - $subtot_paye_vat = 0; + $action = "tva"; + $object = array(&$x_coll, &$x_paye, &$x_both); + $parameters["mode"] = $modetax; + $parameters["year"] = $y; + $parameters["month"] = $m; + $parameters["type"] = 'vat'; - foreach ($x_both[$rate]['paye']['detail'] as $index => $fields) { - // Payment - $ratiopaymentinvoice = 1; - if ($modetax != 1) { - // Define type - // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. - $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); - // Try to enhance type detection using date_start and date_end for free lines where type - // was not saved. - if (!empty($fields['ddate_start'])) { - $type = 1; - } - if (!empty($fields['ddate_end'])) { - $type = 1; - } + // Initialize technical object to manage hooks of expenses. Note that conf->hooks_modules contains array array + $hookmanager->initHooks(array('externalbalance')); + $reshook = $hookmanager->executeHooks('addVatLine', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') - || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) { - //print $langs->trans("NA"); - } else { - if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { - $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); + if (!is_array($x_coll) && $coll_listbuy == -1) { + $langs->load("errors"); + print ''; + break; + } + if (!is_array($x_paye) && $coll_listbuy == -2) { + print ''; + break; + } + + + print ''; + print ''; + + $x_coll_sum = 0; + foreach (array_keys($x_coll) as $rate) { + $subtot_coll_total_ht = 0; + $subtot_coll_vat = 0; + + foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) { + // Payment + $ratiopaymentinvoice = 1; + if ($modetax != 1) { + // Define type + // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. + $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (!empty($fields['ddate_start'])) { + $type = 1; + } + if (!empty($fields['ddate_end'])) { + $type = 1; + } + + if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) { + //print $langs->trans("NA"); + } else { + if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { + $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); + } } } + //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice); + $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; + $temp_vat = $fields['vat'] * $ratiopaymentinvoice; + $subtot_coll_total_ht += $temp_ht; + $subtot_coll_vat += $temp_vat; + $x_coll_sum += $temp_vat; } - //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice); - $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; - $temp_vat = $fields['vat'] * $ratiopaymentinvoice; - $subtot_paye_total_ht += $temp_ht; - $subtot_paye_vat += $temp_vat; - $x_paye_sum += $temp_vat; + } + print ''; + + $x_paye_sum = 0; + foreach (array_keys($x_paye) as $rate) { + $subtot_paye_total_ht = 0; + $subtot_paye_vat = 0; + + foreach ($x_both[$rate]['paye']['detail'] as $index => $fields) { + // Payment + $ratiopaymentinvoice = 1; + if ($modetax != 1) { + // Define type + // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. + $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (!empty($fields['ddate_start'])) { + $type = 1; + } + if (!empty($fields['ddate_end'])) { + $type = 1; + } + + if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) { + //print $langs->trans("NA"); + } else { + if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { + $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); + } + } + } + //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice); + $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; + $temp_vat = $fields['vat'] * $ratiopaymentinvoice; + $subtot_paye_total_ht += $temp_ht; + $subtot_paye_vat += $temp_vat; + $x_paye_sum += $temp_vat; + } + } + print ''; + + $subtotalcoll = $subtotalcoll + $x_coll_sum; + $subtotalpaye = $subtotalpaye + $x_paye_sum; + + $diff = $x_coll_sum - $x_paye_sum; + $total = $total + $diff; + $subtotal = price2num($subtotal + $diff, 'MT'); + + print '' . "\n"; + print "\n"; + print "\n"; + + $i++; + $m++; + if ($i > 2) { + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i = 0; + $subtotalcoll = 0; + $subtotalpaye = 0; + $subtotal = 0; } } - print ''; - - $subtotalcoll = $subtotalcoll + $x_coll_sum; - $subtotalpaye = $subtotalpaye + $x_paye_sum; - - $diff = $x_coll_sum - $x_paye_sum; - $total = $total + $diff; - $subtotal = price2num($subtotal + $diff, 'MT'); - - print ''."\n"; + print ''; print "\n"; - print "\n"; + print ''; - $i++; $m++; - if ($i > 2) { - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - $i = 0; - $subtotalcoll = 0; $subtotalpaye = 0; $subtotal = 0; - } + print '
' . $langs->trans("Year") . " " . $y . '' . $langs->trans("VATToPay") . '' . $langs->trans("VATToCollect") . '' . $langs->trans("Balance") . ' 
'.$langs->trans("ErrorNoAccountancyModuleLoaded").'
'.$langs->trans("FeatureNotYetAvailable").'
'.dol_print_date(dol_mktime(0, 0, 0, $m, 1, $y), "%b %Y").''.price(price2num($x_coll_sum, 'MT')).'
' . $langs->trans("ErrorNoAccountancyModuleLoaded") . '
' . $langs->trans("FeatureNotYetAvailable") . '
' . dol_print_date(dol_mktime(0, 0, 0, $m, 1, $y), "%b %Y") . '' . price(price2num($x_coll_sum, 'MT')) . '' . price(price2num($x_paye_sum, 'MT')) . '' . price(price2num($diff, 'MT')) . ' 
' . $langs->trans("SubTotal") . ':' . price(price2num($subtotalcoll, 'MT')) . '' . price(price2num($subtotalpaye, 'MT')) . '' . price(price2num($subtotal, 'MT')) . ' 
'.price(price2num($x_paye_sum, 'MT')).''.price(price2num($diff, 'MT')).'
' . $langs->trans("TotalToPay") . ':' . price(price2num($total, 'MT')) . ' 
'.$langs->trans("SubTotal").':'.price(price2num($subtotalcoll, 'MT')).''.price(price2num($subtotalpaye, 'MT')).''.price(price2num($subtotal, 'MT')).' 
'; + + + print '
'; + + + /* + * Paid + */ + print load_fiche_titre($langs->trans("VATPaid"), '', ''); + + $sql = ''; + + $sql .= "SELECT SUM(amount) as mm, date_format(tva.datev,'%Y-%m') as dm, 'claimed' as mode"; + $sql .= " FROM " . MAIN_DB_PREFIX . "tva as tva"; + $sql .= " WHERE tva.entity = " . $conf->entity; + $sql .= " AND (tva.datev >= '" . $db->idate($date_start) . "' AND tva.datev <= '" . $db->idate($date_end) . "')"; + $sql .= " GROUP BY dm"; + + $sql .= " UNION "; + + $sql .= "SELECT SUM(ptva.amount) as mm, date_format(tva.datev,'%Y-%m') as dm, 'paid' as mode"; + $sql .= " FROM " . MAIN_DB_PREFIX . "tva as tva"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "payment_vat as ptva ON (tva.rowid = ptva.fk_tva)"; + $sql .= " WHERE tva.entity = " . $conf->entity; + $sql .= " AND (tva.datev >= '" . $db->idate($date_start) . "' AND tva.datev <= '" . $db->idate($date_end) . "')"; + $sql .= " GROUP BY dm"; + + $sql .= " ORDER BY dm ASC, mode ASC"; + //print $sql; + + pt($db, $sql, $langs->trans("Month")); + + print '
'; } -print ''.$langs->trans("TotalToPay").':'.price(price2num($total, 'MT')).''; -print " \n"; -print ''; - -print ''; - - -print '
'; - - - -/* - * VAT Paid - */ - -print load_fiche_titre($langs->trans("VATPaid"), '', ''); - -$sql = ''; - -$sql .= "SELECT SUM(amount) as mm, date_format(tva.datev,'%Y-%m') as dm, 'claimed' as mode"; -$sql .= " FROM ".MAIN_DB_PREFIX."tva as tva"; -$sql .= " WHERE tva.entity = ".$conf->entity; -$sql .= " AND (tva.datev >= '".$db->idate($date_start)."' AND tva.datev <= '".$db->idate($date_end)."')"; -$sql .= " GROUP BY dm"; - -$sql .= " UNION "; - -$sql .= "SELECT SUM(ptva.amount) as mm, date_format(tva.datev,'%Y-%m') as dm, 'paid' as mode"; -$sql .= " FROM ".MAIN_DB_PREFIX."tva as tva"; -$sql .= " INNER JOIN ".MAIN_DB_PREFIX."payment_vat as ptva ON (tva.rowid = ptva.fk_tva)"; -$sql .= " WHERE tva.entity = ".$conf->entity; -$sql .= " AND (tva.datev >= '".$db->idate($date_start)."' AND tva.datev <= '".$db->idate($date_end)."')"; -$sql .= " GROUP BY dm"; - -$sql .= " ORDER BY dm ASC, mode ASC"; -//print $sql; - -pt($db, $sql, $langs->trans("Month")); - -print '
'; llxFooter(); $db->close(); diff --git a/htdocs/compta/tva/quadri_detail.php b/htdocs/compta/tva/quadri_detail.php index 04f90ba02f9..590999c7b31 100644 --- a/htdocs/compta/tva/quadri_detail.php +++ b/htdocs/compta/tva/quadri_detail.php @@ -4,8 +4,9 @@ * Copyright (C) 2004-2013 Laurent Destailleur * Copyright (C) 2006-2015 Yannick Warnier * Copyright (C) 2014 Ferran Marcet - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-2021 Frédéric France * Copyright (C) 2019 Eric Seigne + * Copyright (C) 2021 Open-Dsi * * 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 @@ -45,65 +46,68 @@ require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class. $langs->loadLangs(array("other", "compta", "banks", "bills", "companies", "product", "trips", "admin")); $now = dol_now(); -$current_date = dol_getdate($now); -if (empty($conf->global->SOCIETE_FISCAL_MONTH_START)) { - $conf->global->SOCIETE_FISCAL_MONTH_START = 1; -} - -// Date range -$year = GETPOST("year", "int"); -if (empty($year)) { - $year_current = $current_date['year']; - $year_start = $year_current; +$refresh = GETPOSTISSET('submit') ? true : false; +$invoice_type = GETPOSTISSET('invoice_type') ? GETPOST('invoice_type', 'alpha') : ''; +$vat_rate_show = GETPOSTISSET('vat_rate_show') ? GETPOST('vat_rate_show', 'int') : -1; +$year_current = GETPOSTISSET('year') ? GETPOST('year', 'int') : intval(strftime('%Y', $now)); +$year_start = $year_current; +$month_current = GETPOSTISSET('month') ? GETPOST('month', 'int') : intval(strftime('%m', $now)); +$month_start = $month_current; +if ($refresh === false) { + $date_start = dol_get_first_day($year_start, $month_start); + $date_end = dol_get_last_day($year_start, $month_start); } else { - $year_current = $year; - $year_start = $year; -} -$date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear")); -$date_end = dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear")); -// Set default period if not defined -if (empty($date_start) || empty($date_end)) { // We define date_start and date_end - $q = GETPOST("q", "int"); - if (empty($q)) { - if (GETPOST("month", "int")) { - $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); - } else { - if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) { // quaterly vat, we take last past complete quarter - $date_start = dol_time_plus_duree(dol_get_first_day($year_start, $current_date['mon'], false), -3 - (($current_date['mon'] - $conf->global->SOCIETE_FISCAL_MONTH_START) % 3), 'm'); - $date_end = dol_time_plus_duree($date_start, 3, 'm') - 1; - } elseif ($conf->global->MAIN_INFO_VAT_RETURN == 3) { // yearly vat - if ($current_date['mon'] < $conf->global->SOCIETE_FISCAL_MONTH_START) { - if (($conf->global->SOCIETE_FISCAL_MONTH_START - $current_date['mon']) > 6) { // If period started from less than 6 years, we show past year - $year_start--; - } - } else { - if (($current_date['mon'] - $conf->global->SOCIETE_FISCAL_MONTH_START) < 6) { // If perdio started from less than 6 years, we show past year - $year_start--; - } + // Date range + //$year=GETPOST("year", "int"); + //if (empty($year)) + //{ + // $year_current = strftime("%Y", dol_now()); + // $year_start = $year_current; + //} else { + // $year_current = $year; + // $year_start = $year; + //} + + $date_start=dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear")); + $date_end=dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear")); + // Quarter + if (empty($date_start) || empty($date_end)) { // We define date_start and date_end + $q=GETPOST("q", "int"); + if (empty($q)) { + if (GETPOST("month", "int")) { + $date_start=dol_get_first_day($year_start, GETPOST("month", "int"), false); + $date_end=dol_get_last_day($year_start, GETPOST("month", "int"), false); + } else { + $date_start=dol_get_first_day($year_start, empty($conf->global->SOCIETE_FISCAL_MONTH_START)?1:$conf->global->SOCIETE_FISCAL_MONTH_START, false); + if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) { + $date_end=dol_time_plus_duree($date_start, 3, 'm') - 1; + } elseif ($conf->global->MAIN_INFO_VAT_RETURN == 3) { + $date_end = dol_time_plus_duree($date_start, 1, 'y') - 1; + } elseif ($conf->global->MAIN_INFO_VAT_RETURN == 1) { + $date_end = dol_time_plus_duree($date_start, 1, 'm') - 1; } - $date_start = dol_get_first_day($year_start, $conf->global->SOCIETE_FISCAL_MONTH_START, false); - $date_end = dol_time_plus_duree($date_start, 1, 'y') - 1; - } elseif ($conf->global->MAIN_INFO_VAT_RETURN == 1) { // monthly vat, we take last past complete month - $date_start = dol_time_plus_duree(dol_get_first_day($year_start, $current_date['mon'], false), -1, 'm'); - $date_end = dol_time_plus_duree($date_start, 1, 'm') - 1; } - } - } else { - if ($q == 1) { - $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); - } - if ($q == 2) { - $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); - } - if ($q == 3) { - $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); - } - if ($q == 4) { - $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + } else { + if ($q == 1) { + $date_start=dol_get_first_day($year_start, 1, false); $date_end=dol_get_last_day($year_start, 3, false); + } + if ($q == 2) { + $date_start=dol_get_first_day($year_start, 4, false); $date_end=dol_get_last_day($year_start, 6, false); + } + if ($q == 3) { + $date_start=dol_get_first_day($year_start, 7, false); $date_end=dol_get_last_day($year_start, 9, false); + } + if ($q == 4) { + $date_start=dol_get_first_day($year_start, 10, false); $date_end=dol_get_last_day($year_start, 12, false); + } } } } +$month_start = strftime('%m', $date_start); +$year_start = strftime('%Y', $date_start); + + $min = price2num(GETPOST("min", "alpha")); if (empty($min)) { $min = 0; @@ -111,16 +115,16 @@ if (empty($min)) { // Define modetax (0 or 1) // 0=normal, 1=option vat for services is on debit, 2=option on payments for products -$modetax = $conf->global->TAX_MODE; +$modetax = (empty($conf->global->TAX_MODE) ? 0 : $conf->global->TAX_MODE); if (GETPOSTISSET("modetax")) { - $modetax = GETPOST("modetax", 'int'); + $modetax = GETPOSTINT("modetax"); } if (empty($modetax)) { $modetax = 0; } // Security check -$socid = GETPOST('socid', 'int'); +$socid = GETPOSTINT('socid'); if ($user->socid) { $socid = $user->socid; } @@ -179,7 +183,8 @@ if ($modetax == 2) { $calcmode .= ' ('.$langs->trans("TaxModuleSetupToModifyRules", DOL_URL_ROOT.'/admin/taxes.php').')'; // Set period $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); -$prevyear = $year_start; $prevquarter = $q; +$prevyear = $year_start; +$prevquarter = $q; if ($prevquarter > 1) { $prevquarter--; } else { @@ -236,7 +241,7 @@ if ($mysoc->tva_assuj) { $vatsup .= ' ('.$langs->trans("ToGetBack").')'; } -$optioncss = GETPOST('optioncss'); +$optioncss = GETPOST('optioncss', 'alpha'); if ($optioncss != "print") { report_header($name, '', $period, $periodlink, $description, $builddate, $exportlink, array(), $calcmode); } @@ -422,7 +427,10 @@ if (!is_array($x_coll) || !is_array($x_paye)) { if (is_array($x_both[$rate]['coll']['detail'])) { // VAT Rate print ""; - print ''.$langs->trans("Rate").': '.vatrate($rate).'%'; + print ''; + print $langs->trans('Rate') . ' : ' . vatrate($rate) . '%'; + print ' - ' . img_picto('', 'chevron-down', 'class="paddingrightonly"') . $langs->trans('VATReportShowByRateDetails') . ''; + print ''; print ''."\n"; foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) { @@ -438,112 +446,149 @@ if (!is_array($x_coll) || !is_array($x_paye)) { $type = 1; } - - print ''; - - // Ref - print ''.$fields['link'].''; - - // Invoice date - print ''.dol_print_date($fields['datef'], 'day').''; - - // Payment date - if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') { - print ''.dol_print_date($fields['datep'], 'day').''; - } else { - print ''; - } - - // Company name - print ''.$fields['company_link'].''; - - // Description - print ''; - if ($fields['pid']) { - $product_static->id = $fields['pid']; - $product_static->ref = $fields['pref']; - $product_static->type = $fields['dtype']; // We force with the type of line to have type how line is registered - print $product_static->getNomUrl(1); - if (dol_string_nohtmltag($fields['descr'])) { - print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']), 24); - } - } else { - if ($type) { - $text = img_object($langs->trans('Service'), 'service'); - } else { - $text = img_object($langs->trans('Product'), 'product'); - } - if (preg_match('/^\((.*)\)$/', $fields['descr'], $reg)) { - if ($reg[1] == 'DEPOSIT') { - $fields['descr'] = $langs->transnoentitiesnoconv('Deposit'); - } elseif ($reg[1] == 'CREDIT_NOTE') { - $fields['descr'] = $langs->transnoentitiesnoconv('CreditNote'); - } else { - $fields['descr'] = $langs->transnoentitiesnoconv($reg[1]); - } - } - print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']), 24); - - // Show range - print_date_range($fields['ddate_start'], $fields['ddate_end']); - } - print ''; - - // Total HT - if ($modetax != 1) { - print ''; - print price($fields['totalht']); - if (price2num($fields['ftotal_ttc'])) { - //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - "; - $ratiolineinvoice = ($fields['dtotal_ttc'] / $fields['ftotal_ttc']); - //print ' ('.round($ratiolineinvoice*100,2).'%)'; - } - print ''; - } - // Payment - $ratiopaymentinvoice = 1; + $ratiopaymentinvoice=1; if ($modetax != 1) { - print ''; - //print $fields['totalht']."-".$fields['payment_amount']."-".$fields['ftotal_ttc']; - if ($fields['payment_amount'] && $fields['ftotal_ttc']) { - $payment_static->id = $fields['payment_id']; - print $payment_static->getNomUrl(2); - } if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) { - print $langs->trans("NA"); } else { if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { - $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); - } - print price(price2num($fields['payment_amount'], 'MT')); - if (isset($fields['payment_amount'])) { - print ' ('.round($ratiopaymentinvoice * 100, 2).'%)'; + $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); } } - print ''; } // Total collected - print ''; - $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; - print price(price2num($temp_ht, 'MT'), 1); - print ''; + $temp_ht=$fields['totalht']*$ratiopaymentinvoice; // VAT - print ''; - $temp_vat = $fields['vat'] * $ratiopaymentinvoice; - print price(price2num($temp_vat, 'MT'), 1); - //print price($fields['vat']); - print ''; - print ''; + $temp_vat=$fields['vat']*$ratiopaymentinvoice; $subtot_coll_total_ht += $temp_ht; $subtot_coll_vat += $temp_vat; $x_coll_sum += $temp_vat; } } + + if ($invoice_type == 'customer' && $vat_rate_show == $rate) { + if (is_array($x_both[$rate]['coll']['detail'])) { + foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) { + // Define type + // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. + $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (!empty($fields['ddate_start'])) { + $type = 1; + } + if (!empty($fields['ddate_end'])) { + $type = 1; + } + + + print ''; + + // Ref + print '' . $fields['link'] . ''; + + // Invoice date + print '' . dol_print_date($fields['datef'], 'day') . ''; + + // Payment date + if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') print '' . dol_print_date($fields['datep'], 'day') . ''; + else print ''; + + // Company name + print '' . $fields['company_link'] . ''; + + // Description + print ''; + if ($fields['pid']) { + $product_static->id = $fields['pid']; + $product_static->ref = $fields['pref']; + $product_static->type = $fields['dtype']; // We force with the type of line to have type how line is registered + print $product_static->getNomUrl(1); + if (dol_string_nohtmltag($fields['descr'])) { + print ' - ' . dol_trunc(dol_string_nohtmltag($fields['descr']), 24); + } + } else { + if ($type) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } + if (preg_match('/^\((.*)\)$/', $fields['descr'], $reg)) { + if ($reg[1] == 'DEPOSIT') { + $fields['descr'] = $langs->transnoentitiesnoconv('Deposit'); + } elseif ($reg[1] == 'CREDIT_NOTE') { + $fields['descr'] = $langs->transnoentitiesnoconv('CreditNote'); + } else { + $fields['descr'] = $langs->transnoentitiesnoconv($reg[1]); + } + } + print $text . ' ' . dol_trunc(dol_string_nohtmltag($fields['descr']), 24); + + // Show range + print_date_range($fields['ddate_start'], $fields['ddate_end']); + } + print ''; + + // Total HT + if ($modetax != 1) { + print ''; + print price($fields['totalht']); + if (price2num($fields['ftotal_ttc'])) { + //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - "; + $ratiolineinvoice = ($fields['dtotal_ttc'] / $fields['ftotal_ttc']); + //print ' ('.round($ratiolineinvoice*100,2).'%)'; + } + print ''; + } + + // Payment + $ratiopaymentinvoice = 1; + if ($modetax != 1) { + print ''; + //print $fields['totalht']."-".$fields['payment_amount']."-".$fields['ftotal_ttc']; + if ($fields['payment_amount'] && $fields['ftotal_ttc']) { + $payment_static->id = $fields['payment_id']; + print $payment_static->getNomUrl(2); + } + if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) { + print $langs->trans("NA"); + } else { + if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { + $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); + } + print price(price2num($fields['payment_amount'], 'MT')); + if (isset($fields['payment_amount'])) { + print ' (' . round($ratiopaymentinvoice * 100, 2) . '%)'; + } + } + print ''; + } + + // Total collected + print ''; + $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; + print price(price2num($temp_ht, 'MT'), 1); + print ''; + + // VAT + print ''; + $temp_vat = $fields['vat'] * $ratiopaymentinvoice; + print price(price2num($temp_vat, 'MT'), 1); + //print price($fields['vat']); + print ''; + print ''; + + //$subtot_coll_total_ht += $temp_ht; + //$subtot_coll_vat += $temp_vat; + //$x_coll_sum += $temp_vat; + } + } + } // Total customers for this vat rate print ''; print ''; @@ -571,17 +616,14 @@ if (!is_array($x_coll) || !is_array($x_paye)) { } // Blank line - print ' '; + print ' '; // Print table headers for this quadri - expenses now print ''; print ''.$elementsup.''; print ''.$langs->trans("DateInvoice").''; - if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') { - print ''.$langs->trans("DatePayment").''; - } else { - print ''; - } + if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') print ''.$langs->trans("DatePayment").''; + else print ''; print ''.$namesup.''; print ''.$productsup.''; if ($modetax != 1) { @@ -598,7 +640,10 @@ if (!is_array($x_coll) || !is_array($x_paye)) { if (is_array($x_both[$rate]['paye']['detail'])) { print ""; - print ''.$langs->trans("Rate").': '.vatrate($rate).'%'; + print ''; + print $langs->trans('Rate') . ' : ' . vatrate($rate) . '%'; + print ' - ' . img_picto('', 'chevron-down', 'class="paddingrightonly"') . $langs->trans('VATReportShowByRateDetails') . ''; + print ''; print ''."\n"; foreach ($x_both[$rate]['paye']['detail'] as $index => $fields) { @@ -614,112 +659,151 @@ if (!is_array($x_coll) || !is_array($x_paye)) { $type = 1; } - - print ''; - - // Ref - print ''.$fields['link'].''; - - // Invoice date - print ''.dol_print_date($fields['datef'], 'day').''; - - // Payment date - if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') { - print ''.dol_print_date($fields['datep'], 'day').''; - } else { - print ''; - } - - // Company name - print ''.$fields['company_link'].''; - - // Description - print ''; - if ($fields['pid']) { - $product_static->id = $fields['pid']; - $product_static->ref = $fields['pref']; - $product_static->type = $fields['dtype']; // We force with the type of line to have type how line is registered - print $product_static->getNomUrl(1); - if (dol_string_nohtmltag($fields['descr'])) { - print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']), 24); - } - } else { - if ($type) { - $text = img_object($langs->trans('Service'), 'service'); - } else { - $text = img_object($langs->trans('Product'), 'product'); - } - if (preg_match('/^\((.*)\)$/', $fields['descr'], $reg)) { - if ($reg[1] == 'DEPOSIT') { - $fields['descr'] = $langs->transnoentitiesnoconv('Deposit'); - } elseif ($reg[1] == 'CREDIT_NOTE') { - $fields['descr'] = $langs->transnoentitiesnoconv('CreditNote'); - } else { - $fields['descr'] = $langs->transnoentitiesnoconv($reg[1]); - } - } - print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']), 24); - - // Show range - print_date_range($fields['ddate_start'], $fields['ddate_end']); - } - print ''; - - // Total HT - if ($modetax != 1) { - print ''; - print price($fields['totalht']); - if (price2num($fields['ftotal_ttc'])) { - //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - "; - $ratiolineinvoice = ($fields['dtotal_ttc'] / $fields['ftotal_ttc']); - //print ' ('.round($ratiolineinvoice*100,2).'%)'; - } - print ''; - } - // Payment $ratiopaymentinvoice = 1; if ($modetax != 1) { - print ''; - if ($fields['payment_amount'] && $fields['ftotal_ttc']) { - $paymentfourn_static->id = $fields['payment_id']; - print $paymentfourn_static->getNomUrl(2); - } - if (($type == 0 && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice') || ($type == 1 && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) { - print $langs->trans("NA"); } else { if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) { $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); } - print price(price2num($fields['payment_amount'], 'MT')); - if (isset($fields['payment_amount'])) { - print ' ('.round($ratiopaymentinvoice * 100, 2).'%)'; - } } - print ''; } // VAT paid - print ''; $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; - print price(price2num($temp_ht, 'MT'), 1); - print ''; // VAT - print ''; $temp_vat = $fields['vat'] * $ratiopaymentinvoice; - print price(price2num($temp_vat, 'MT'), 1); - //print price($fields['vat']); - print ''; - print ''; $subtot_paye_total_ht += $temp_ht; $subtot_paye_vat += $temp_vat; $x_paye_sum += $temp_vat; } + + if ($invoice_type == 'supplier' && $vat_rate_show == $rate) { + foreach ($x_both[$rate]['paye']['detail'] as $index => $fields) { + // Define type + // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. + $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (!empty($fields['ddate_start'])) { + $type = 1; + } + if (!empty($fields['ddate_end'])) { + $type = 1; + } + + + print ''; + + // Ref + print '' . $fields['link'] . ''; + + // Invoice date + print '' . dol_print_date($fields['datef'], 'day') . ''; + + // Payment date + if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') { + print '' . dol_print_date($fields['datep'], 'day') . ''; + } else { + print ''; + } + + // Company name + print '' . $fields['company_link'] . ''; + + // Description + print ''; + if ($fields['pid']) { + $product_static->id = $fields['pid']; + $product_static->ref = $fields['pref']; + $product_static->type = $fields['dtype']; // We force with the type of line to have type how line is registered + print $product_static->getNomUrl(1); + if (dol_string_nohtmltag($fields['descr'])) { + print ' - ' . dol_trunc(dol_string_nohtmltag($fields['descr']), 24); + } + } else { + if ($type) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } + if (preg_match('/^\((.*)\)$/', $fields['descr'], $reg)) { + if ($reg[1] == 'DEPOSIT') { + $fields['descr'] = $langs->transnoentitiesnoconv('Deposit'); + } elseif ($reg[1] == 'CREDIT_NOTE') { + $fields['descr'] = $langs->transnoentitiesnoconv('CreditNote'); + } else { + $fields['descr'] = $langs->transnoentitiesnoconv($reg[1]); + } + } + print $text . ' ' . dol_trunc(dol_string_nohtmltag($fields['descr']), 24); + + // Show range + print_date_range($fields['ddate_start'], $fields['ddate_end']); + } + print ''; + + // Total HT + if ($modetax != 1) { + print ''; + print price($fields['totalht']); + if (price2num($fields['ftotal_ttc'])) { + //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - "; + $ratiolineinvoice = ($fields['dtotal_ttc'] / $fields['ftotal_ttc']); + //print ' ('.round($ratiolineinvoice*100,2).'%)'; + } + print ''; + } + + // Payment + $ratiopaymentinvoice = 1; + if ($modetax != 1) { + print ''; + if ($fields['payment_amount'] && $fields['ftotal_ttc']) { + $paymentfourn_static->id = $fields['payment_id']; + print $paymentfourn_static->getNomUrl(2); + } + + if (($type == 0 && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice') + || ($type == 1 && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) { + print $langs->trans("NA"); + } else { + if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) { + $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); + } + print price(price2num($fields['payment_amount'], 'MT')); + if (isset($fields['payment_amount'])) { + print ' (' . round($ratiopaymentinvoice * 100, 2) . '%)'; + } + } + print ''; + } + + // VAT paid + print ''; + $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; + print price(price2num($temp_ht, 'MT'), 1); + print ''; + + // VAT + print ''; + $temp_vat = $fields['vat'] * $ratiopaymentinvoice; + print price(price2num($temp_vat, 'MT'), 1); + //print price($fields['vat']); + print ''; + print ''; + + //$subtot_paye_total_ht += $temp_ht; + //$subtot_paye_vat += $temp_vat; + //$x_paye_sum += $temp_vat; + } + } } + // Total suppliers for this vat rate print ''; print ''; diff --git a/htdocs/conf/.gitignore b/htdocs/conf/.gitignore index ed21fdfaa4c..8d06ea77328 100644 --- a/htdocs/conf/.gitignore +++ b/htdocs/conf/.gitignore @@ -5,3 +5,4 @@ /conf.php.pgsql /conf.php.sqlite /conf.php.utf8 +/conf.php.nov* diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php index 0def459d444..e75908adc10 100644 --- a/htdocs/contact/card.php +++ b/htdocs/contact/card.php @@ -750,7 +750,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { print ''; print ''; - //Unsubscribe + // Unsubscribe if (!empty($conf->mailing->enabled)) { if ($conf->use_javascript_ajax && $conf->global->MAILING_CONTACT_DEFAULT_BULK_STATUS==-1) { print "\n".''; + $stringtoshow .= '
'; // hideobject is to start hidden + $stringtoshow .= '
'; + $stringtoshow .= ''; + $stringtoshow .= ''; + $stringtoshow .= ''; + $stringtoshow .= ' ' . $langs->trans("Days"); + $stringtoshow .= ''; + $stringtoshow .= '
'; + $stringtoshow .= '
'; + + include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; + $px1 = new DolGraph(); + + $mesg = $px1->isGraphKo(); + $totalnb = 0; + if (!$mesg) { + $data = array(); + foreach ($dataseries as $value) { + $data[] = array($value['label'], $value['data']); + $totalnb += $value['data']; + } + $px1->SetData($data); + $px1->setShowLegend(2); + $px1->SetType(array('bar')); + $px1->SetLegend(array($langs->trans('BoxNumberOfTicketByDay'))); + $px1->SetMaxValue($px1->GetCeilMaxValue()); + $px1->SetHeight(192); + $px1->SetShading(3); + $px1->SetHorizTickIncrement(1); + $px1->SetCssPrefix("cssboxes"); + $px1->mode = 'depth'; + + $px1->draw('idgraphticketlastxdays'); + $graphtoshow= $px1->show($totalnb ? 0 : 1); + } + if ($totalnb) { + $stringtoshow .= $graphtoshow; + } + $stringtoshow .= ''; + if ($totalnb) { + $this->info_box_contents[][]=array( + 'td' => 'center', + 'text' => $stringtoshow + ); + } else { + $this->info_box_contents[0][0] = array( + 'td' => 'class="center opacitymedium"', + 'text' => $stringtoshow . $langs->trans("BoxNoTicketLastXDays", $days) + ); + } + } else { + $this->info_box_contents[0][0] = array( + 'td' => 'class="left"', + 'text' => $langs->trans("ReadPermissionNotAllowed"), + ); + } + } + + /** + * Method to show box + * + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @param int $nooutput No print, only return string + * @return string + */ + public function showBox($head = null, $contents = null, $nooutput = 0) + { + return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); + } +} diff --git a/htdocs/core/boxes/box_graph_nb_tickets_type.php b/htdocs/core/boxes/box_graph_nb_tickets_type.php new file mode 100644 index 00000000000..eea0f0ccf77 --- /dev/null +++ b/htdocs/core/boxes/box_graph_nb_tickets_type.php @@ -0,0 +1,209 @@ + + * 2016 Christophe Battarel + * Copyright (C) 2019 Frédéric France + * + * 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 + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file core/boxes/box_nb_ticket_last_x_days.php + * \ingroup ticket + * \brief This box shows the number of new daily tickets the last X days + */ +require_once DOL_DOCUMENT_ROOT."/core/boxes/modules_boxes.php"; + +/** + * Class to manage the box + */ +class box_graph_nb_tickets_type extends ModeleBoxes +{ + + public $boxcode = "box_nb_tickets_type"; + public $boximg = "ticket"; + public $boxlabel; + public $depends = array("ticket"); + + public $param; + public $info_box_head = array(); + public $info_box_contents = array(); + + public $widgettype = 'graph'; + + + /** + * Constructor + * @param DoliDB $db Database handler + * @param string $param More parameters + */ + public function __construct($db, $param = '') + { + global $langs; + $langs->load("boxes"); + $this->db = $db; + + $this->boxlabel = $langs->transnoentitiesnoconv("BoxTicketType"); + } + + /** + * Load data into info_box_contents array to show array later. + * + * @param int $max Maximum number of records to load + * @return void + */ + public function loadBox($max = 5) + { + global $conf, $user, $langs; + + $badgeStatus0 = '#cbd3d3'; // draft + $badgeStatus1 = '#bc9526'; // validated + $badgeStatus1b = '#bc9526'; // validated + $badgeStatus2 = '#9c9c26'; // approved + $badgeStatus3 = '#bca52b'; + $badgeStatus4 = '#25a580'; // Color ok + $badgeStatus4b = '#25a580'; // Color ok + $badgeStatus5 = '#cad2d2'; + $badgeStatus6 = '#cad2d2'; + $badgeStatus7 = '#baa32b'; + $badgeStatus8 = '#993013'; + $badgeStatus9 = '#e7f0f0'; + $text = $langs->trans("BoxTicketType"); + $this->info_box_head = array( + 'text' => $text, + 'limit' => dol_strlen($text) + ); + + $listofopplabel = array(); + $listofoppcode = array(); + $colorseriesstat = array(); + if ($user->rights->ticket->read) { + $sql = "SELECT ctt.rowid, ctt.label, ctt.code"; + $sql .= " FROM " . MAIN_DB_PREFIX . "c_ticket_type as ctt"; + $sql .= " WHERE ctt.active = 1"; + $sql .= $this->db->order('ctt.rowid', 'ASC'); + $resql = $this->db->query($sql); + + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) { + $objp = $this->db->fetch_object($resql); + $listofoppcode[$objp->rowid] = $objp->code; + $listofopplabel[$objp->rowid] = $objp->label; + switch ($objp->code) { + case 'COM': + $colorseriesstat[$objp->rowid] = $badgeStatus1; + break; + case 'HELP': + $colorseriesstat[$objp->rowid] = $badgeStatus2; + break; + case 'ISSUE': + $colorseriesstat[$objp->rowid] = $badgeStatus3; + break; + case 'REQUEST': + $colorseriesstat[$objp->rowid] = $badgeStatus4; + break; + case 'OTHER': + $colorseriesstat[$objp->rowid] = $badgeStatus5; + break; + default: + break; + } + $i++; + } + } else { + dol_print_error($this->db); + } + $dataseries = array(); + $data = array(); + $sql = "SELECT t.type_code, COUNT(t.type_code) as nb"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ticket as t"; + $sql .= " WHERE t.fk_statut <> 8"; + $sql .= " GROUP BY t.type_code"; + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) { + $objp = $this->db->fetch_object($resql); + $data[$objp->type_code] = $objp->nb; + $i++; + } + foreach ($listofoppcode as $rowid => $code) { + $dataseries[] = array('label' => $langs->getLabelFromKey($this->db, 'TicketTypeShort' . $code, 'c_ticket_category', 'code', 'label', $code), 'data' => $data[$code]); + } + } else { + dol_print_error($this->db); + } + $stringtoprint = ''; + $stringtoprint .= '
'; + if (!empty($dataseries) && count($dataseries) > 0) { + include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; + $px1 = new DolGraph(); + + $mesg = $px1->isGraphKo(); + $totalnb = 0; + if (!$mesg) { + $px1->SetDataColor(array_values($colorseriesstat)); + $data = array(); + $legend = array(); + foreach ($dataseries as $value) { + $data[] = array($value['label'], $value['data']); + $totalnb += $value['data']; + } + $px1->SetData($data); + $px1->setShowLegend(2); + $px1->SetType(array('pie')); + $px1->SetLegend($legend); + $px1->SetMaxValue($px1->GetCeilMaxValue()); + $px1->SetShading(3); + $px1->SetHorizTickIncrement(1); + $px1->SetCssPrefix("cssboxes"); + $px1->mode = 'depth'; + $px1->draw('idgraphtickettype'); + $stringtoprint .= $px1->show($totalnb ? 0 : 1); + } + $stringtoprint .= '
'; + $this->info_box_contents[][]=array( + 'td' => 'center', + 'text' => $stringtoprint + ); + } else { + $this->info_box_contents[0][0] = array( + 'td' => 'class="center opacitymedium"', + 'text' => $langs->trans("BoxNoTicketSeverity"), + ); + } + } else { + $this->info_box_contents[0][0] = array( + 'td' => 'class="left"', + 'text' => $langs->trans("ReadPermissionNotAllowed"), + ); + } + } + + /** + * Method to show box + * + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @param int $nooutput No print, only return string + * @return string + */ + public function showBox($head = null, $contents = null, $nooutput = 0) + { + return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); + } +} diff --git a/htdocs/core/boxes/box_graph_new_vs_close_ticket.php b/htdocs/core/boxes/box_graph_new_vs_close_ticket.php new file mode 100644 index 00000000000..bd835d6cc07 --- /dev/null +++ b/htdocs/core/boxes/box_graph_new_vs_close_ticket.php @@ -0,0 +1,181 @@ + + * 2016 Christophe Battarel + * Copyright (C) 2019 Frédéric France + * + * 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 + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file core/boxes/box_nb_ticket_last_x_days.php + * \ingroup ticket + * \brief This box shows the number of new daily tickets the last X days + */ +require_once DOL_DOCUMENT_ROOT."/core/boxes/modules_boxes.php"; + +/** + * Class to manage the box + */ +class box_graph_new_vs_close_ticket extends ModeleBoxes +{ + + public $boxcode = "box_nb_tickets_type"; + public $boximg = "ticket"; + public $boxlabel; + public $depends = array("ticket"); + + public $param; + public $info_box_head = array(); + public $info_box_contents = array(); + + public $widgettype = 'graph'; + + + /** + * Constructor + * @param DoliDB $db Database handler + * @param string $param More parameters + */ + public function __construct($db, $param = '') + { + global $langs; + $langs->load("boxes"); + $this->db = $db; + + $this->boxlabel = $langs->transnoentitiesnoconv("BoxNewTicketVSClose"); + } + + /** + * Load data into info_box_contents array to show array later. + * + * @param int $max Maximum number of records to load + * @return void + */ + public function loadBox($max = 5) + { + global $conf, $user, $langs; + + $badgeStatus0 = '#cbd3d3'; // draft + $badgeStatus1 = '#bc9526'; // validated + $badgeStatus1b = '#bc9526'; // validated + $badgeStatus2 = '#9c9c26'; // approved + $badgeStatus3 = '#bca52b'; + $badgeStatus4 = '#25a580'; // Color ok + $badgeStatus4b = '#25a580'; // Color ok + $badgeStatus5 = '#cad2d2'; + $badgeStatus6 = '#cad2d2'; + $badgeStatus7 = '#baa32b'; + $badgeStatus8 = '#993013'; + $badgeStatus9 = '#e7f0f0'; + $text = $langs->trans("BoxNewTicketVSClose"); + $this->info_box_head = array( + 'text' => $text, + 'limit' => dol_strlen($text) + ); + + if ($user->rights->ticket->read) { + $data = array(); + $totalnb = 0; + $sql = "SELECT COUNT(t.datec) as nb"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ticket as t"; + $sql .= " WHERE CAST(t.datec AS DATE) = CURRENT_DATE"; + $sql .= " AND t.fk_statut <> 8"; + $sql .= " GROUP BY CAST(t.datec AS DATE)"; + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + if ($num > 0) { + $objp = $this->db->fetch_object($resql); + $data[] = array($langs->trans('TicketCreatedToday'), $objp->nb); + $totalnb += $objp->nb; + } else { + $data[] = array($langs->trans('TicketCreatedToday'), 0); + } + } else { + dol_print_error($this->db); + } + $sql = "SELECT COUNT(t.date_close) as nb"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ticket as t"; + $sql .= " WHERE CAST(t.date_close AS DATE) = CURRENT_DATE"; + $sql .= " AND t.fk_statut = 8"; + $sql .= " GROUP BY CAST(t.date_close AS DATE)"; + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + if ($num > 0) { + $objp = $this->db->fetch_object($resql); + $data[] = array($langs->trans('TicketClosedToday'), $objp->nb); + $totalnb += $objp->nb; + } else { + $data[] = array($langs->trans('TicketClosedToday'), 0); + } + } else { + dol_print_error($this->db); + } + $colorseries = array(); + $colorseries[] = $badgeStatus8; + $colorseries[] = $badgeStatus2; + $stringtoprint = ''; + $stringtoprint .= '
'; + if (!empty($data) && count($data) > 0) { + include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; + $px1 = new DolGraph(); + $mesg = $px1->isGraphKo(); + if (!$mesg) { + $px1->SetDataColor(array_values($colorseries)); + $px1->SetData($data); + $px1->setShowLegend(2); + $px1->SetType(array('pie')); + $px1->SetMaxValue($px1->GetCeilMaxValue()); + $px1->SetShading(3); + $px1->SetHorizTickIncrement(1); + $px1->SetCssPrefix("cssboxes"); + $px1->mode = 'depth'; + + $px1->draw('idgraphticketnewvsclosetoday'); + $stringtoprint .= $px1->show($totalnb ? 0 : 1); + } + $stringtoprint .= '
'; + $this->info_box_contents[][]=array( + 'td' => 'center', + 'text' => $stringtoprint + ); + } else { + $this->info_box_contents[0][0] = array( + 'td' => 'class="center opacitymedium"', + 'text' => $langs->trans("BoxNoTicketSeverity"), + ); + } + } else { + $this->info_box_contents[0][0] = array( + 'td' => 'class="left"', + 'text' => $langs->trans("ReadPermissionNotAllowed"), + ); + } + } + + /** + * Method to show box + * + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @param int $nooutput No print, only return string + * @return string + */ + public function showBox($head = null, $contents = null, $nooutput = 0) + { + return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); + } +} diff --git a/htdocs/core/boxes/box_graph_orders_permonth.php b/htdocs/core/boxes/box_graph_orders_permonth.php index 3fafa464993..48f0bd67ec3 100644 --- a/htdocs/core/boxes/box_graph_orders_permonth.php +++ b/htdocs/core/boxes/box_graph_orders_permonth.php @@ -41,6 +41,8 @@ class box_graph_orders_permonth extends ModeleBoxes public $info_box_head = array(); public $info_box_contents = array(); + public $widgettype = 'graph'; + /** * Constructor @@ -122,7 +124,8 @@ class box_graph_orders_permonth extends ModeleBoxes $showtot = (!empty($tmparray['showtot']) ? $tmparray['showtot'] : ''); } if (empty($shownb) && empty($showtot)) { - $shownb = 1; $showtot = 1; + $shownb = 1; + $showtot = 1; } $nowarray = dol_getdate(dol_now(), true); if (empty($endyear)) { @@ -193,7 +196,8 @@ class box_graph_orders_permonth extends ModeleBoxes if (!$mesg) { $px2->SetData($data2); unset($data2); - $i = $startyear; $legend = array(); + $i = $startyear; + $legend = array(); while ($i <= $endyear) { if ($startmonth != 1) { $legend[] = sprintf("%d/%d", $i - 2001, $i - 2000); diff --git a/htdocs/core/boxes/box_graph_orders_supplier_permonth.php b/htdocs/core/boxes/box_graph_orders_supplier_permonth.php index 419e3afba83..a394834cd97 100644 --- a/htdocs/core/boxes/box_graph_orders_supplier_permonth.php +++ b/htdocs/core/boxes/box_graph_orders_supplier_permonth.php @@ -41,6 +41,8 @@ class box_graph_orders_supplier_permonth extends ModeleBoxes public $info_box_head = array(); public $info_box_contents = array(); + public $widgettype = 'graph'; + /** * Constructor @@ -121,7 +123,8 @@ class box_graph_orders_supplier_permonth extends ModeleBoxes $showtot = (!empty($tmparray['showtot']) ? $tmparray['showtot'] : ''); } if (empty($shownb) && empty($showtot)) { - $shownb = 1; $showtot = 1; + $shownb = 1; + $showtot = 1; } $nowarray = dol_getdate(dol_now(), true); if (empty($endyear)) { @@ -192,7 +195,8 @@ class box_graph_orders_supplier_permonth extends ModeleBoxes if (!$mesg) { $px2->SetData($data2); unset($data2); - $i = $startyear; $legend = array(); + $i = $startyear; + $legend = array(); while ($i <= $endyear) { if ($startmonth != 1) { $legend[] = sprintf("%d/%d", $i - 2001, $i - 2000); diff --git a/htdocs/core/boxes/box_graph_product_distribution.php b/htdocs/core/boxes/box_graph_product_distribution.php index 91a5f598347..4a88617de4e 100644 --- a/htdocs/core/boxes/box_graph_product_distribution.php +++ b/htdocs/core/boxes/box_graph_product_distribution.php @@ -44,6 +44,8 @@ class box_graph_product_distribution extends ModeleBoxes public $info_box_head = array(); public $info_box_contents = array(); + public $widgettype = 'graph'; + /** * Constructor @@ -101,7 +103,9 @@ class box_graph_product_distribution extends ModeleBoxes $showordernb = (!empty($tmparray['showordernb']) ? $tmparray['showordernb'] : ''); } if (empty($showinvoicenb) && empty($showpropalnb) && empty($showordernb)) { - $showpropalnb = 1; $showinvoicenb = 1; $showordernb = 1; + $showpropalnb = 1; + $showinvoicenb = 1; + $showordernb = 1; } if (empty($conf->facture->enabled) || empty($user->rights->facture->lire)) { $showinvoicenb = 0; @@ -154,7 +158,8 @@ class box_graph_product_distribution extends ModeleBoxes $langs->load("propal"); include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propalestats.class.php'; - $showpointvalue = 1; $nocolor = 0; + $showpointvalue = 1; + $nocolor = 0; $stats_proposal = new PropaleStats($this->db, $socid, ($userid > 0 ? $userid : 0)); $data2 = $stats_proposal->getAllByProductEntry($year, (GETPOST('action', 'aZ09') == $refreshaction ?-1 : (3600 * 24)), 5); if (empty($data2)) { @@ -169,7 +174,8 @@ class box_graph_product_distribution extends ModeleBoxes $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); if (!$mesg) { - $i = 0; $legend = array(); + $i = 0; + $legend = array(); foreach ($data2 as $key => $val) { $data2[$key][0] = dol_trunc($data2[$key][0], 32); @@ -210,7 +216,8 @@ class box_graph_product_distribution extends ModeleBoxes $langs->load("orders"); include_once DOL_DOCUMENT_ROOT.'/commande/class/commandestats.class.php'; - $showpointvalue = 1; $nocolor = 0; + $showpointvalue = 1; + $nocolor = 0; $mode = 'customer'; $stats_order = new CommandeStats($this->db, $socid, $mode, ($userid > 0 ? $userid : 0)); $data3 = $stats_order->getAllByProductEntry($year, (GETPOST('action', 'aZ09') == $refreshaction ?-1 : (3600 * 24)), 5); @@ -226,7 +233,8 @@ class box_graph_product_distribution extends ModeleBoxes $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); if (!$mesg) { - $i = 0; $legend = array(); + $i = 0; + $legend = array(); foreach ($data3 as $key => $val) { $data3[$key][0] = dol_trunc($data3[$key][0], 32); @@ -268,7 +276,8 @@ class box_graph_product_distribution extends ModeleBoxes $langs->load("bills"); include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facturestats.class.php'; - $showpointvalue = 1; $nocolor = 0; + $showpointvalue = 1; + $nocolor = 0; $mode = 'customer'; $stats_invoice = new FactureStats($this->db, $socid, $mode, ($userid > 0 ? $userid : 0)); $data1 = $stats_invoice->getAllByProductEntry($year, (GETPOST('action', 'aZ09') == $refreshaction ?-1 : (3600 * 24)), 5); @@ -284,7 +293,8 @@ class box_graph_product_distribution extends ModeleBoxes $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); if (!$mesg) { - $i = 0; $legend = array(); + $i = 0; + $legend = array(); foreach ($data1 as $key => $val) { $data1[$key][0] = dol_trunc($data1[$key][0], 32); diff --git a/htdocs/core/boxes/box_graph_propales_permonth.php b/htdocs/core/boxes/box_graph_propales_permonth.php index 8193e81d060..8a95761ea08 100644 --- a/htdocs/core/boxes/box_graph_propales_permonth.php +++ b/htdocs/core/boxes/box_graph_propales_permonth.php @@ -41,6 +41,8 @@ class box_graph_propales_permonth extends ModeleBoxes public $info_box_head = array(); public $info_box_contents = array(); + public $widgettype = 'graph'; + /** * Constructor @@ -122,7 +124,8 @@ class box_graph_propales_permonth extends ModeleBoxes $showtot = (!empty($tmparray['showtot']) ? $tmparray['showtot'] : ''); } if (empty($shownb) && empty($showtot)) { - $shownb = 1; $showtot = 1; + $shownb = 1; + $showtot = 1; } $nowarray = dol_getdate(dol_now(), true); if (empty($endyear)) { @@ -149,7 +152,8 @@ class box_graph_propales_permonth extends ModeleBoxes $px1->SetType($datatype1); $px1->SetData($data1); unset($data1); - $i = $startyear; $legend = array(); + $i = $startyear; + $legend = array(); while ($i <= $endyear) { if ($startmonth != 1) { $legend[] = sprintf("%d/%d", $i - 2001, $i - 2000); @@ -195,7 +199,8 @@ class box_graph_propales_permonth extends ModeleBoxes $px2->SetType($datatype2); $px2->SetData($data2); unset($data2); - $i = $startyear; $legend = array(); + $i = $startyear; + $legend = array(); while ($i <= $endyear) { if ($startmonth != 1) { $legend[] = sprintf("%d/%d", $i - 2001, $i - 2000); diff --git a/htdocs/core/boxes/box_graph_ticket_by_severity.php b/htdocs/core/boxes/box_graph_ticket_by_severity.php new file mode 100644 index 00000000000..252769abd0e --- /dev/null +++ b/htdocs/core/boxes/box_graph_ticket_by_severity.php @@ -0,0 +1,220 @@ + + * 2016 Christophe Battarel + * Copyright (C) 2019 Frédéric France + * + * 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 + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file core/boxes/box_ticket_by_severity.php + * \ingroup ticket + * \brief This box shows open tickets by severity + */ +require_once DOL_DOCUMENT_ROOT."/core/boxes/modules_boxes.php"; + +/** + * Class to manage the box + */ +class box_graph_ticket_by_severity extends ModeleBoxes +{ + + public $boxcode = "box_ticket_by_severity"; + public $boximg = "ticket"; + public $boxlabel; + public $depends = array("ticket"); + + /** + * @var DoliDB Database handler. + */ + public $db; + + public $param; + public $info_box_head = array(); + public $info_box_contents = array(); + + public $widgettype = 'graph'; + + + /** + * Constructor + * @param DoliDB $db Database handler + * @param string $param More parameters + */ + public function __construct($db, $param = '') + { + global $langs; + $langs->load("boxes"); + $this->db = $db; + + $this->boxlabel = $langs->transnoentitiesnoconv("BoxTicketSeverity"); + } + + /** + * Load data into info_box_contents array to show array later. + * + * @param int $max Maximum number of records to load + * @return void + */ + public function loadBox($max = 5) + { + global $conf, $user, $langs; + + $badgeStatus0 = '#cbd3d3'; // draft + $badgeStatus1 = '#bc9526'; // validated + $badgeStatus1b = '#bc9526'; // validated + $badgeStatus2 = '#9c9c26'; // approved + $badgeStatus3 = '#bca52b'; + $badgeStatus4 = '#25a580'; // Color ok + $badgeStatus4b = '#25a580'; // Color ok + $badgeStatus5 = '#cad2d2'; + $badgeStatus6 = '#cad2d2'; + $badgeStatus7 = '#baa32b'; + $badgeStatus8 = '#993013'; + $badgeStatus9 = '#e7f0f0'; + if (file_exists(DOL_DOCUMENT_ROOT . '/theme/' . $conf->theme . '/theme_vars.inc.php')) { + include DOL_DOCUMENT_ROOT . '/theme/' . $conf->theme . '/theme_vars.inc.php'; + } + $this->max = $max; + + require_once DOL_DOCUMENT_ROOT."/ticket/class/ticket.class.php"; + + $text = $langs->trans("BoxTicketSeverity", $max); + $this->info_box_head = array( + 'text' => $text, + 'limit' => dol_strlen($text) + ); + + $listofopplabel = array(); + $listofoppcode = array(); + $colorseriesstat = array(); + if ($user->rights->ticket->read) { + $sql = "SELECT cts.rowid, cts.label, cts.code"; + $sql .= " FROM " . MAIN_DB_PREFIX . "c_ticket_severity as cts"; + $sql .= " WHERE cts.active = 1"; + $sql .= $this->db->order('cts.rowid', 'ASC'); + $resql = $this->db->query($sql); + + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) { + $objp = $this->db->fetch_object($resql); + $listofoppcode[$objp->rowid] = $objp->code; + $listofopplabel[$objp->rowid] = $objp->label; + switch ($objp->code) { + case 'LOW': + $colorseriesstat[$objp->rowid] = $badgeStatus4; + break; + case 'NORMAL': + $colorseriesstat[$objp->rowid] = $badgeStatus2; + break; + case 'HIGH': + $colorseriesstat[$objp->rowid] = $badgeStatus1; + break; + case 'BLOCKING': + $colorseriesstat[$objp->rowid] = $badgeStatus8; + break; + default: + break; + } + $i++; + } + } else { + dol_print_error($this->db); + } + + $dataseries = array(); + $data = array(); + $sql = "SELECT t.severity_code, COUNT(t.severity_code) as nb"; + $sql .= " FROM " . MAIN_DB_PREFIX . "ticket as t"; + $sql .= " WHERE t.fk_statut <> 8"; + $sql .= " GROUP BY t.severity_code"; + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < $num) { + $objp = $this->db->fetch_object($resql); + $data[$objp->severity_code] = $objp->nb; + $i++; + } + foreach ($listofoppcode as $rowid => $code) { + $dataseries[] = array('label' => $langs->getLabelFromKey($this->db, 'TicketSeverityShort' . $code, 'c_ticket_category', 'code', 'label', $code), 'data' => $data[$code]); + } + } else { + dol_print_error($this->db); + } + $stringtoprint = ''; + $stringtoprint .= '
'; + if (!empty($dataseries) && count($dataseries) > 0) { + include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; + $px1 = new DolGraph(); + $mesg = $px1->isGraphKo(); + $totalnb = 0; + if (!$mesg) { + $px1->SetDataColor(array_values($colorseriesstat)); + $data = array(); + $legend = array(); + foreach ($dataseries as $value) { + $data[] = array($value['label'], $value['data']); + $totalnb += $value['data']; + } + $px1->SetData($data); + $px1->setShowLegend(2); + $px1->SetType(array('pie')); + $px1->SetLegend($legend); + $px1->SetMaxValue($px1->GetCeilMaxValue()); + //$px1->SetHeight($HEIGHT); + $px1->SetShading(3); + $px1->SetHorizTickIncrement(1); + $px1->SetCssPrefix("cssboxes"); + $px1->mode = 'depth'; + + $px1->draw('idgraphticketseverity'); + $stringtoprint .= $px1->show($totalnb ? 0 : 1); + } + $stringtoprint .= '
'; + $this->info_box_contents[][]=array( + 'td' => 'center', + 'text' => $stringtoprint + ); + } else { + $this->info_box_contents[0][0] = array( + 'td' => 'class="center opacitymedium"', + 'text' => $langs->trans("BoxNoTicketSeverity") + ); + } + } else { + $this->info_box_contents[0][0] = array( + 'td' => 'class="left"', + 'text' => $langs->trans("ReadPermissionNotAllowed"), + ); + } + } + + /** + * Method to show box + * + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @param int $nooutput No print, only return string + * @return string + */ + public function showBox($head = null, $contents = null, $nooutput = 0) + { + return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); + } +} diff --git a/htdocs/core/boxes/box_members.php b/htdocs/core/boxes/box_members.php index 5c9aee97828..acd3773d2f0 100644 --- a/htdocs/core/boxes/box_members.php +++ b/htdocs/core/boxes/box_members.php @@ -92,7 +92,7 @@ class box_members extends ModeleBoxes $sql = "SELECT a.rowid, a.ref, a.lastname, a.firstname, a.societe as company, a.fk_soc,"; $sql .= " a.datec, a.tms, a.statut as status, a.datefin as date_end_subscription,"; $sql .= ' a.photo, a.email, a.gender, a.morphy,'; - $sql .= " t.subscription"; + $sql .= " t.subscription, t.libelle as label"; $sql .= " FROM ".MAIN_DB_PREFIX."adherent as a, ".MAIN_DB_PREFIX."adherent_type as t"; $sql .= " WHERE a.entity IN (".getEntity('member').")"; $sql .= " AND a.fk_adherent_type = t.rowid"; diff --git a/htdocs/core/boxes/box_members_by_type.php b/htdocs/core/boxes/box_members_by_type.php new file mode 100644 index 00000000000..cf81eaac57c --- /dev/null +++ b/htdocs/core/boxes/box_members_by_type.php @@ -0,0 +1,277 @@ + + * Copyright (C) 2004-2017 Laurent Destailleur + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2015-2020 Frederic France + * + * 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 + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/boxes/box_members_by_type.php + * \ingroup adherent + * \brief Module to show box of members + */ + +include_once DOL_DOCUMENT_ROOT . '/core/boxes/modules_boxes.php'; + + +/** + * Class to manage the box to show last modofied members + */ +class box_members_by_type extends ModeleBoxes +{ + public $boxcode = "box_members_by_type"; + public $boximg = "object_user"; + public $boxlabel = "BoxMembersByType"; + public $depends = array("adherent"); + + /** + * @var DoliDB Database handler. + */ + public $db; + + public $param; + public $enabled = 1; + + public $info_box_head = array(); + public $info_box_contents = array(); + + + /** + * Constructor + * + * @param DoliDB $db Database handler + * @param string $param More parameters + */ + public function __construct($db, $param = '') + { + global $conf, $user; + + $this->db = $db; + + // disable module for such cases + $listofmodulesforexternal = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); + if (!in_array('adherent', $listofmodulesforexternal) && !empty($user->socid)) { + $this->enabled = 0; // disabled for external users + } + + $this->hidden = !($user->rights->adherent->lire); + } + + /** + * Load data into info_box_contents array to show array later. + * + * @param int $max Maximum number of records to load + * @return void + */ + public function loadBox($max = 5) + { + global $user, $langs, $conf; + $langs->load("boxes"); + + $this->max = $max; + + include_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php'; + require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent_type.class.php'; + $staticmember = new Adherent($this->db); + + $this->info_box_head = array('text' => $langs->trans("BoxTitleMembersByType", $max)); + + if ($user->rights->adherent->lire) { + $MembersToValidate = array(); + $MembersValidated = array(); + $MemberUpToDate = array(); + $MembersResiliated = array(); + + $SommeA = 0; + $SommeB = 0; + $SommeC = 0; + $SommeD = 0; + + $AdherentType = array(); + + // Type of membership + $sql = "SELECT t.rowid, t.libelle as label, t.subscription,"; + $sql .= " d.statut, count(d.rowid) as somme"; + $sql .= " FROM " . MAIN_DB_PREFIX . "adherent_type as t"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "adherent as d"; + $sql .= " ON t.rowid = d.fk_adherent_type"; + $sql .= " AND d.entity IN (" . getEntity('adherent') . ")"; + $sql .= " WHERE t.entity IN (" . getEntity('member_type') . ")"; + $sql .= " GROUP BY t.rowid, t.libelle, t.subscription, d.statut"; + + dol_syslog("box_members_by_type::select nb of members per type", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num) { + $objp = $this->db->fetch_object($result); + + $adhtype = new AdherentType($this->db); + $adhtype->id = $objp->rowid; + $adhtype->subscription = $objp->subscription; + $adhtype->label = $objp->label; + $AdherentType[$objp->rowid] = $adhtype; + + if ($objp->statut == -1) { + $MembersToValidate[$objp->rowid] = $objp->somme; + } + if ($objp->statut == 1) { + $MembersValidated[$objp->rowid] = $objp->somme; + } + if ($objp->statut == 0) { + $MembersResiliated[$objp->rowid] = $objp->somme; + } + + $i++; + } + $this->db->free($result); + $now = dol_now(); + + // Members up to date list + // current rule: uptodate = the end date is in future whatever is type + // old rule: uptodate = if type does not need payment, that end date is null, if type need payment that end date is in future) + $sql = "SELECT count(*) as somme , d.fk_adherent_type"; + $sql .= " FROM " . MAIN_DB_PREFIX . "adherent as d, " . MAIN_DB_PREFIX . "adherent_type as t"; + $sql .= " WHERE d.entity IN (" . getEntity('adherent') . ")"; + $sql .= " AND d.statut = 1 AND (d.datefin >= '" . $this->db->idate($now) . "' OR t.subscription = 0)"; + $sql .= " AND t.rowid = d.fk_adherent_type"; + $sql .= " GROUP BY d.fk_adherent_type"; + + dol_syslog("index.php::select nb of uptodate members by type", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) { + $num2 = $this->db->num_rows($result); + $i = 0; + while ($i < $num2) { + $objp = $this->db->fetch_object($result); + $MemberUpToDate[$objp->fk_adherent_type] = $objp->somme; + $i++; + } + $this->db->free($result); + } + + $line = 0; + $this->info_box_contents[$line][] = array( + 'td' => 'class="liste_titre"', + 'text' => $langs->trans("MembersTypes"), + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => $langs->trans("MembersStatusToValid"), + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => $langs->trans("OutOfDate"), + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => $langs->trans("UpToDate"), + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => $langs->trans("MembersStatusResiliated"), + ); + $line++; + foreach ($AdherentType as $key => $adhtype) { + $SommeA += isset($MembersToValidate[$key]) ? $MembersToValidate[$key] : 0; + $SommeB += isset($MembersValidated[$key]) ? $MembersValidated[$key] - (isset($MemberUpToDate[$key]) ? $MemberUpToDate[$key] : 0) : 0; + $SommeC += isset($MemberUpToDate[$key]) ? $MemberUpToDate[$key] : 0; + $SommeD += isset($MembersResiliated[$key]) ? $MembersResiliated[$key] : 0; + $this->info_box_contents[$line][] = array( + 'td' => 'class="tdoverflowmax150 maxwidth150onsmartphone"', + 'text' => $adhtype->getNomUrl(1, dol_size(32)), + 'asis' => 1, + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => (isset($MembersToValidate[$key]) && $MembersToValidate[$key] > 0 ? $MembersToValidate[$key] : '') . ' ' . $staticmember->LibStatut(-1, $adhtype->subscription, 0, 3), + 'asis' => 1, + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => (isset($MembersValidated[$key]) && ($MembersValidated[$key] - (isset($MemberUpToDate[$key]) ? $MemberUpToDate[$key] : 0) > 0) ? $MembersValidated[$key] - (isset($MemberUpToDate[$key]) ? $MemberUpToDate[$key] : 0) : '') . ' ' . $staticmember->LibStatut(1, $adhtype->subscription, 0, 3), + 'asis' => 1, + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => (isset($MemberUpToDate[$key]) && $MemberUpToDate[$key] > 0 ? $MemberUpToDate[$key] : '') . ' ' . $staticmember->LibStatut(1, $adhtype->subscription, $now, 3), + 'asis' => 1, + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => (isset($MembersResiliated[$key]) && $MembersResiliated[$key] > 0 ? $MembersResiliated[$key] : '') . ' ' . $staticmember->LibStatut(0, $adhtype->subscription, 0, 3), + 'asis' => 1, + ); + + $line++; + } + + if ($num == 0) { + $this->info_box_contents[$line][0] = array( + 'td' => 'class="center"', + 'text' => $langs->trans("NoRecordedMembersByType"), + ); + } else { + $this->info_box_contents[$line][] = array( + 'td' => 'class="liste_total"', + 'text' => $langs->trans("Total"), + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="liste_total right"', + 'text' => $SommeA.' '.$staticmember->LibStatut(-1, $adhtype->subscription, 0, 3), + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="liste_total right"', + 'text' => $SommeB.' '.$staticmember->LibStatut(1, $adhtype->subscription, 0, 3), + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="liste_total right"', + 'text' => $SommeC.' '.$staticmember->LibStatut(1, $adhtype->subscription, $now, 3), + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="liste_total right"', + 'text' => $SommeD.' '.$staticmember->LibStatut(0, $adhtype->subscription, 0, 3), + ); + } + } else { + $this->info_box_contents[0][0] = array( + 'td' => '', + 'maxlength' => 500, + 'text' => ($this->db->error() . ' sql=' . $sql), + ); + } + } else { + $this->info_box_contents[0][0] = array( + 'td' => 'class="nohover opacitymedium left"', + 'text' => $langs->trans("ReadPermissionNotAllowed") + ); + } + } + + /** + * Method to show box + * + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @param int $nooutput No print, only return string + * @return string + */ + public function showBox($head = null, $contents = null, $nooutput = 0) + { + return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); + } +} diff --git a/htdocs/core/boxes/box_members_last_modified.php b/htdocs/core/boxes/box_members_last_modified.php new file mode 100644 index 00000000000..9ec1bf70558 --- /dev/null +++ b/htdocs/core/boxes/box_members_last_modified.php @@ -0,0 +1,197 @@ + + * Copyright (C) 2004-2017 Laurent Destailleur + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2015-2020 Frederic France + * + * 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 + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/boxes/box_last_modified_members.php + * \ingroup adherent + * \brief Module to show box of members + */ + +include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php'; + + +/** + * Class to manage the box to show last modofied members + */ +class box_last_modified_members extends ModeleBoxes +{ + public $boxcode = "box_last_modified_members"; + public $boximg = "object_user"; + public $boxlabel = "BoxLastModifiedMembers"; + public $depends = array("adherent"); + + /** + * @var DoliDB Database handler. + */ + public $db; + + public $param; + public $enabled = 1; + + public $info_box_head = array(); + public $info_box_contents = array(); + + + /** + * Constructor + * + * @param DoliDB $db Database handler + * @param string $param More parameters + */ + public function __construct($db, $param = '') + { + global $conf, $user; + + $this->db = $db; + + // disable module for such cases + $listofmodulesforexternal = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); + if (!in_array('adherent', $listofmodulesforexternal) && !empty($user->socid)) { + $this->enabled = 0; // disabled for external users + } + + $this->hidden = !($user->rights->adherent->lire); + } + + /** + * Load data into info_box_contents array to show array later. + * + * @param int $max Maximum number of records to load + * @return void + */ + public function loadBox($max = 5) + { + global $user, $langs, $conf; + $langs->load("boxes"); + + $this->max = $max; + + include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; + require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php'; + $memberstatic = new Adherent($this->db); + $statictype = new AdherentType($this->db); + + $this->info_box_head = array('text' => $langs->trans("BoxTitleLastModifiedMembers", $max)); + + if ($user->rights->adherent->lire) { + $sql = "SELECT a.rowid, a.ref, a.lastname, a.firstname, a.societe as company, a.fk_soc,"; + $sql .= " a.datec, a.tms, a.statut as status, a.datefin as date_end_subscription,"; + $sql .= ' a.photo, a.email, a.gender, a.morphy,'; + $sql .= " t.rowid as typeid, t.subscription, t.libelle as label"; + $sql .= " FROM ".MAIN_DB_PREFIX."adherent as a, ".MAIN_DB_PREFIX."adherent_type as t"; + $sql .= " WHERE a.entity IN (".getEntity('member').")"; + $sql .= " AND a.fk_adherent_type = t.rowid"; + $sql .= " ORDER BY a.tms DESC"; + $sql .= $this->db->plimit($max, 0); + + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + + $line = 0; + while ($line < $num) { + $objp = $this->db->fetch_object($result); + $datec = $this->db->jdate($objp->datec); + $datem = $this->db->jdate($objp->tms); + + $memberstatic->lastname = $objp->lastname; + $memberstatic->firstname = $objp->firstname; + $memberstatic->id = $objp->rowid; + $memberstatic->ref = $objp->ref; + $memberstatic->photo = $objp->photo; + $memberstatic->gender = $objp->gender; + $memberstatic->email = $objp->email; + $memberstatic->morphy = $objp->morphy; + $memberstatic->company = $objp->company; + $memberstatic->statut = $objp->status; + $memberstatic->need_subscription = $objp->subscription; + $memberstatic->datefin = $this->db->jdate($objp->date_end_subscription); + if (!empty($objp->fk_soc)) { + $memberstatic->socid = $objp->fk_soc; + $memberstatic->fetch_thirdparty(); + $memberstatic->name = $memberstatic->thirdparty->name; + } else { + $memberstatic->name = $objp->company; + } + $statictype->id = $objp->typeid; + $statictype->label = $objp->label; + $statictype->subscription = $objp->subscription; + + $this->info_box_contents[$line][] = array( + 'td' => 'class="tdoverflowmax150 maxwidth150onsmartphone"', + 'text' => $memberstatic->getNomUrl(-1), + 'asis' => 1, + ); + + $this->info_box_contents[$line][] = array( + 'td' => 'class="tdoverflowmax150 maxwidth150onsmartphone"', + 'text' => $statictype->getNomUrl(1, 32), + 'asis' => 1, + ); + + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => dol_print_date($datem, "day"), + ); + + $this->info_box_contents[$line][] = array( + 'td' => 'class="right" width="18"', + 'text' => $memberstatic->LibStatut($objp->status, $objp->subscription, $this->db->jdate($objp->date_end_subscription), 3), + ); + + $line++; + } + + if ($num == 0) { + $this->info_box_contents[$line][0] = array( + 'td' => 'class="center"', + 'text'=>$langs->trans("NoRecordedCustomers"), + ); + } + + $this->db->free($result); + } else { + $this->info_box_contents[0][0] = array( + 'td' => '', + 'maxlength'=>500, + 'text' => ($this->db->error().' sql='.$sql), + ); + } + } else { + $this->info_box_contents[0][0] = array( + 'td' => 'class="nohover opacitymedium left"', + 'text' => $langs->trans("ReadPermissionNotAllowed") + ); + } + } + + /** + * Method to show box + * + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @param int $nooutput No print, only return string + * @return string + */ + public function showBox($head = null, $contents = null, $nooutput = 0) + { + return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); + } +} diff --git a/htdocs/core/boxes/box_members_last_subscriptions.php b/htdocs/core/boxes/box_members_last_subscriptions.php new file mode 100644 index 00000000000..0b2cb02d920 --- /dev/null +++ b/htdocs/core/boxes/box_members_last_subscriptions.php @@ -0,0 +1,202 @@ + + * Copyright (C) 2004-2017 Laurent Destailleur + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2015-2020 Frederic France + * + * 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 + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/boxes/box_last_members_subscriptions.php + * \ingroup adherent + * \brief Module to show box of members + */ + +include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php'; + + +/** + * Class to manage the box to show last modofied members + */ +class box_last_members_subscriptions extends ModeleBoxes +{ + public $boxcode = "box_last_members_subscriptions"; + public $boximg = "object_user"; + public $boxlabel = "BoxLastMembersSubscriptions"; + public $depends = array("adherent"); + + /** + * @var DoliDB Database handler. + */ + public $db; + + public $param; + public $enabled = 1; + + public $info_box_head = array(); + public $info_box_contents = array(); + + + /** + * Constructor + * + * @param DoliDB $db Database handler + * @param string $param More parameters + */ + public function __construct($db, $param = '') + { + global $conf, $user; + + $this->db = $db; + + // disable module for such cases + $listofmodulesforexternal = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); + if (!in_array('adherent', $listofmodulesforexternal) && !empty($user->socid)) { + $this->enabled = 0; // disabled for external users + } + + $this->hidden = !($user->rights->adherent->lire); + } + + /** + * Load data into info_box_contents array to show array later. + * + * @param int $max Maximum number of records to load + * @return void + */ + public function loadBox($max = 5) + { + global $user, $langs, $conf; + $langs->load("boxes"); + + $this->max = $max; + + include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; + require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php'; + require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php'; + $staticmember = new Adherent($this->db); + $statictype = new AdherentType($this->db); + $subscriptionstatic = new Subscription($this->db); + + $this->info_box_head = array('text' => $langs->trans("LastSubscriptionsModified", $max)); + + if ($user->rights->adherent->lire) { + $sql = "SELECT a.rowid, a.statut as status, a.lastname, a.firstname, a.societe as company, a.fk_soc,"; + $sql .= " a.gender, a.email, a.photo, a.morphy,"; + $sql .= " a.datefin as date_end_subscription,"; + $sql .= " ta.rowid as typeid, ta.libelle as label, ta.subscription as need_subscription,"; + $sql .= " c.rowid as cid, c.tms as datem, c.datec as datec, c.dateadh as date_start, c.datef as date_end, c.subscription"; + $sql .= " FROM ".MAIN_DB_PREFIX."adherent as a, ".MAIN_DB_PREFIX."adherent_type as ta, ".MAIN_DB_PREFIX."subscription as c"; + $sql .= " WHERE a.entity IN (".getEntity('adherent').")"; + $sql .= " AND a.fk_adherent_type = ta.rowid"; + $sql .= " AND c.fk_adherent = a.rowid"; + $sql .= $this->db->order("c.tms", "DESC"); + $sql .= $this->db->plimit($max, 0); + + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + + $line = 0; + while ($line < $num) { + $obj = $this->db->fetch_object($result); + $staticmember->id = $obj->rowid; + $staticmember->ref = $obj->rowid; + $staticmember->lastname = $obj->lastname; + $staticmember->firstname = $obj->firstname; + $staticmember->gender = $obj->gender; + $staticmember->email = $obj->email; + $staticmember->photo = $obj->photo; + $staticmember->morphy = $obj->morphy; + $staticmember->statut = $obj->status; + $staticmember->need_subscription = $obj->need_subscription; + $staticmember->datefin = $this->db->jdate($obj->date_end_subscription); + if (!empty($obj->fk_soc)) { + $staticmember->fk_soc = $obj->fk_soc; + $staticmember->fetch_thirdparty(); + $staticmember->name = $staticmember->thirdparty->name; + } else { + $staticmember->name = $obj->company; + } + + $subscriptionstatic->id = $obj->cid; + $subscriptionstatic->ref = $obj->cid; + + $this->info_box_contents[$line][] = array( + 'td' => 'class="tdoverflowmax100 maxwidth100onsmartphone"', + 'text' => $subscriptionstatic->getNomUrl(1), + 'asis' => 1, + ); + + $this->info_box_contents[$line][] = array( + 'td' => 'class="tdoverflowmax150 maxwidth150onsmartphone"', + 'text' => $staticmember->getNomUrl(-1, 32, 'subscription'), + 'asis' => 1, + ); + + $this->info_box_contents[$line][] = array( + 'td' => 'class="tdoverflowmax150 maxwidth150onsmartphone"', + 'text' => get_date_range($this->db->jdate($obj->date_start), $this->db->jdate($obj->date_end)), + ); + + $this->info_box_contents[$line][] = array( + 'td' => 'class="right" width="18"', + 'text' => price($obj->subscription), + ); + + $this->info_box_contents[$line][] = array( + 'td' => 'class="right tdoverflowmax150 maxwidth150onsmartphone"', + 'text' => dol_print_date($this->db->jdate($obj->datem ? $obj->datem : $obj->datec), 'dayhour'), + ); + + $line++; + } + + if ($num == 0) { + $this->info_box_contents[$line][0] = array( + 'td' => 'class="center"', + 'text'=>$langs->trans("NoRecordedCustomers"), + ); + } + + $this->db->free($result); + } else { + $this->info_box_contents[0][0] = array( + 'td' => '', + 'maxlength'=>500, + 'text' => ($this->db->error().' sql='.$sql), + ); + } + } else { + $this->info_box_contents[0][0] = array( + 'td' => 'class="nohover opacitymedium left"', + 'text' => $langs->trans("ReadPermissionNotAllowed") + ); + } + } + + /** + * Method to show box + * + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @param int $nooutput No print, only return string + * @return string + */ + public function showBox($head = null, $contents = null, $nooutput = 0) + { + return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); + } +} diff --git a/htdocs/core/boxes/box_members_subscriptions_by_year.php b/htdocs/core/boxes/box_members_subscriptions_by_year.php new file mode 100644 index 00000000000..55a11339c0f --- /dev/null +++ b/htdocs/core/boxes/box_members_subscriptions_by_year.php @@ -0,0 +1,242 @@ + + * Copyright (C) 2004-2017 Laurent Destailleur + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2015-2021 Frederic France + * + * 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 + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/boxes/box_members_subscriptions_by_year.php + * \ingroup adherent + * \brief Module to show box of members + */ + +include_once DOL_DOCUMENT_ROOT . '/core/boxes/modules_boxes.php'; + + +/** + * Class to manage the box to show last modofied members + */ +class box_members_subscriptions_by_year extends ModeleBoxes +{ + public $boxcode = "box_members_subscriptions_by_year"; + public $boximg = "object_user"; + public $boxlabel = "BoxMembersSubscriptionsByYear"; + public $depends = array("adherent"); + + /** + * @var DoliDB Database handler. + */ + public $db; + + public $param; + public $enabled = 1; + + public $info_box_head = array(); + public $info_box_contents = array(); + + + /** + * Constructor + * + * @param DoliDB $db Database handler + * @param string $param More parameters + */ + public function __construct($db, $param = '') + { + global $conf, $user; + + $this->db = $db; + + // disable module for such cases + $listofmodulesforexternal = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); + if (!in_array('adherent', $listofmodulesforexternal) && !empty($user->socid)) { + $this->enabled = 0; // disabled for external users + } + + $this->hidden = !($user->rights->adherent->lire); + } + + /** + * Load data into info_box_contents array to show array later. + * + * @param int $max Maximum number of records to load + * @return void + */ + public function loadBox($max = 5) + { + global $user, $langs, $conf; + $langs->load("boxes"); + + $this->max = $max; + + include_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php'; + require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent_type.class.php'; + $memberstatic = new Adherent($this->db); + $statictype = new AdherentType($this->db); + + $this->info_box_head = array('text' => $langs->trans("BoxTitleMembersSubscriptionsByYear", $max)); + + if ($user->rights->adherent->lire) { + $num = 0; + $line = 0; + // List of subscription by year + $Total = array(); + $Number = array(); + $tot = 0; + $numb = 0; + + $sql = "SELECT c.subscription, c.dateadh as dateh"; + $sql .= " FROM " . MAIN_DB_PREFIX . "adherent as d, " . MAIN_DB_PREFIX . "subscription as c"; + $sql .= " WHERE d.entity IN (" . getEntity('adherent') . ")"; + $sql .= " AND d.rowid = c.fk_adherent"; + + + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num) { + $objp = $this->db->fetch_object($result); + $year = dol_print_date($this->db->jdate($objp->dateh), "%Y"); + $Total[$year] = (isset($Total[$year]) ? $Total[$year] : 0) + $objp->subscription; + $Number[$year] = (isset($Number[$year]) ? $Number[$year] : 0) + 1; + $tot += $objp->subscription; + $numb += 1; + $i++; + } + + + $line = 0; + $this->info_box_contents[$line][] = array( + 'td' => 'class="liste_titre"', + 'text' => $langs->trans("Year"), + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => $langs->trans("Subscriptions"), + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => $langs->trans("AmountTotal"), + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => $langs->trans("AmountAverage"), + ); + + $line++; + + krsort($Total); + $i = 0; + foreach ($Total as $key => $value) { + if ($i >= 8) { + // print ''; + // print "..."; + // print ""; + // print ""; + // print ""; + // print "\n"; + $this->info_box_contents[$line][] = array( + 'td' => 'class="tdoverflowmax150 maxwidth150onsmartphone"', + 'text' => '...', + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => '', + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => '', + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => '', + ); + $line++; + break; + } + $this->info_box_contents[$line][] = array( + 'td' => 'class="tdoverflowmax150 maxwidth150onsmartphone"', + 'text' => ''.$key.'', + 'asis' => 1, + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => $Number[$key], + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => price($value), + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="right"', + 'text' => price(price2num($value / $Number[$key], 'MT')), + ); + $line++; + } + + if ($num == 0) { + $this->info_box_contents[$line][0] = array( + 'td' => 'class="center"', + 'text' => $langs->trans("NoRecordedMembers"), + ); + } else { + $this->info_box_contents[$line][] = array( + 'td' => 'class="liste_total"', + 'text' => $langs->trans("Total"), + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="liste_total right"', + 'text' => $numb, + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="liste_total right"', + 'text' => price($tot), + ); + $this->info_box_contents[$line][] = array( + 'td' => 'class="liste_total right"', + 'text' => price(price2num($numb > 0 ? ($tot / $numb) : 0, 'MT')), + ); + } + } else { + $this->info_box_contents[0][0] = array( + 'td' => '', + 'maxlength' => 500, + 'text' => ($this->db->error() . ' sql=' . $sql), + ); + } + } else { + $this->info_box_contents[0][0] = array( + 'td' => 'class="nohover opacitymedium left"', + 'text' => $langs->trans("ReadPermissionNotAllowed") + ); + } + } + + /** + * Method to show box + * + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @param int $nooutput No print, only return string + * @return string + */ + public function showBox($head = null, $contents = null, $nooutput = 0) + { + return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); + } +} diff --git a/htdocs/core/boxes/modules_boxes.php b/htdocs/core/boxes/modules_boxes.php index 379a65b7a5d..b7b9d979174 100644 --- a/htdocs/core/boxes/modules_boxes.php +++ b/htdocs/core/boxes/modules_boxes.php @@ -109,6 +109,12 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" box */ public $note; + /** + * @var string Widget type ('graph' means the widget is a graph widget) + */ + public $widgettype = ''; + + /** * Constructor * diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index 0d235a21798..863bb9a6794 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -578,7 +578,8 @@ class CMailFile $hookmanager = new HookManager($db); $hookmanager->initHooks(array('mail')); - $parameters = array(); $action = ''; + $parameters = array(); + $action = ''; $reshook = $hookmanager->executeHooks('sendMail', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) { $this->error = "Error in hook maildao sendMail ".$reshook; @@ -815,7 +816,8 @@ class CMailFile $this->smtps->setHost($server); $this->smtps->setPort($port); // 25, 465...; - $loginid = ''; $loginpass = ''; + $loginid = ''; + $loginpass = ''; if (!empty($conf->global->$keyforsmtpid)) { $loginid = $conf->global->$keyforsmtpid; $this->smtps->setID($loginid); @@ -946,7 +948,8 @@ class CMailFile return 'Bad value for sendmode'; } - $parameters = array(); $action = ''; + $parameters = array(); + $action = ''; $reshook = $hookmanager->executeHooks('sendMailAfter', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) { $this->error = "Error in hook maildao sendMailAfter ".$reshook; diff --git a/htdocs/core/class/CSMSFile.class.php b/htdocs/core/class/CSMSFile.class.php index 65cf7091d39..ca221a366ed 100644 --- a/htdocs/core/class/CSMSFile.class.php +++ b/htdocs/core/class/CSMSFile.class.php @@ -151,7 +151,8 @@ class CSMSFile } } elseif (!empty($conf->global->MAIN_SMS_SENDMODE)) { // $conf->global->MAIN_SMS_SENDMODE looks like a value 'class@module' $tmp = explode('@', $conf->global->MAIN_SMS_SENDMODE); - $classfile = $tmp[0]; $module = (empty($tmp[1]) ? $tmp[0] : $tmp[1]); + $classfile = $tmp[0]; + $module = (empty($tmp[1]) ? $tmp[0] : $tmp[1]); dol_include_once('/'.$module.'/class/'.$classfile.'.class.php'); try { $classname = ucfirst($classfile); diff --git a/htdocs/core/class/ccountry.class.php b/htdocs/core/class/ccountry.class.php index 1c886a526ed..4f448845e80 100644 --- a/htdocs/core/class/ccountry.class.php +++ b/htdocs/core/class/ccountry.class.php @@ -130,7 +130,8 @@ class Ccountry // extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } if (!$error) { @@ -239,14 +240,15 @@ class Ccountry // extends CommonObject $sql .= " code_iso=".(isset($this->code_iso) ? "'".$this->db->escape($this->code_iso)."'" : "null").","; $sql .= " label=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").","; $sql .= " active=".(isset($this->active) ? $this->active : "null").""; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } // Commit or rollback @@ -277,14 +279,15 @@ class Ccountry // extends CommonObject $error = 0; $sql = "DELETE FROM ".MAIN_DB_PREFIX."c_country"; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } // Commit or rollback diff --git a/htdocs/core/class/comment.class.php b/htdocs/core/class/comment.class.php index 3f9ca42e136..78f168fd8f7 100644 --- a/htdocs/core/class/comment.class.php +++ b/htdocs/core/class/comment.class.php @@ -141,7 +141,8 @@ class Comment extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } if (!$error) { @@ -261,14 +262,15 @@ class Comment extends CommonObject $sql .= " fk_user_modif=".$user->id.","; $sql .= " entity=".(!empty($this->entity) ? $this->entity : '1').","; $sql .= " import_key=".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null"); - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $this->db->begin(); dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } if (!$error) { @@ -314,11 +316,12 @@ class Comment extends CommonObject $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $resql = $this->db->query($sql); if (!$resql) { - $error++; $this->errors[] = "Error ".$this->db->lasterror(); + $error++; + $this->errors[] = "Error ".$this->db->lasterror(); } if (!$error) { diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index ecbfdc94454..0f3865f54a7 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -786,6 +786,14 @@ abstract class CommonDocGenerator $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs); + // Load product data optional fields to the line -> enables to use "line_product_options_{extrafield}" + if (isset($line->fk_product) && $line->fk_product > 0) { + $tmpproduct = new Product($this->db); + $tmpproduct->fetch($line->fk_product); + foreach ($tmpproduct->array_options as $key=>$label) + $resarray["line_product_".$key] = $label; + } + return $resarray; } diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index fc4e2058273..6366cf52756 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -632,9 +632,8 @@ abstract class CommonInvoice extends CommonObject $datelim = $this->date + ($cdr_nbjour * 3600 * 24); $datelim += ($cdr_decalage * 3600 * 24); - } - // 1 : application of the "end of the month" rule - elseif ($cdr_type == 1) { + } elseif ($cdr_type == 1) { + // 1 : application of the "end of the month" rule $datelim = $this->date + ($cdr_nbjour * 3600 * 24); $mois = date('m', $datelim); @@ -650,9 +649,8 @@ abstract class CommonInvoice extends CommonObject $datelim -= (3600 * 24); $datelim += ($cdr_decalage * 3600 * 24); - } - // 2 : application of the rule, the N of the current or next month - elseif ($cdr_type == 2 && !empty($cdr_decalage)) { + } elseif ($cdr_type == 2 && !empty($cdr_decalage)) { + // 2 : application of the rule, the N of the current or next month include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $datelim = $this->date + ($cdr_nbjour * 3600 * 24); @@ -877,6 +875,13 @@ abstract class CommonInvoiceLine extends CommonObjectLine */ public $subprice; + /** + * Unit price before taxes + * @var float + * @deprecated + */ + public $price; + /** * Id of corresponding product * @var int @@ -907,12 +912,31 @@ abstract class CommonInvoiceLine extends CommonObjectLine */ public $localtax2_tx; + /** + * Local tax 1 type + * @var string + */ + public $localtax1_type; + + /** + * Local tax 2 type + * @var string + */ + public $localtax2_type; + /** * Percent of discount * @var float */ public $remise_percent; + /** + * Fixed discount + * @var float + * @deprecated + */ + public $remise; + /** * Total amount before taxes * @var float @@ -946,6 +970,13 @@ abstract class CommonInvoiceLine extends CommonObjectLine public $date_start_fill; // If set to 1, when invoice is created from a template invoice, it will also auto set the field date_start at creation public $date_end_fill; // If set to 1, when invoice is created from a template invoice, it will also auto set the field date_end at creation + public $buy_price_ht; + public $buyprice; // For backward compatibility + public $pa_ht; // For backward compatibility + + public $marge_tx; + public $marque_tx; + /** * List of cumulative options: * Bit 0: 0 for common VAT - 1 if VAT french NPR @@ -962,4 +993,7 @@ abstract class CommonInvoiceLine extends CommonObjectLine public $multicurrency_total_ht; public $multicurrency_total_tva; public $multicurrency_total_ttc; + + public $fk_user_author; + public $fk_user_modif; } diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 06f2531cbb5..5ff380a8b69 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -762,7 +762,8 @@ abstract class CommonObject $out .= img_picto($langs->trans("Address"), 'map-marker-alt'); $out .= ' '; } - $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); $outdone++; + $out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); + $outdone++; $outdone++; // List of extra languages @@ -1181,7 +1182,8 @@ abstract class CommonObject if (!$notrigger) { $result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user); if ($result < 0) { - $this->db->rollback(); return -1; + $this->db->rollback(); + return -1; } } @@ -1617,6 +1619,9 @@ abstract class CommonObject if ($idtofetch) { $thirdparty = new Societe($this->db); $result = $thirdparty->fetch($idtofetch); + if ($result<0) { + $this->errors=array_merge($this->errors, $thirdparty->errors); + } $this->thirdparty = $thirdparty; // Use first price level if level not defined for third party @@ -1845,7 +1850,7 @@ abstract class CommonObject $result = false; if (!empty($id) && !empty($field) && !empty($table)) { $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table; - $sql .= " WHERE rowid = ".$id; + $sql .= " WHERE rowid = ".((int) $id); dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG); $resql = $this->db->query($sql); @@ -2235,10 +2240,13 @@ abstract class CommonObject if (get_class($this) == 'Tva') { $fieldname = 'fk_typepayment'; } + if (get_class($this) == 'Salary') { + $fieldname = 'fk_typepayment'; + } $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL'); - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); if ($this->db->query($sql)) { $this->mode_reglement_id = $id; @@ -2273,7 +2281,7 @@ abstract class CommonObject $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'"; - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); if ($this->db->query($sql)) { $this->multicurrency_code = $code; @@ -2311,7 +2319,7 @@ abstract class CommonObject $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= ' SET '.$fieldname.' = '.$rate; - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); if ($this->db->query($sql)) { $this->multicurrency_tx = $rate; @@ -2519,7 +2527,7 @@ abstract class CommonObject $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL'); - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); if ($this->db->query($sql)) { $this->cond_reglement_id = $id; @@ -2561,7 +2569,7 @@ abstract class CommonObject $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL'); - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); if ($this->db->query($sql)) { $this->transport_mode_id = $id; @@ -2596,7 +2604,7 @@ abstract class CommonObject $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= ' SET '.$fieldname.' = '.$id; - $sql .= ' WHERE rowid='.$this->id; + $sql .= ' WHERE rowid='.((int) $this->id); if ($this->db->query($sql)) { $this->retained_warranty_fk_cond_reglement = $id; @@ -2674,7 +2682,7 @@ abstract class CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; $sql .= " SET fk_shipping_method = ".$shipping_method_id; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $resql = $this->db->query($sql); if (!$resql) { dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG); @@ -2721,7 +2729,7 @@ abstract class CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; $sql .= " SET fk_warehouse = ".$warehouse_id; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); if ($this->db->query($sql)) { $this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id; @@ -2798,7 +2806,7 @@ abstract class CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; $sql .= " SET fk_account = ".$fk_account; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".((int) $this->id); $resql = $this->db->query($sql); if (!$resql) { @@ -3154,9 +3162,8 @@ abstract class CommonObject return $this->getRangOfLine($fk_parent_line); } } - } - // If not, search the last rang of element - else { + } else { + // If not, search the last rang of element $sql = 'SELECT max('.$positionfield.') FROM '.MAIN_DB_PREFIX.$this->table_element_line; $sql .= ' WHERE '.$this->fk_element.' = '.$this->id; @@ -3745,42 +3752,60 @@ abstract class CommonObject if ($objecttype == 'facture') { $classpath = 'compta/facture/class'; } elseif ($objecttype == 'facturerec') { - $classpath = 'compta/facture/class'; $module = 'facture'; + $classpath = 'compta/facture/class'; + $module = 'facture'; } elseif ($objecttype == 'propal') { $classpath = 'comm/propal/class'; } elseif ($objecttype == 'supplier_proposal') { $classpath = 'supplier_proposal/class'; } elseif ($objecttype == 'shipping') { - $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon'; + $classpath = 'expedition/class'; + $subelement = 'expedition'; + $module = 'expedition_bon'; } elseif ($objecttype == 'delivery') { - $classpath = 'delivery/class'; $subelement = 'delivery'; $module = 'delivery_note'; + $classpath = 'delivery/class'; + $subelement = 'delivery'; + $module = 'delivery_note'; } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') { - $classpath = 'fourn/class'; $module = 'fournisseur'; + $classpath = 'fourn/class'; + $module = 'fournisseur'; } elseif ($objecttype == 'fichinter') { - $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter'; + $classpath = 'fichinter/class'; + $subelement = 'fichinter'; + $module = 'ficheinter'; } elseif ($objecttype == 'subscription') { - $classpath = 'adherents/class'; $module = 'adherent'; + $classpath = 'adherents/class'; + $module = 'adherent'; } elseif ($objecttype == 'contact') { $module = 'societe'; } // Set classfile - $classfile = strtolower($subelement); $classname = ucfirst($subelement); + $classfile = strtolower($subelement); + $classname = ucfirst($subelement); if ($objecttype == 'order') { - $classfile = 'commande'; $classname = 'Commande'; + $classfile = 'commande'; + $classname = 'Commande'; } elseif ($objecttype == 'invoice_supplier') { - $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur'; + $classfile = 'fournisseur.facture'; + $classname = 'FactureFournisseur'; } elseif ($objecttype == 'order_supplier') { - $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur'; + $classfile = 'fournisseur.commande'; + $classname = 'CommandeFournisseur'; } elseif ($objecttype == 'supplier_proposal') { - $classfile = 'supplier_proposal'; $classname = 'SupplierProposal'; + $classfile = 'supplier_proposal'; + $classname = 'SupplierProposal'; } elseif ($objecttype == 'facturerec') { - $classfile = 'facture-rec'; $classname = 'FactureRec'; + $classfile = 'facture-rec'; + $classname = 'FactureRec'; } elseif ($objecttype == 'subscription') { - $classfile = 'subscription'; $classname = 'Subscription'; + $classfile = 'subscription'; + $classname = 'Subscription'; } elseif ($objecttype == 'project' || $objecttype == 'projet') { - $classpath = 'projet/class'; $classfile = 'project'; $classname = 'Project'; + $classpath = 'projet/class'; + $classfile = 'project'; + $classname = 'Project'; } // Here $module, $classfile and $classname are set @@ -4151,7 +4176,7 @@ abstract class CommonObject $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element; $sql .= " WHERE entity IN (".getEntity($this->element).")"; if (!empty($id)) { - $sql .= " AND rowid = ".$id; + $sql .= " AND rowid = ".((int) $id); } if (!empty($ref)) { $sql .= " AND ref = '".$this->db->escape($ref)."'"; @@ -4618,7 +4643,8 @@ abstract class CommonObject $element = $this->element; - $text = ''; $description = ''; + $text = ''; + $description = ''; // Line in view mode if ($action != 'editline' || $selected != $line->id) { @@ -4985,7 +5011,8 @@ abstract class CommonObject if (!$notrigger) { $result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user); if ($result < 0) { - $this->db->rollback(); return -1; + $this->db->rollback(); + return -1; } } $this->db->commit(); @@ -5106,7 +5133,8 @@ abstract class CommonObject $tmpdir = trim($tmpdir); $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir); if (!$tmpdir) { - unset($listofdir[$key]); continue; + unset($listofdir[$key]); + continue; } if (is_dir($tmpdir)) { $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0); @@ -5679,7 +5707,7 @@ abstract class CommonObject return 0; } } else { - dol_print_error($this->db); + $this->errors[]=$this->db->lasterror; return -1; } } @@ -6343,6 +6371,7 @@ abstract class CommonObject $out = ''; $type = ''; + $isDependList=0; $param = array(); $param['options'] = array(); $reg = array(); @@ -6381,6 +6410,7 @@ abstract class CommonObject $type = $this->fields[$key]['type']; } + $label = $this->fields[$key]['label']; //$elementtype=$this->fields[$key]['elementtype']; // Seems not used $default = $this->fields[$key]['default']; @@ -6428,11 +6458,10 @@ abstract class CommonObject } } - if (in_array($type, array('date', 'datetime'))) { + if (in_array($type, array('date'))) { $tmp = explode(',', $size); $newsize = $tmp[0]; - - $showtime = in_array($type, array('datetime')) ? 1 : 0; + $showtime = 0; // Do not show current date when field not required (see selectDate() method) if (!$required && $value == '') { @@ -6441,6 +6470,16 @@ abstract class CommonObject // TODO Must also support $moreparam $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1); + } elseif (in_array($type, array('datetime'))) { + $tmp = explode(',', $size); + $newsize = $tmp[0]; + $showtime = 1; + + // Do not show current date when field not required (see selectDate() method) + if (!$required && $value == '') $value = '-1'; + + // TODO Must also support $moreparam + $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel'); } elseif (in_array($type, array('duration'))) { $out = $form->select_duration($keyprefix.$key.$keysuffix, $value, 0, 'text', 0, 1); } elseif (in_array($type, array('int', 'integer'))) { @@ -6489,7 +6528,7 @@ abstract class CommonObject $out = ' '; } elseif ($type == 'select') { $out = ''; - if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) { + if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); } @@ -6511,7 +6550,7 @@ abstract class CommonObject $out .= ''; } elseif ($type == 'sellist') { $out = ''; - if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) { + if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; $out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0); } @@ -6529,7 +6568,6 @@ abstract class CommonObject // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid'); - if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) { if (strpos($InfoFieldList[4], 'extra.') !== false) { $keyList = 'main.'.$InfoFieldList[2].' as rowid'; @@ -6633,6 +6671,7 @@ abstract class CommonObject if (!empty($InfoFieldList[3]) && $parentField) { $parent = $parentName.':'.$obj->{$parentField}; + $isDependList=1; } $out .= '